Skip to content

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

Video without ffmpeg: a sound that comes as a file, and HLS pieces saved as what they are (#569) (#593)

Ahmed Nefzaouibbbeb4a08cfd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 588d8830..ef08c3eb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Fixed
+- **Download video** without ffmpeg (on macOS and Linux, where MDM doesn't install it): the sound alone comes from a format the site sends as one file when it has one, and a sound or video that came as an HLS stream's pieces is saved as what it is (`.aac`, `.ts`) instead of `.mp4`, which players refused to open ([#569](https://github.com/anefzaoui/misterdownloadmanager/issues/569)).
- A freeze when the disk was slow: MDM looked on the disk for a portable data folder on every tick of the window; it now works the data folder out once ([#565](https://github.com/anefzaoui/misterdownloadmanager/issues/565)).
- macOS 15 and later: Chinese names and text find the PingFang font again, which moved into the system's font assets, with Hiragino Sans GB and STHeiti as fallbacks ([#541](https://github.com/anefzaoui/misterdownloadmanager/issues/541)).
- The video button follows **Options → General → Customize MDM Download panels in browsers** in the pages already open: switched off, or its site listed, it goes within a few seconds, without reloading the page (it stayed until a reload, and on YouTube, which never reloads, for good). A site listed as `example.com` now takes `www.example.com` and its other subdomains too, and a player embedded from another site follows the site in the address bar ([#532](https://github.com/anefzaoui/misterdownloadmanager/issues/532)).
diff --git a/ROADMAP.md b/ROADMAP.md
index 058bd070..7fc2acda 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -533,6 +533,8 @@ These ship in a later version, when they're ready.
### Bugs being looked into
+- 🔄 Without ffmpeg, YouTube's sound alone saved as `.mp4` though it was raw AAC from HLS pieces,
+ which no player opened ([#569](https://github.com/anefzaoui/misterdownloadmanager/issues/569)): fix in review
- 🔄 A progress window's title bar buttons not answering
([#540](https://github.com/anefzaoui/misterdownloadmanager/issues/540)): a window with a title of
256 characters or more got the system's title bar above MDM's own; that part is fixed, in review.
diff --git a/crates/tools/src/resolve.rs b/crates/tools/src/resolve.rs
index baafba95..abbe6341 100644
--- a/crates/tools/src/resolve.rs
+++ b/crates/tools/src/resolve.rs
@@ -60,6 +60,9 @@ pub struct Format {
pub size: Option<u64>,
/// Kbit/s, when the site says (a stream's variants differ by it alone).
pub tbr: Option<f64>,
+ /// Comes as an HLS stream (yt-dlp's `protocol` `m3u8`, `m3u8_native`): its pieces make a
+ /// proper file only once ffmpeg has put them into one (#569).
+ pub hls: bool,
}
/// One line of the choice list: what to show and what to ask yt-dlp for.
@@ -129,6 +132,7 @@ struct RawFormat {
filesize: Option<u64>,
filesize_approx: Option<u64>,
tbr: Option<f64>,
+ protocol: Option<String>,
}
/// Whether `title` is only the last part of `page`'s address, which is what yt-dlp calls a video
@@ -166,6 +170,7 @@ pub fn parse(json: &[u8]) -> Option<Video> {
fps: f.fps,
size: f.filesize.or(f.filesize_approx),
tbr: f.tbr,
+ hls: f.protocol.as_deref().is_some_and(|p| p.contains("m3u8")),
})
.collect(),
subtitles: tracks(raw.subtitles),
@@ -393,6 +398,39 @@ pub fn needs_merging(v: &Video) -> bool {
best(true) > best(false)
}
+/// A format selector for yt-dlp without ffmpeg (#569): each of its "best" picks (`ba`,
+/// `b[height=720]`) tried first among the formats that come as a file, then as it was. An HLS
+/// stream's pieces are joined as they come: without ffmpeg to put them into the container they
+/// were named for, YouTube's HLS sound is raw AAC under an `.mp4` name, which no player opens
+/// as one. A merge (`bv*+ba`, which needs ffmpeg anyway) and a format named by its ID (the one
+/// asked for) are left as they are.
+pub fn without_remuxing(selector: &str) -> String {
+ const BEST: [&str; 10] = [
+ "b",
+ "ba",
+ "bv",
+ "b*",
+ "ba*",
+ "bv*",
+ "best",
+ "bestaudio",
+ "bestvideo",
+ "best*",
+ ];
+ selector
+ .split('/')
+ .map(|alt| {
+ let base = alt.split('[').next().unwrap_or(alt).trim();
+ if BEST.contains(&base) && !alt.contains('+') && !alt.contains("protocol") {
+ format!("{alt}[protocol!*=m3u8]/{alt}")
+ } else {
+ alt.to_owned()
+ }
+ })
+ .collect::<Vec<_>>()
+ .join("/")
+}
+
/// The choices, best first: each resolution (merged with the best audio when ffmpeg is there,
/// else only formats that carry both), then audio only.
pub fn choices(v: &Video, can_merge: bool) -> Vec<Choice> {
@@ -404,11 +442,12 @@ pub fn choices(v: &Video, can_merge: bool) -> Vec<Choice> {
.collect();
heights.sort_unstable_by(|a, b| b.cmp(a));
heights.dedup();
+ // Without ffmpeg a sound that comes as a file (#569): an HLS one stays its raw pieces.
let best_audio = v
.formats
.iter()
.filter(|f| f.audio && !f.video)
- .max_by_key(|f| f.size.unwrap_or(0));
+ .max_by_key(|f| (can_merge || !f.hls, f.size.unwrap_or(0)));
let mut out: Vec<Choice> = heights
.into_iter()
.map(|h| {
@@ -553,6 +592,7 @@ mod tests {
audio: true,
size: None,
tbr: Some(tbr),
+ hls: false,
};
let v = Video {
title: "t".into(),
@@ -710,6 +750,40 @@ mod tests {
assert!(!needs_merging(&parse(sound.as_bytes()).unwrap()));
}
+ /// #569: YouTube on a Mac with neither ffmpeg nor a JavaScript runtime: its sound as HLS
+ /// streams (the larger) and as a file. Without ffmpeg the file is the choice, and yt-dlp is
+ /// asked for a file first; with ffmpeg the best, HLS or not (ffmpeg makes it a proper file).
+ #[test]
+ fn without_ffmpeg_a_sound_that_comes_as_a_file() {
+ let json = r#"{"title": "T", "formats": [
+ {"format_id": "233", "ext": "mp4", "vcodec": "none", "acodec": "mp4a.40.2", "protocol": "m3u8_native", "filesize_approx": 2000},
+ {"format_id": "140", "ext": "m4a", "vcodec": "none", "acodec": "mp4a.40.2", "protocol": "https", "filesize": 900}]}"#;
+ let v = parse(json.as_bytes()).unwrap();
+ assert!(v.formats[0].hls && !v.formats[1].hls);
+ let without = choices(&v, false);
+ assert_eq!(without[0].label, "Audio only original M4A");
+ assert_eq!(without[0].size, Some(900));
+ assert_eq!(choices(&v, true)[0].size, Some(2000));
+ assert_eq!(without_remuxing("ba"), "ba[protocol!*=m3u8]/ba");
+ assert_eq!(
+ without_remuxing("b[height=360]"),
+ "b[height=360][protocol!*=m3u8]/b[height=360]"
+ );
+ assert_eq!(
+ without_remuxing("bv*[height=720]+ba/b[height=720]"),
+ "bv*[height=720]+ba/b[height=720][protocol!*=m3u8]/b[height=720]"
+ );
+ // A format by its ID, and one already choosing its way, as they are.
+ assert_eq!(without_remuxing("hls-1280"), "hls-1280");
+ assert_eq!(without_remuxing("18"), "18");
+ assert_eq!(without_remuxing("ba[protocol=https]"), "ba[protocol=https]");
+ // Only HLS sound: still offered (it is saved for what it is, video.rs).
+ let hls_only = r#"{"title": "T", "formats": [
+ {"format_id": "233", "ext": "mp4", "vcodec": "none", "acodec": "mp4a.40.2", "protocol": "m3u8_native"}]}"#;
+ let only = choices(&parse(hls_only.as_bytes()).unwrap(), false);
+ assert_eq!(only[0].selector, "ba");
+ }
+
/// #70: what each audio choice converts to; the original and videos convert nothing.
#[test]
fn audio_conversions() {
diff --git a/crates/tools/src/video.rs b/crates/tools/src/video.rs
index e19aa390..fd0975f7 100644
--- a/crates/tools/src/video.rs
+++ b/crates/tools/src/video.rs
@@ -337,6 +337,8 @@ fn supervise(
Attempt::Stopped => return,
Attempt::Done(f, problems, quality) => {
end(child);
+ // Named for what it holds (#569): HLS pieces joined without ffmpeg.
+ let f = named_for_content(f);
if relaxed_to.is_some()
&& let Some(q) = quality
{
@@ -636,6 +638,67 @@ fn saved_by_name(ours: &[String]) -> Option<PathBuf> {
.max_by_key(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok())
}
+/// What a saved file holds when its name says otherwise: an HLS stream's pieces joined as they
+/// came, which only ffmpeg makes into the MP4 they're named for (#569). YouTube's HLS sound is
+/// raw AAC (ADTS frames, each piece led by an ID3 tag with its time): `aac`, which players open.
+/// A video's pieces are an MPEG transport stream: `ts`. A real MP4 (ffmpeg was there, or the
+/// format came as a file) is none of these.
+fn content_ext(head: &[u8]) -> Option<&'static str> {
+ // ID3v2 tags first: a 10-byte header, then the tag's size in 7-bit bytes.
+ let mut at = 0usize;
+ while head.len() >= at + 10 && &head[at..at + 3] == b"ID3" {
+ let size = head[at + 6..at + 10]
+ .iter()
+ .fold(0usize, |n, b| (n << 7) | usize::from(b & 0x7f));
+ let footer = if head[at + 5] & 0x10 != 0 { 10 } else { 0 };
+ at += 10 + size + footer;
+ }
+ let rest = head.get(at..)?;
+ // ADTS: a 12-bit sync word, then MPEG layer 0.
+ if rest.len() >= 7 && rest[0] == 0xff && rest[1] & 0xf6 == 0xf0 {
+ return Some("aac");
+ }
+ // A transport stream: a sync byte every 188 bytes.
+ if at == 0 && head.len() > 376 && [0, 188, 376].iter().all(|&i| head[i] == 0x47) {
+ return Some("ts");
+ }
+ None
+}
+
+/// `f`, renamed for what it holds when its MP4 name is wrong ([`content_ext`]); as it was
+/// otherwise, or when the rename fails (the file is kept).
+fn named_for_content(f: PathBuf) -> PathBuf {
+ let named = f
+ .extension()
+ .map(|e| e.to_string_lossy().to_ascii_lowercase());
+ if !matches!(named.as_deref(), Some("mp4" | "m4a")) {
+ return f;
+ }
+ let mut head = Vec::with_capacity(8192);
+ let read = std::fs::File::open(&f).and_then(|file| {
+ use std::io::Read;
+ file.take(8192).read_to_end(&mut head)
+ });
+ let Some(ext) = read.ok().and_then(|_| content_ext(&head)) else {
+ return f;
+ };
+ let stem = f
+ .file_stem()
+ .unwrap_or_default()
+ .to_string_lossy()
+ .into_owned();
+ let free = (1..100)
+ .map(|n| match n {
+ 1 => f.with_file_name(format!("{stem}.{ext}")),
+ n => f.with_file_name(format!("{stem} ({n}).{ext}")),
+ })
+ .find(|p| !p.exists());
+ match free {
+ Some(to) if std::fs::rename(&f, &to).is_ok() => to,
+ _ => f,
+ }
+}
+
/// 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;
@@ -877,7 +940,15 @@ impl VideoJob {
let output = dir.join(format!("{}.%(ext)s", template_text(stem)));
// An MP3, Opus or FLAC choice (#32, #70): the best sound, converted by ffmpeg.
let convert = crate::resolve::audio_conversion(selector);
- let format = if convert.is_some() { "ba/b" } else { selector };
+ let format = if convert.is_some() {
+ "ba/b".to_owned()
+ } else if ffmpeg.is_none() {
+ // A format that comes as a file first (#569): without ffmpeg an HLS stream stays
+ // its raw pieces.
+ crate::resolve::without_remuxing(selector)
+ } else {
+ selector.to_owned()
+ };
// What comes down is the sound as the site has it, not the file the choice's size
// estimated: the progress follows yt-dlp's own total.
let expected = if convert.is_some() { None } else { expected };
@@ -885,7 +956,7 @@ impl VideoJob {
let with_subs = convert.is_none() && !subs.langs.is_empty();
let mut ours: Vec<String> = vec![
"-f".into(),
- format.into(),
+ format,
"-o".into(),
output.to_string_lossy().into_owned(),
"--no-playlist".into(),
@@ -1017,6 +1088,45 @@ impl VideoJob {
mod tests {
use super::*;
+ /// #569: what a file joined from HLS pieces holds, from its first bytes. YouTube's sound:
+ /// pieces each led by an ID3 tag (Apple's timestamp), then ADTS frames.
+ #[test]
+ fn joined_hls_pieces_are_named_for_what_they_hold() {
+ let mut aac = b"ID3?".to_vec();
+ aac.extend(std::iter::repeat_n(0u8, 0x3f));
+ aac.extend([0xff, 0xf1, 0x50, 0x80, 0x2e, 0x7f, 0xfc]);
+ assert_eq!(content_ext(&aac), Some("aac"));
+ // ADTS with no tag, and MPEG-1 layer 3 (an MP3: not ours to rename).
+ assert_eq!(content_ext(&[0xff, 0xf9, 0x50, 0x80, 0, 0, 0]), Some("aac"));
+ assert_eq!(content_ext(&[0xff, 0xfb, 0x90, 0x64, 0, 0, 0]), None);
+ let mut ts = vec![0u8; 400];
+ for i in [0, 188, 376] {
+ ts[i] = 0x47;
+ }
+ assert_eq!(content_ext(&ts), Some("ts"));
+ // A real MP4 (ffmpeg was there): as it is.
+ let mut mp4 = vec![0, 0, 0, 0x20];
+ mp4.extend(b"ftypisom");
+ mp4.resize(400, 0);
+ assert_eq!(content_ext(&mp4), None);
+
+ let dir = tempfile::tempdir().unwrap();
+ let joined = dir.path().join("Talk.mp4");
+ std::fs::write(&joined, &aac).unwrap();
+ assert_eq!(named_for_content(joined), dir.path().join("Talk.aac"));
+ assert!(dir.path().join("Talk.aac").is_file());
+ // Another Talk.aac there already: not overwritten.
+ std::fs::write(dir.path().join("Talk.mp4"), &aac).unwrap();
+ let second = named_for_content(dir.path().join("Talk.mp4"));
+ assert_eq!(second, dir.path().join("Talk (2).aac"));
+ // A real MP4 keeps its name; so does a sound already named .aac.
+ let real = dir.path().join("Real.mp4");
+ std::fs::write(&real, &mp4).unwrap();
+ assert_eq!(named_for_content(real.clone()), real);
+ let named = dir.path().join("Talk.aac");
+ assert_eq!(named_for_content(named.clone()), named);
+ }
+
/// #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).
diff --git a/crates/tools/tests/fake_ytdlp.rs b/crates/tools/tests/fake_ytdlp.rs
index b7af6e0d..846623ff 100644
Binary files a/crates/tools/tests/fake_ytdlp.rs and b/crates/tools/tests/fake_ytdlp.rs differ