mirror of
https://github.com/pvrzz/atmosphere.git
synced 2026-11-29 05:22:26 +00:00
Gapless playback, crossfade and volume levelling
- Two-deck player keeps the next song loaded and buffered, and blends it in 20 ms before the current one ends, so albums and playlists play without gaps - Skipping to the next song uses the preloaded deck, so it starts instantly - Optional crossfade (up to 12 s); songs from the same album stay gapless - Optional volume levelling: uses ReplayGain tags or measures each song once (-14 LUFS, capped so boosts never clip); files are never changed - Playback section at the top of Settings
This commit is contained in:
@@ -522,3 +522,61 @@ mod tests {
|
||||
assert_eq!(range_of(None, 1000), None);
|
||||
}
|
||||
}
|
||||
|
||||
static LOUDNESS: std::sync::LazyLock<tokio::sync::Semaphore> = std::sync::LazyLock::new(|| tokio::sync::Semaphore::new(1));
|
||||
|
||||
pub fn gain_from_ebur128(log: &str) -> Option<f32> {
|
||||
let lufs = regex::Regex::new(r"I:\s+(-?[\d.]+)\s+LUFS").ok()?.captures_iter(log).last()?.get(1)?.as_str().parse::<f32>().ok()?;
|
||||
let peak = regex::Regex::new(r"Peak:\s+(-?[\d.]+|-inf)\s+dBFS").ok()?.captures_iter(log).last().and_then(|c| c[1].parse::<f32>().ok());
|
||||
if !lufs.is_finite() || lufs < -70.0 {
|
||||
return None;
|
||||
}
|
||||
let mut gain = (-14.0 - lufs).clamp(-20.0, 12.0);
|
||||
if let Some(p) = peak.filter(|p| p.is_finite()) {
|
||||
gain = gain.min(-1.0 - p);
|
||||
}
|
||||
Some((gain * 10.0).round() / 10.0)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn track_loudness(state: State<'_, AppState>, id: String) -> CmdResult<Option<f32>> {
|
||||
let Some(t) = state.library.track(&id) else { return Ok(None) };
|
||||
if t.gain_db.is_some() {
|
||||
return Ok(t.gain_db);
|
||||
}
|
||||
let s = state.snapshot();
|
||||
let Some(ffmpeg) = crate::engine::locate(&s.ytdlp_path, &s.ffmpeg_path).ok().and_then(|t| t.ffmpeg).or_else(|| crate::engine::find_tool("ffmpeg")) else { return Ok(None) };
|
||||
let _permit = LOUDNESS.acquire().await.map_err(|e| e.to_string())?;
|
||||
if let Some(g) = state.library.track(&id).and_then(|t| t.gain_db) {
|
||||
return Ok(Some(g));
|
||||
}
|
||||
let out = crate::engine::command(&ffmpeg)
|
||||
.args(["-hide_banner", "-nostats", "-i", &t.path, "-map", "0:a:0", "-af", "ebur128=peak=true", "-f", "null", "-"])
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.output()
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let gain = gain_from_ebur128(&String::from_utf8_lossy(&out.stderr));
|
||||
if let Some(g) = gain {
|
||||
state.library.set_gain(&id, g);
|
||||
}
|
||||
Ok(gain)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod loudness_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn levels_toward_minus_14_without_clipping() {
|
||||
let loud = "Summary:\n Integrated loudness:\n I: -8.0 LUFS\n True peak:\n Peak: 0.4 dBFS";
|
||||
assert_eq!(gain_from_ebur128(loud), Some(-6.0));
|
||||
let quiet = " I: -20.0 LUFS\n Peak: -9.0 dBFS";
|
||||
assert_eq!(gain_from_ebur128(quiet), Some(6.0));
|
||||
let peaky = " I: -20.0 LUFS\n Peak: -2.0 dBFS";
|
||||
assert_eq!(gain_from_ebur128(peaky), Some(1.0));
|
||||
assert_eq!(gain_from_ebur128("nothing"), None);
|
||||
assert_eq!(crate::library::parse_gain("-6.20 dB"), Some(-6.2));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,6 +38,9 @@ pub struct Track {
|
||||
pub playlist: Option<String>,
|
||||
pub has_lyrics: bool,
|
||||
pub added: u64,
|
||||
pub gain_db: Option<f32>,
|
||||
pub sample_rate: Option<u32>,
|
||||
pub channels: Option<u8>,
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
@@ -184,6 +187,7 @@ pub fn read_track(path: &Path, playlist: Option<String>) -> Result<Track> {
|
||||
let album_artist = get(&|t| t.get_string(ItemKey::AlbumArtist).map(String::from)).unwrap_or_default();
|
||||
let year = get(&|t| t.get_string(ItemKey::Year).or_else(|| t.get_string(ItemKey::RecordingDate)).or_else(|| t.get_string(ItemKey::ReleaseDate)).map(String::from)).and_then(|y| year_of(&y));
|
||||
let lyrics_tag = tag.and_then(|t| t.get_string(ItemKey::Lyrics)).is_some_and(|l| !l.trim().is_empty());
|
||||
let gain_db = tag.and_then(|t| t.get_string(ItemKey::ReplayGainTrackGain)).and_then(parse_gain);
|
||||
let group = format!("{}|{}", if album_artist.is_empty() { &artist } else { &album_artist }, album).to_lowercase();
|
||||
let art_key = if album.is_empty() { hash(&path.to_string_lossy()) } else { hash(&group) };
|
||||
let art = tag.and_then(|t| t.pictures().first()).and_then(|p| save_art(&art_key, p.data()));
|
||||
@@ -208,10 +212,18 @@ pub fn read_track(path: &Path, playlist: Option<String>) -> Result<Track> {
|
||||
playlist,
|
||||
has_lyrics: lyrics_tag || path.with_extension("lrc").exists(),
|
||||
added: now(),
|
||||
gain_db,
|
||||
sample_rate: props.sample_rate(),
|
||||
channels: props.channels(),
|
||||
path: path_s,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_gain(s: &str) -> Option<f32> {
|
||||
let n: String = s.trim().trim_end_matches(|c: char| c.is_alphabetic() || c.is_whitespace()).trim().to_string();
|
||||
n.parse::<f32>().ok().filter(|g| g.is_finite() && g.abs() < 60.0)
|
||||
}
|
||||
|
||||
fn playlist_of(path: &Path, playlists_dir: &Path) -> Option<String> {
|
||||
let rel = path.strip_prefix(playlists_dir).ok()?;
|
||||
let mut parts = rel.components();
|
||||
@@ -781,6 +793,13 @@ impl Library {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn set_gain(&self, id: &str, gain: f32) {
|
||||
let changed = self.tracks.write().unwrap().get_mut(id).map(|t| t.gain_db = Some(gain)).is_some();
|
||||
if changed {
|
||||
self.persist();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn refresh(&self, id: &str, playlists_dir: &Path) -> Result<Track> {
|
||||
let t = self.track(id).ok_or_else(|| anyhow!("That track is no longer in the library"))?;
|
||||
let _ = std::fs::remove_file(art_dir().join(format!("{}.jpg", t.art.clone().unwrap_or_default())));
|
||||
|
||||
@@ -532,6 +532,7 @@ fn main() {
|
||||
libcmd::lyrics_save_text,
|
||||
libcmd::set_fullscreen,
|
||||
libcmd::playlist_link,
|
||||
libcmd::track_loudness,
|
||||
libcmd::playlist_relocate,
|
||||
libcmd::playlist_unlink
|
||||
])
|
||||
|
||||
Reference in New Issue
Block a user