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: a stream's pieces several at once (#531) (#544)

Ahmed Nefzaoui09ec4704a23a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8e9e90b0..6e010d9b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Added
+- Videos a site sends in pieces (HLS and DASH streams, as many sites other than YouTube do) download several pieces at once, as many as **Options → Connection** gives a file (8 by default): against a test server that slows each connection, 4 at once took under a third of the time, 8 under a fifth. With a speed limit on, they still come one at a time, so the limit holds; a video in one file, as most of YouTube's are, is unchanged. The command line's `video-get` and `playlist-get` take `-c` for it ([#531](https://github.com/anefzaoui/misterdownloadmanager/issues/531)).
- Linux and macOS: a yt-dlp installed by the system (a package manager, Homebrew) is found and used when MDM has none of its own; **Helpers** can still switch to MDM's own copy, kept up to date ([#452](https://github.com/anefzaoui/misterdownloadmanager/issues/452)).
### Fixed
diff --git a/ROADMAP.md b/ROADMAP.md
index ccd76ab5..510038bd 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -491,6 +491,9 @@ These ship in a later version, when they're ready.
### Being built
+- 🔄 Videos sent in pieces (HLS, DASH) downloading several pieces at once, as many as a file's
+ connections ([#531](https://github.com/anefzaoui/misterdownloadmanager/issues/531)): in review;
+ a video in one file (most of YouTube's) still comes over one connection
- 🔄 Linux and macOS: the system's yt-dlp used when MDM has none of its own, with Helpers able\n to switch to MDM's copy ([#452](https://github.com/anefzaoui/misterdownloadmanager/issues/452)): in review
- 🔄 macOS: video look-ups in a copy of MDM a browser downloaded, without the Terminal command
([#330](https://github.com/anefzaoui/misterdownloadmanager/issues/330),
diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs
index c4e94cd3..ab1f6913 100644
--- a/crates/app/src/app.rs
+++ b/crates/app/src/app.rs
@@ -3503,6 +3503,12 @@ impl App {
let tool = tools.as_deref().and_then(mdm_tools::installed);
let ffmpeg = tools.as_deref().and_then(mdm_tools::ffmpeg::installed);
let rate = self.settings.speed_limit();
+ // A stream in pieces (HLS, DASH): as many at once as a file's connections (#531).
+ let fragments = self
+ .items
+ .iter()
+ .find(|i| i.id == id)
+ .map_or(1, |i| self.settings.connections_for(&i.url));
let Some(item) = self.item(id) else { return };
let Some(spec) = item.video.clone() else {
return;
@@ -3532,6 +3538,7 @@ impl App {
&folder,
&stem,
rate,
+ fragments,
ffmpeg.as_ref().map(|f| f.exe.as_path()),
item.size,
&crate::videodlg::from_browser(&item.context),
diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs
index 23b76c2f..2253dd0b 100644
--- a/crates/cli/src/lib.rs
+++ b/crates/cli/src/lib.rs
@@ -123,6 +123,11 @@ enum Cmd {
/// Put the subtitles into the video file instead of beside it (needs ffmpeg; MP4/MKV).
#[arg(long)]
embed_subs: bool,
+ /// A stream in pieces (HLS, DASH): this many pieces at once (1 to 128), as `get`'s
+ /// connections; a plain file is one connection whatever this says.
+ #[arg(short, long, default_value_t = Options::default().max_connections,
+ value_parser = clap::value_parser!(u32).range(1..=MAX_CONNECTIONS_UNLOCKED as i64))]
+ connections: u32,
/// The network adapter yt-dlp (and the ffmpeg it starts) goes through (#35), as
/// `get --adapter`.
#[arg(long)]
@@ -150,6 +155,11 @@ enum Cmd {
/// Folder to save into: a folder named after the list is made there.
#[arg(short, long, default_value = ".")]
output: PathBuf,
+ /// A stream in pieces (HLS, DASH): this many pieces at once (1 to 128), as `get`'s
+ /// connections; a plain file is one connection whatever this says.
+ #[arg(short, long, default_value_t = Options::default().max_connections,
+ value_parser = clap::value_parser!(u32).range(1..=MAX_CONNECTIONS_UNLOCKED as i64))]
+ connections: u32,
/// The first entry (from 1).
#[arg(long, default_value_t = 1)]
from: u64,
@@ -685,6 +695,7 @@ async fn run(cmd: Cmd, json: bool, accounts: Option<&dyn Accounts>) -> anyhow::R
url,
format,
output,
+ connections,
from,
count,
} => {
@@ -734,6 +745,7 @@ async fn run(cmd: Cmd, json: bool, accounts: Option<&dyn Accounts>) -> anyhow::R
&folder,
&stem,
None,
+ connections,
ffmpeg.as_deref(),
None,
&Default::default(),
@@ -901,6 +913,7 @@ async fn run(cmd: Cmd, json: bool, accounts: Option<&dyn Accounts>) -> anyhow::R
subs,
auto_subs,
embed_subs,
+ connections,
adapter,
} => {
if let Some(a) = adapter {
@@ -931,6 +944,7 @@ async fn run(cmd: Cmd, json: bool, accounts: Option<&dyn Accounts>) -> anyhow::R
&output,
&stem,
None,
+ connections,
ffmpeg.as_deref(),
// No size shown here: the progress steadies itself (video::Meter).
None,
diff --git a/crates/tools/src/video.rs b/crates/tools/src/video.rs
index 52fa89b7..e19aa390 100644
--- a/crates/tools/src/video.rs
+++ b/crates/tools/src/video.rs
@@ -426,8 +426,14 @@ pub const MAX_WHILE_RUNNING: f64 = 0.999;
/// fragment: the streams are added up, the total never falls below the size the video window
/// showed (`expected`, every stream), and the fraction done goes back only when a stream's end
/// had looked like the whole (no `expected`, the next stream starts).
+///
+/// Pieces fetched several at once ([`pace_args`]) report from each at its turn: the count can
+/// step back a little, which isn't a new stream (#531: one taken for it added a 25 MB estimate,
+/// and a 6 MB video read 66 MB). Then only a fall to under half of it, by 64 KB or more, is.
struct Meter {
expected: Option<u64>,
+ /// Pieces at once: the count may step back.
+ at_once: bool,
/// The streams already finished, and the current one's last total and bytes.
finished: u64,
last_total: u64,
@@ -437,9 +443,10 @@ struct Meter {
}
impl Meter {
- fn new(expected: Option<u64>) -> Self {
+ fn new(expected: Option<u64>, at_once: bool) -> Self {
Meter {
expected: expected.filter(|e| *e > 0),
+ at_once,
finished: 0,
last_total: 0,
last_got: 0,
@@ -457,7 +464,12 @@ impl Meter {
.or(f.get(2).copied().flatten())
.map(|t| t.max(0.0) as u64);
// Back near 0: the next stream started; the one before counts in full.
- if got < self.last_got && self.last_got > 0 {
+ let next_stream = if self.at_once {
+ got.saturating_mul(2) < self.last_got && self.last_got - got >= 64 * 1024
+ } else {
+ got < self.last_got
+ };
+ if next_stream && self.last_got > 0 {
self.finished += self.last_total.max(self.last_got);
self.last_total = 0;
// Without the whole size from the start, the first stream's end looked like the
@@ -697,7 +709,8 @@ fn attempt(
return failed(format!("Cannot write the video information: {e}"), rerouted);
}
let _cleanup = Remove(file.clone());
- let mut meter = Meter::new(expected);
+ let at_once = ours.iter().any(|a| a == "--concurrent-fragments");
+ let mut meter = Meter::new(expected, at_once);
let ran = match run(exe, ours, &file, progress, child, Some(&mut meter)) {
Ok(Some(r)) => r,
Ok(None) => return Attempt::Stopped,
@@ -818,6 +831,19 @@ fn template_text(s: &str) -> String {
s.replace('%', "%%")
}
+/// yt-dlp's speed: at most `rate` bytes/s; a stream in pieces (HLS, DASH) `fragments` pieces at
+/// once, as a file comes down over several connections (Options → Connection, #531). yt-dlp uses
+/// that for such streams only (a plain file stays one connection), and its limit holds for each
+/// piece, not for them together: with a limit, one piece at a time, so the limit stays the
+/// download's, whatever the format turns out to be.
+pub fn pace_args(rate: Option<u64>, fragments: u32) -> Vec<String> {
+ match rate {
+ Some(r) => vec!["--limit-rate".into(), r.to_string()],
+ None if fragments > 1 => vec!["--concurrent-fragments".into(), fragments.to_string()],
+ None => Vec::new(),
+ }
+}
+
/// Our progress line: `MDMP <downloaded> <total> <estimate> <speed>` (`NA` when unknown).
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>`.
@@ -827,8 +853,8 @@ const FINAL: &str = "after_move:MDMF %(filepath)s";
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;
- /// `ffmpeg` (its exe) merges separate video and audio into an MP4. `expected`: the size the
+ /// Download `url` in format `selector` to `dir/<stem>.<ext>`, at most `rate` bytes/s, a
+ /// stream in pieces `fragments` pieces at once ([`pace_args`]); `ffmpeg` (its exe) merges separate video and audio into an MP4. `expected`: the size the
/// choice was shown with (every stream), so the progress starts from the whole. `browser`:
/// what the browser's request for the page carried (proc::FromBrowser). `subs`: the
/// subtitles to save with it (#68; none for a sound alone, which has no picture to put them
@@ -841,6 +867,7 @@ impl VideoJob {
dir: &Path,
stem: &str,
rate: Option<u64>,
+ fragments: u32,
ffmpeg: Option<&Path>,
expected: Option<u64>,
browser: &proc::FromBrowser,
@@ -874,9 +901,7 @@ impl VideoJob {
"--print".into(),
QUALITY.into(),
];
- if let Some(r) = rate {
- ours.extend(["--limit-rate".into(), r.to_string()]);
- }
+ ours.extend(pace_args(rate, fragments));
// A subtitles-only second run, for the ones a site refuses (#68): the same output name.
let mut retry_base: Vec<String> = vec![
"-o".into(),
@@ -992,6 +1017,18 @@ impl VideoJob {
mod tests {
use super::*;
+ /// #531: a stream in pieces comes down several at once, as many as a file's connections;
+ /// with a speed limit one at a time, as yt-dlp's limit holds for each piece (measured
+ /// against the lab server: `--limit-rate 512K -N 4` took a quarter of the time).
+ #[test]
+ fn fragments_at_once_unless_the_speed_is_limited() {
+ let s = |v: Vec<String>| v.join(" ");
+ assert_eq!(s(pace_args(None, 8)), "--concurrent-fragments 8");
+ assert_eq!(s(pace_args(None, 1)), "");
+ assert_eq!(s(pace_args(None, 0)), "");
+ assert_eq!(s(pace_args(Some(524_288), 8)), "--limit-rate 524288");
+ }
+
/// Live (network, yt-dlp): `MDM_LIVE_YTDLP=<yt-dlp.exe> MDM_LIVE_PAGE=<video page>
/// cargo test -p mdm-tools live_download -- --ignored --nocapture`. Downloads the smallest
/// audio and prints the log (a swapped server shows there).
@@ -1010,6 +1047,7 @@ mod tests {
dir.path(),
"a",
None,
+ 1,
ffmpeg.as_deref(),
None,
&Default::default(),
@@ -1052,6 +1090,7 @@ mod tests {
dir.path(),
"clip",
None,
+ 1,
None,
None,
&Default::default(),
@@ -1081,6 +1120,7 @@ mod tests {
dir.path(),
"clip",
None,
+ 1,
None,
None,
&Default::default(),
@@ -1101,7 +1141,11 @@ mod tests {
}
fn run(expected: Option<u64>, lines: &[&str]) -> Vec<(u64, Option<u64>)> {
- let mut m = Meter::new(expected);
+ run_with(expected, false, lines)
+ }
+
+ fn run_with(expected: Option<u64>, at_once: bool, lines: &[&str]) -> Vec<(u64, Option<u64>)> {
+ let mut m = Meter::new(expected, at_once);
let mut p = Progress {
state: State::Running,
downloaded: 0,
@@ -1149,6 +1193,42 @@ mod tests {
assert!(f[f.len() - 1] > 0.99, "{f:?}");
}
+ /// #531: yt-dlp's lines with 8 pieces at once (real ones, from the lab server's HLS stream of
+ /// 6 MB), its count stepping back now and then: never more than the file, and the end is
+ /// the file. A second stream (the sound after the picture) still adds up.
+ #[test]
+ fn pieces_at_once_step_back_without_a_new_stream() {
+ let lines = [
+ "30720 NA 6905856.0 5636",
+ "26624 NA 6905856.0 5636",
+ "1304576 NA 37576704.0 911582",
+ "1961984 NA 25104384.0 911582",
+ "1830912 NA 25104384.0 911582",
+ "4061184 NA 8382464.0 1683967",
+ "3929088 NA 8382464.0 1683967",
+ "6289408 NA 7704576.0 1883540",
+ "6158336 NA 7704576.0 1883540",
+ "6291456 NA 6553600.0 1883540",
+ ];
+ let v = run_with(None, true, &lines);
+ for (d, _) in &v {
+ assert!(*d <= 6_291_456, "more than the file: {v:?}");
+ }
+ assert_eq!(v.last().unwrap().0, 6_291_456);
+ // Before, the first step back counted the 6.9 MB estimate as a finished stream.
+ assert!(run(None, &lines).iter().any(|(d, _)| *d > 6_291_456));
+ let two = run_with(
+ None,
+ true,
+ &[
+ "4000000 4000000 NA 5",
+ "1024 NA 900000 5",
+ "900000 900000 NA 5",
+ ],
+ );
+ assert_eq!(two.last().unwrap().0, 4_900_000, "{two:?}");
+ }
+
/// The file size stays the file's size at the end: holding the bar short of 100 % is the
/// window's (`Item::fraction`), not a total made 0.1 % too big (100.100 MB for 100 MB).
#[test]
diff --git a/crates/tools/tests/cookies.rs b/crates/tools/tests/cookies.rs
index ce6b891b..827beb5e 100644
--- a/crates/tools/tests/cookies.rs
+++ b/crates/tools/tests/cookies.rs
@@ -71,6 +71,7 @@ fn download(exe: &std::path::Path, url: &str, browser: &FromBrowser) -> (State,
dir.path(),
"clip",
None,
+ 1,
None,
None,
browser,
diff --git a/crates/tools/tests/fake_ytdlp.rs b/crates/tools/tests/fake_ytdlp.rs
index f811b0fc..b7af6e0d 100644
--- a/crates/tools/tests/fake_ytdlp.rs
+++ b/crates/tools/tests/fake_ytdlp.rs
@@ -274,6 +274,7 @@ fn download_as(
out.path(),
stem,
None,
+ 1,
None,
None,
&Default::default(),
diff --git a/docs/command-line.md b/docs/command-line.md
index 4c5fe3d6..3cc59fda 100644
--- a/docs/command-line.md
+++ b/docs/command-line.md
@@ -50,8 +50,8 @@ It comes with every download of MDM, next to the app (the installer puts it in M
| `gallery-get URL [-o folder] [--limit N] [--adapter name]` | Download a gallery's pictures (a Wikimedia Commons category, a Flickr album, ...) into a folder named after it inside `-o`; `--limit` takes at most that many, the first the site lists. Started again, it fetches only the new ones. `--adapter` sends gallery-dl's connections through one network adapter, as for `get`. |
| `video-info URL` | What video a page holds (YouTube, Vimeo, ...), and the qualities to choose from. |
| `playlist-info URL [--from N] [--count N]` | A playlist's or channel's videos, one line each as they're listed: its place, length, title and address. |
-| `playlist-get URL [-f selector] [-o folder] [--from N] [--count N]` | Download a playlist's or channel's videos one after another, into a folder named after the list inside `-o`. `-f` is one quality for all, as for `video-get` (by default each video's best; `bv*[height<=720]+ba/b[height<=720]` = up to 720p; `ba` = the original sound; `mp3:320`, `opus:`, `flac:` as for `video-get`). |
-| `video-get URL [-f selector] [-o folder] [--subs langs] [--auto-subs] [--embed-subs] [--adapter name]` | Download a video; `-f` takes a quality's selector from `video-info` (`b` = the best single file; `ba` = the sound alone as the site has it, not converted; `mp3:320`, `mp3:256`, `mp3:192` or `mp3:128` = the sound as an MP3 at that bitrate, `mp3:0` at its best variable one; `opus:` = as Opus; `flac:` = as FLAC, lossless but no better than the site's sound; conversions need ffmpeg). `--subs` saves subtitles beside it: language codes from `video-info` (`en,fr`), or `all` for every one the uploader gave; `--auto-subs` takes the site's automatic captions instead; `--embed-subs` puts them into the video (needs ffmpeg, MP4 or MKV). `--adapter` sends yt-dlp's connections (and ffmpeg's) through one network adapter, as for `get`; when it isn't connected, nothing starts. |
+| `playlist-get URL [-f selector] [-o folder] [-c pieces] [--from N] [--count N]` | Download a playlist's or channel's videos one after another, into a folder named after the list inside `-o`. `-f` is one quality for all, as for `video-get` (by default each video's best; `bv*[height<=720]+ba/b[height<=720]` = up to 720p; `ba` = the original sound; `mp3:320`, `opus:`, `flac:` as for `video-get`). `-c` as for `video-get`. |
+| `video-get URL [-f selector] [-o folder] [-c pieces] [--subs langs] [--auto-subs] [--embed-subs] [--adapter name]` | Download a video; `-f` takes a quality's selector from `video-info` (`b` = the best single file; `ba` = the sound alone as the site has it, not converted; `mp3:320`, `mp3:256`, `mp3:192` or `mp3:128` = the sound as an MP3 at that bitrate, `mp3:0` at its best variable one; `opus:` = as Opus; `flac:` = as FLAC, lossless but no better than the site's sound; conversions need ffmpeg). `-c`: a video the site sends in pieces (HLS, DASH) comes down this many pieces at once (8 by default, 1 to 128); a video in one file is one connection whatever it says. `--subs` saves subtitles beside it: language codes from `video-info` (`en,fr`), or `all` for every one the uploader gave; `--auto-subs` takes the site's automatic captions instead; `--embed-subs` puts them into the video (needs ffmpeg, MP4 or MKV). `--adapter` sends yt-dlp's connections (and ffmpeg's) through one network adapter, as for `get`; when it isn't connected, nothing starts. |
| `install-ytdlp`, `install-ffmpeg` | Install or update the helpers videos need: yt-dlp (checked against its signing key) and ffmpeg (Windows; on macOS and Linux MDM uses the system's). |
| `torrent-info SOURCE` | A torrent's name, files (numbered) and size; `SOURCE` is a magnet link or a `.torrent` file. |
| `torrent-get SOURCE [-o folder] [--files 0,2] [--use-existing]` | Download a torrent, or only some of its files. If some of its files are already in the folder, it stops and names them; `--use-existing` uses them instead (what matches is kept, the rest downloaded). |