diff --git a/src/downloader.rs b/src/downloader.rs index 0a22b52..abb1d76 100644 --- a/src/downloader.rs +++ b/src/downloader.rs @@ -312,6 +312,29 @@ impl Job { async fn run(&mut self, settings: &Settings, req: &JobRequest, save: &SaveOptions) -> Result> { self.emit("preparing", None, None); + let mut swapped_note = None; + let swapped; + let req = if settings.prefer_official_audio && !matches!(save.save_as, SaveAs::Video) && req.entry.music_video && req.entry.platform == "YouTube" { + let tools = engine::locate(&settings.ytdlp_path, &settings.ffmpeg_path)?; + let artist = if req.meta.artist.trim().is_empty() { req.entry.artist.clone() } else { req.meta.artist.clone() }; + let title = if req.meta.title.trim().is_empty() { req.entry.title.clone() } else { req.meta.title.clone() }; + match crate::media::find_official_audio(settings, &tools, &artist, &title).await { + Some(url) if url != req.entry.url => { + let mut r = req.clone(); + r.entry.url = url; + r.entry.media = None; + swapped = r; + swapped_note = Some("Used the official audio upload instead of the music video's sound.".to_string()); + &swapped + } + _ => { + swapped_note = Some("No official audio upload was found, so the music video's sound was saved.".to_string()); + req + } + } + } else { + req + }; let entry = &req.entry; match entry.availability.as_str() { "drm" => bail!("This stream is DRM-encrypted, so it was skipped. If it's your own track, turn on downloads for it in the platform's track settings (or enable “Use my browser sign-in”), then choose Original file to get your uploaded master."), @@ -346,6 +369,7 @@ impl Job { } }; let mut notes = plan.notes.clone(); + notes.extend(swapped_note); if settings.embed_metadata { self.emit("tagging", None, None); if let Err(e) = tagging::apply(&path, &req.meta, &req.entry.url, tools.ffmpeg.as_deref()).await { diff --git a/src/media.rs b/src/media.rs index e503d47..fea786a 100644 --- a/src/media.rs +++ b/src/media.rs @@ -53,6 +53,7 @@ pub struct Entry { pub availability: String, pub media: Option, pub detailed: bool, + pub music_video: bool, } #[derive(Clone, Debug, Serialize)] @@ -206,6 +207,38 @@ fn best_thumbnail(v: &Value) -> Option { } static DASH: LazyLock = LazyLock::new(|| Regex::new(r"\s+[-–—]\s+").unwrap()); +static MUSIC_VIDEO: LazyLock = LazyLock::new(|| Regex::new(r"(?i)(official\s+(music\s+)?video|music\s+video|\bm/?v\b|video\s+oficial|clipe\s+oficial|official\s+visuali[sz]er)").unwrap()); + +fn same_song(candidate: &str, title: &str) -> bool { + let n = |s: &str| crate::artistinfo::norm(&tidy_title(s)); + let (c, t) = (n(candidate), n(title)); + !t.is_empty() && (c == t || c.contains(&t)) +} + +pub fn pick_official_audio(results: &Value, artist: &str, title: &str) -> Option { + let artist_n = crate::artistinfo::norm(artist); + let list = results["entries"].as_array()?; + let url = |e: &Value| s(&e["url"]).or_else(|| s(&e["webpage_url"])); + let topic = list.iter().find(|e| { + let ch = s(&e["channel"]).or_else(|| s(&e["uploader"])).unwrap_or_default(); + ch.ends_with(" - Topic") && crate::artistinfo::norm(ch.trim_end_matches(" - Topic")) == artist_n && s(&e["title"]).is_some_and(|t| same_song(&t, title)) + }); + let own = || { + list.iter().find(|e| { + let ch = tidy_channel(&s(&e["channel"]).or_else(|| s(&e["uploader"])).unwrap_or_default()); + let t = s(&e["title"]).unwrap_or_default(); + crate::artistinfo::norm(&ch) == artist_n && Regex::new(r"(?i)\bofficial\s+audio\b").unwrap().is_match(&t) && same_song(&t, title) + }) + }; + topic.or_else(own).and_then(url) +} + +pub async fn find_official_audio(settings: &Settings, tools: &Tools, artist: &str, title: &str) -> Option { + let mut args = base_args(settings, tools); + args.extend(["-J".into(), "--flat-playlist".into(), "--".into(), format!("ytsearch8:{artist} {title} official audio")]); + let v = run_json(tools, args).await.ok()?; + pick_official_audio(&v, artist, title) +} static TITLE_JUNK: LazyLock = LazyLock::new(|| { Regex::new(r"(?i)\s*[\(\[【][^)\]】]*\b(official|music\s*video|lyrics?|lyric\s*video|visuali[sz]er|audio|video\s*oficial|clipe\s*oficial|mv|m/v|hd|hq|4k|8k|explicit|clean\s*version|full\s*song|premiere)\b[^)\]】]*[\)\]】]").unwrap() }); @@ -267,6 +300,7 @@ pub fn entry_from_info(v: &Value, index: u32) -> Entry { let raw_artist = s(&v["artist"]).or_else(|| joined(&v["artists"])).or_else(|| s(&v["creator"])); let real_artist = raw_artist.as_ref().is_some_and(|a| *a != uploader) && !extractor.to_ascii_lowercase().contains("soundcloud"); let cleaned = tidy_title(&raw_title); + let music_video = MUSIC_VIDEO.is_match(&raw_title) || s(&v["title"]).is_some_and(|t| MUSIC_VIDEO.is_match(&t)); let (artist, title) = match (real_artist, split_artist_title(&cleaned)) { (false, Some((a, t))) => (a, tidy_title(&t)), _ => (raw_artist.map(|a| tidy_channel(&a)).unwrap_or_else(|| uploader.clone()), cleaned), @@ -295,6 +329,7 @@ pub fn entry_from_info(v: &Value, index: u32) -> Entry { availability, detailed: has_formats, media, + music_video, } } @@ -738,6 +773,32 @@ mod tests { assert_eq!(big.last().unwrap().1, 101); } + #[tokio::test] + #[ignore] + async fn live_finds_official_audio() { + let tools = engine::locate("", "").unwrap(); + let url = find_official_audio(&Settings::default(), &tools, "Daft Punk", "Get Lucky").await; + assert!(url.is_some_and(|u| u.contains("youtube.com"))); + } + + #[test] + fn prefers_topic_or_the_artists_own_official_audio() { + let results = json!({ "entries": [ + { "title": "Get Lucky - Daft Punk (Audio)", "channel": "Bob", "url": "https://y/bob" }, + { "title": "Daft Punk - Get Lucky (Official Audio) ft. Pharrell Williams", "channel": "Daft Punk", "url": "https://y/own" }, + { "title": "Get Lucky", "channel": "Daft Punk - Topic", "url": "https://y/topic" } + ]}); + assert_eq!(pick_official_audio(&results, "Daft Punk", "Get Lucky").as_deref(), Some("https://y/topic")); + let no_topic = json!({ "entries": [ results["entries"][0].clone(), results["entries"][1].clone() ] }); + assert_eq!(pick_official_audio(&no_topic, "Daft Punk", "Get Lucky").as_deref(), Some("https://y/own")); + let only_reuploads = json!({ "entries": [ results["entries"][0].clone() ] }); + assert_eq!(pick_official_audio(&only_reuploads, "Daft Punk", "Get Lucky"), None); + let v = json!({ "extractor_key": "Youtube", "id": "9", "title": "Westwood – Eyes (Official Music Video)", "uploader": "Westwood", "formats": [] }); + assert!(entry_from_info(&v, 1).music_video); + let a = json!({ "extractor_key": "Youtube", "id": "8", "title": "Westwood – Eyes (Official Audio)", "uploader": "Westwood", "formats": [] }); + assert!(!entry_from_info(&a, 1).music_video); + } + #[test] fn youtube_titles_lose_video_clutter() { let v = json!({ "extractor_key": "Youtube", "id": "9", "title": "Westwood – Eyes (Official Music Video)", "uploader": "Westwood", "formats": [] }); diff --git a/src/settings.rs b/src/settings.rs index 89825a6..3d2b69c 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -49,6 +49,7 @@ pub struct Settings { pub video_height: u32, pub video_container: String, pub video_keep_audio: bool, + pub prefer_official_audio: bool, pub concurrency: u8, pub filename_template: String, pub embed_metadata: bool, @@ -97,6 +98,7 @@ impl Default for Settings { video_height: 1080, video_container: "mp4".into(), video_keep_audio: true, + prefer_official_audio: true, concurrency: 3, filename_template: "{artist} - {title}".into(), embed_metadata: true, @@ -143,6 +145,7 @@ pub struct SettingsPatch { pub video_height: Option, pub video_container: Option, pub video_keep_audio: Option, + pub prefer_official_audio: Option, pub concurrency: Option, pub filename_template: Option, pub embed_metadata: Option, @@ -210,7 +213,7 @@ impl Settings { ($($f:ident),*) => { $( if let Some(v) = p.$f { self.$f = v; } )* }; } set!(save_as, embed_metadata, collection_folders, number_tracks, skip_downloaded, sponsorblock, embed_subtitles, embed_chapters, watch_clipboard); - set!(api_enabled, api_read, api_control, api_links, check_updates, artist_info, video_keep_audio); + set!(api_enabled, api_read, api_control, api_links, check_updates, artist_info, video_keep_audio, prefer_official_audio); if let Some(p) = p.api_port.filter(|p| *p >= 1024) { self.api_port = p; } diff --git a/ui/index.html b/ui/index.html index 93c9634..8a44d88 100644 --- a/ui/index.html +++ b/ui/index.html @@ -185,6 +185,7 @@
Save to
+