mirror of
https://github.com/pvrzz/atmosphere.git
synced 2026-11-29 05:22:26 +00:00
Music videos: keep video and audio, switch between them at the same moment
- Save as Video can also keep a matching audio file (on by default, recommended), copied losslessly from the video where possible - Songs with a video beside them get a video badge; video-only files play as songs - Video button (V) shows the music video in TV mode, kept in sync with the song, so switching between the cover and the video never interrupts playback
This commit is contained in:
@@ -352,6 +352,26 @@ impl Job {
|
||||
notes.push(format!("Saved, but your metadata edits couldn't be written ({e})."));
|
||||
}
|
||||
}
|
||||
let path = if plan.video && settings.video_keep_audio {
|
||||
match (tools.ffmpeg.as_deref(), &path) {
|
||||
(Some(ff), video) => match extract_audio(ff, video).await {
|
||||
Ok(audio) => {
|
||||
if settings.embed_metadata {
|
||||
let _ = tagging::apply(&audio, &req.meta, &req.entry.url, Some(ff)).await;
|
||||
}
|
||||
notes.push("Saved the video and a matching audio file. Play it as a song, and show the video any time.".into());
|
||||
audio
|
||||
}
|
||||
Err(e) => {
|
||||
notes.push(format!("Saved the video, but the audio file couldn't be made ({e})."));
|
||||
path
|
||||
}
|
||||
},
|
||||
_ => path,
|
||||
}
|
||||
} else {
|
||||
path
|
||||
};
|
||||
self.progress = 1.0;
|
||||
let note = (!notes.is_empty()).then(|| notes.join(" "));
|
||||
self.emit("done", note, Some(&path));
|
||||
@@ -656,6 +676,29 @@ async fn cleanup(dir: &Path, stem: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn extract_audio(ffmpeg: &Path, video: &Path) -> Result<PathBuf> {
|
||||
let mp4 = video.extension().is_some_and(|e| e.eq_ignore_ascii_case("mp4") || e.eq_ignore_ascii_case("m4v") || e.eq_ignore_ascii_case("mov"));
|
||||
let attempts: Vec<(&str, Vec<&str>)> = if mp4 {
|
||||
vec![("m4a", vec!["-c:a", "copy"]), ("m4a", vec!["-c:a", "aac", "-b:a", "256k"])]
|
||||
} else {
|
||||
vec![("opus", vec!["-c:a", "copy"]), ("m4a", vec!["-c:a", "aac", "-b:a", "256k"])]
|
||||
};
|
||||
for (ext, codec) in attempts {
|
||||
let out = video.with_extension(ext);
|
||||
let mut args: Vec<String> = ["-hide_banner", "-loglevel", "error", "-y", "-i"].map(String::from).into();
|
||||
args.push(video.to_string_lossy().into_owned());
|
||||
args.extend(["-map", "0:a:0", "-vn", "-map_metadata", "0"].map(String::from));
|
||||
args.extend(codec.iter().map(|c| c.to_string()));
|
||||
args.push(out.to_string_lossy().into_owned());
|
||||
let ok = engine::command(ffmpeg).args(&args).stdout(Stdio::null()).stderr(Stdio::null()).status().await.is_ok_and(|s| s.success());
|
||||
if ok && out.metadata().is_ok_and(|m| m.len() > 0) {
|
||||
return Ok(out);
|
||||
}
|
||||
let _ = tokio::fs::remove_file(&out).await;
|
||||
}
|
||||
bail!("ffmpeg couldn't read the video's audio")
|
||||
}
|
||||
|
||||
pub fn target_dir(settings: &Settings, req: &JobRequest) -> PathBuf {
|
||||
let base = PathBuf::from(&settings.output_dir);
|
||||
let named = req.folder.as_deref().map(str::trim).filter(|n| !n.is_empty() && settings.collection_folders);
|
||||
@@ -772,6 +815,35 @@ mod tests {
|
||||
assert!(plan(&entry(Some(128), false, vec![720]), &save(SaveAs::Mp3, 320, 0), false).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn keeps_an_audio_file_beside_a_video_and_pairs_them() {
|
||||
let Some(ff) = engine::find_tool("ffmpeg") else { return };
|
||||
let dir = std::env::temp_dir().join(format!("atmo-video-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let video = dir.join("Westwood - Eyes.mp4");
|
||||
let made = engine::command(&ff)
|
||||
.args(["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10", "-f", "lavfi", "-i", "sine=frequency=440", "-t", "2", "-c:v", "libx264", "-c:a", "aac", "-shortest"])
|
||||
.arg(&video)
|
||||
.status()
|
||||
.await
|
||||
.is_ok_and(|s| s.success());
|
||||
if !made {
|
||||
return;
|
||||
}
|
||||
let audio = extract_audio(&ff, &video).await.unwrap();
|
||||
assert_eq!(audio.extension().unwrap(), "m4a");
|
||||
assert!(crate::library::is_playable(&audio));
|
||||
assert!(!crate::library::is_playable(&video));
|
||||
let t = crate::library::read_track(&audio, None).unwrap();
|
||||
assert_eq!(t.video.as_deref(), Some(&*video.to_string_lossy()));
|
||||
std::fs::remove_file(&audio).unwrap();
|
||||
assert!(crate::library::is_playable(&video));
|
||||
let v = crate::library::read_track(&video, None).unwrap();
|
||||
assert_eq!(v.video.as_deref(), Some(&*video.to_string_lossy()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sorts_downloads_into_albums_playlists_and_tracks() {
|
||||
let settings = Settings { output_dir: "M".into(), playlists_dir: "M/Playlists".into(), collection_folders: true, ..Default::default() };
|
||||
|
||||
+11
-3
@@ -66,11 +66,11 @@ fn apply_changes(app: &AppHandle, paths: HashSet<PathBuf>) {
|
||||
touched |= state.library.remove_under(&p) > 0;
|
||||
} else if p.is_dir() {
|
||||
for e in walkdir::WalkDir::new(&p).into_iter().flatten().filter(|e| e.file_type().is_file()) {
|
||||
if crate::library::is_audio(e.path()) && !state.library.knows(e.path()) {
|
||||
if crate::library::is_playable(e.path()) && !state.library.knows(e.path()) {
|
||||
touched |= state.library.add_file(e.path(), &pl).is_ok();
|
||||
}
|
||||
}
|
||||
} else if crate::library::is_audio(&p) && !state.library.knows(&p) {
|
||||
} else if crate::library::is_playable(&p) && !state.library.knows(&p) {
|
||||
touched |= state.library.add_file(&p, &pl).is_ok();
|
||||
}
|
||||
}
|
||||
@@ -432,12 +432,16 @@ pub fn set_fullscreen(app: AppHandle, on: bool) -> CmdResult<bool> {
|
||||
fn mime(path: &Path) -> &'static str {
|
||||
match path.extension().and_then(|e| e.to_str()).unwrap_or_default().to_ascii_lowercase().as_str() {
|
||||
"mp3" => "audio/mpeg",
|
||||
"m4a" | "mp4" | "aac" => "audio/mp4",
|
||||
"m4a" | "aac" => "audio/mp4",
|
||||
"flac" => "audio/flac",
|
||||
"ogg" => "audio/ogg",
|
||||
"opus" => "audio/ogg; codecs=opus",
|
||||
"wav" => "audio/wav",
|
||||
"aiff" | "aif" => "audio/aiff",
|
||||
"mp4" | "m4v" => "video/mp4",
|
||||
"webm" => "video/webm",
|
||||
"mkv" => "video/x-matroska",
|
||||
"mov" => "video/quicktime",
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
"png" => "image/png",
|
||||
_ => "application/octet-stream",
|
||||
@@ -498,6 +502,10 @@ pub fn serve(app: &AppHandle, request: &Request<Vec<u8>>) -> Response<Vec<u8>> {
|
||||
Some(t) => stream(Path::new(&t.path), range),
|
||||
None => respond(404, "text/plain", b"unknown track".to_vec(), &[]),
|
||||
},
|
||||
"v" => match state.library.track(id).and_then(|t| t.video) {
|
||||
Some(v) => stream(Path::new(&v), range),
|
||||
None => respond(404, "text/plain", b"no video".to_vec(), &[]),
|
||||
},
|
||||
"a" => match state.library.art_path(id) {
|
||||
Some(p) if p.extension().is_some_and(|e| e == "png") => match std::fs::read(&p) {
|
||||
Ok(data) => respond(200, "image/png", data, &[("Cache-Control", "max-age=86400".into())]),
|
||||
|
||||
+36
-3
@@ -13,6 +13,7 @@ use std::sync::RwLock;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
pub const AUDIO_EXT: [&str; 9] = ["mp3", "m4a", "flac", "ogg", "opus", "wav", "aac", "aiff", "aif"];
|
||||
pub const VIDEO_EXT: [&str; 5] = ["mp4", "m4v", "mkv", "webm", "mov"];
|
||||
const ORDER_FILE: &str = "playlist.m3u8";
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
@@ -41,6 +42,7 @@ pub struct Track {
|
||||
pub gain_db: Option<f32>,
|
||||
pub sample_rate: Option<u32>,
|
||||
pub channels: Option<u8>,
|
||||
pub video: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
@@ -187,6 +189,20 @@ pub fn is_audio(p: &Path) -> bool {
|
||||
p.extension().and_then(|e| e.to_str()).is_some_and(|e| AUDIO_EXT.contains(&e.to_ascii_lowercase().as_str()))
|
||||
}
|
||||
|
||||
pub fn is_video(p: &Path) -> bool {
|
||||
p.extension().and_then(|e| e.to_str()).is_some_and(|e| VIDEO_EXT.contains(&e.to_ascii_lowercase().as_str()))
|
||||
}
|
||||
|
||||
fn sibling(p: &Path, exts: &[&str]) -> Option<PathBuf> {
|
||||
let stem = p.file_stem()?;
|
||||
let dir = p.parent()?;
|
||||
exts.iter().map(|e| dir.join(stem).with_extension(e)).find(|c| c != p && c.is_file())
|
||||
}
|
||||
|
||||
pub fn is_playable(p: &Path) -> bool {
|
||||
is_audio(p) || (is_video(p) && sibling(p, &AUDIO_EXT).is_none())
|
||||
}
|
||||
|
||||
fn file_stamp(p: &Path) -> Option<(u64, u64)> {
|
||||
let m = std::fs::metadata(p).ok()?;
|
||||
let mtime = m.modified().ok()?.duration_since(UNIX_EPOCH).ok()?.as_secs();
|
||||
@@ -214,6 +230,22 @@ fn year_of(s: &str) -> Option<u32> {
|
||||
}
|
||||
|
||||
pub fn read_track(path: &Path, playlist: Option<String>) -> Result<Track> {
|
||||
let mut t = match read_tags(path, playlist.clone()) {
|
||||
Ok(t) => t,
|
||||
Err(e) if is_video(path) => {
|
||||
let (size, mtime) = file_stamp(path).ok_or(e)?;
|
||||
let path_s = path.to_string_lossy().into_owned();
|
||||
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("Untitled").to_string();
|
||||
let (artist, title) = crate::media::split_artist_title(&stem).unwrap_or((String::new(), stem));
|
||||
Track { id: hash(&path_s), title, artist, format: path.extension().and_then(|e| e.to_str()).unwrap_or_default().to_ascii_lowercase(), size, mtime, playlist, added: now(), path: path_s, ..Default::default() }
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
t.video = if is_video(path) { Some(t.path.clone()) } else { sibling(path, &VIDEO_EXT).map(|v| v.to_string_lossy().into_owned()) };
|
||||
Ok(t)
|
||||
}
|
||||
|
||||
fn read_tags(path: &Path, playlist: Option<String>) -> Result<Track> {
|
||||
let (size, mtime) = file_stamp(path).ok_or_else(|| anyhow!("unreadable"))?;
|
||||
let file = lofty::read_from_path(path)?;
|
||||
let props = file.properties();
|
||||
@@ -254,6 +286,7 @@ pub fn read_track(path: &Path, playlist: Option<String>) -> Result<Track> {
|
||||
gain_db,
|
||||
sample_rate: props.sample_rate(),
|
||||
channels: props.channels(),
|
||||
video: None,
|
||||
path: path_s,
|
||||
})
|
||||
}
|
||||
@@ -311,7 +344,7 @@ impl Library {
|
||||
|
||||
pub fn open_paths(&self, paths: &[PathBuf]) -> Vec<Track> {
|
||||
let mut out = Vec::new();
|
||||
for p in paths.iter().filter(|p| p.is_file() && is_audio(p)) {
|
||||
for p in paths.iter().filter(|p| p.is_file() && is_playable(p)) {
|
||||
let key = p.to_string_lossy();
|
||||
if let Some(t) = self.tracks.read().unwrap().values().find(|t| t.path == key).cloned() {
|
||||
out.push(t);
|
||||
@@ -348,7 +381,7 @@ impl Library {
|
||||
for root in all_roots.iter().filter(|r| r.is_dir()) {
|
||||
for entry in walkdir::WalkDir::new(root).follow_links(false).into_iter().filter_entry(|e| !e.file_name().to_string_lossy().starts_with('.')).flatten() {
|
||||
let p = entry.path();
|
||||
if entry.file_type().is_file() && is_audio(p) && seen.insert(p.to_path_buf()) {
|
||||
if entry.file_type().is_file() && is_playable(p) && seen.insert(p.to_path_buf()) {
|
||||
files.push(p.to_path_buf());
|
||||
}
|
||||
}
|
||||
@@ -596,7 +629,7 @@ impl Library {
|
||||
let mut found = Vec::new();
|
||||
for e in walkdir::WalkDir::new(folder).follow_links(false).into_iter().filter_entry(|e| !e.file_name().to_string_lossy().starts_with('.')).flatten() {
|
||||
let p = e.path();
|
||||
if e.file_type().is_file() && is_audio(p) && !hidden.contains(&*p.to_string_lossy()) {
|
||||
if e.file_type().is_file() && is_playable(p) && !hidden.contains(&*p.to_string_lossy()) {
|
||||
if let Ok(t) = read_track(p, self.playlist_for(p, playlists_dir)) {
|
||||
found.push(t);
|
||||
}
|
||||
|
||||
+4
-1
@@ -48,6 +48,7 @@ pub struct Settings {
|
||||
pub mp3_bitrate: u32,
|
||||
pub video_height: u32,
|
||||
pub video_container: String,
|
||||
pub video_keep_audio: bool,
|
||||
pub concurrency: u8,
|
||||
pub filename_template: String,
|
||||
pub embed_metadata: bool,
|
||||
@@ -95,6 +96,7 @@ impl Default for Settings {
|
||||
mp3_bitrate: 320,
|
||||
video_height: 1080,
|
||||
video_container: "mp4".into(),
|
||||
video_keep_audio: true,
|
||||
concurrency: 3,
|
||||
filename_template: "{artist} - {title}".into(),
|
||||
embed_metadata: true,
|
||||
@@ -140,6 +142,7 @@ pub struct SettingsPatch {
|
||||
pub mp3_bitrate: Option<u32>,
|
||||
pub video_height: Option<u32>,
|
||||
pub video_container: Option<String>,
|
||||
pub video_keep_audio: Option<bool>,
|
||||
pub concurrency: Option<u8>,
|
||||
pub filename_template: Option<String>,
|
||||
pub embed_metadata: Option<bool>,
|
||||
@@ -207,7 +210,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);
|
||||
set!(api_enabled, api_read, api_control, api_links, check_updates, artist_info, video_keep_audio);
|
||||
if let Some(p) = p.api_port.filter(|p| *p >= 1024) {
|
||||
self.api_port = p;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user