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:
Christian
2026-11-18 22:25:12 -05:00
parent f6db780bca
commit 93db117243
9 changed files with 371 additions and 31 deletions
+58
View File
@@ -522,3 +522,61 @@ mod tests {
assert_eq!(range_of(None, 1000), None); 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));
}
}
+19
View File
@@ -38,6 +38,9 @@ pub struct Track {
pub playlist: Option<String>, pub playlist: Option<String>,
pub has_lyrics: bool, pub has_lyrics: bool,
pub added: u64, pub added: u64,
pub gain_db: Option<f32>,
pub sample_rate: Option<u32>,
pub channels: Option<u8>,
} }
#[derive(Default, Serialize, Deserialize)] #[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 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 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 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 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_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())); 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, playlist,
has_lyrics: lyrics_tag || path.with_extension("lrc").exists(), has_lyrics: lyrics_tag || path.with_extension("lrc").exists(),
added: now(), added: now(),
gain_db,
sample_rate: props.sample_rate(),
channels: props.channels(),
path: path_s, 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> { fn playlist_of(path: &Path, playlists_dir: &Path) -> Option<String> {
let rel = path.strip_prefix(playlists_dir).ok()?; let rel = path.strip_prefix(playlists_dir).ok()?;
let mut parts = rel.components(); let mut parts = rel.components();
@@ -781,6 +793,13 @@ impl Library {
Ok(out) 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> { 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 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()))); let _ = std::fs::remove_file(art_dir().join(format!("{}.jpg", t.art.clone().unwrap_or_default())));
+1
View File
@@ -532,6 +532,7 @@ fn main() {
libcmd::lyrics_save_text, libcmd::lyrics_save_text,
libcmd::set_fullscreen, libcmd::set_fullscreen,
libcmd::playlist_link, libcmd::playlist_link,
libcmd::track_loudness,
libcmd::playlist_relocate, libcmd::playlist_relocate,
libcmd::playlist_unlink libcmd::playlist_unlink
]) ])
+2
View File
@@ -238,6 +238,7 @@ async function init() {
bindMini(); bindMini();
bindConnect(); bindConnect();
bindUpdates(); bindUpdates();
bindPlaybackSettings();
bindStats(); bindStats();
await listen("atmosphere://job", (e) => onJob(e.payload)); await listen("atmosphere://job", (e) => onJob(e.payload));
await listen("atmosphere://probe", (e) => onProbe(e.payload)); await listen("atmosphere://probe", (e) => onProbe(e.payload));
@@ -1471,6 +1472,7 @@ function renderSettings() {
$("#rightsInfo").textContent = at ? `You agreed on ${at}. Withdrawing it cancels downloads and asks again in the app.` : "Not confirmed yet."; $("#rightsInfo").textContent = at ? `You agreed on ${at}. Withdrawing it cancels downloads and asks again in the app.` : "Not confirmed yet.";
renderTemplatePreview(); renderTemplatePreview();
renderSignin(); renderSignin();
if (typeof renderPlaybackSettings === "function") renderPlaybackSettings();
if (typeof renderApiSettings === "function") renderApiSettings(); if (typeof renderApiSettings === "function") renderApiSettings();
renderToolSettings(); renderToolSettings();
renderLibrarySettings(); renderLibrarySettings();
+1 -1
View File
@@ -99,7 +99,7 @@ function bindConnect() {
window.addEventListener("player", (e) => { window.addEventListener("player", (e) => {
if (e.detail.type !== "time") apiPublishSoon(); if (e.detail.type !== "time") apiPublishSoon();
}); });
Player.audio.addEventListener("seeked", apiPublishSoon); Player.on("seeked", apiPublishSoon);
Connect.beat = setInterval(() => { Connect.beat = setInterval(() => {
if (!Player.audio.paused) apiPublishSoon(); if (!Player.audio.paused) apiPublishSoon();
}, 10000); }, 10000);
+9
View File
@@ -168,6 +168,15 @@
</header> </header>
<div class="settings-scroll"> <div class="settings-scroll">
<div class="settings"> <div class="settings">
<h2 id="set-playback">Playback</h2>
<div class="group">
<div class="setting">
<div><strong>Crossfade</strong><span id="xfNote">Off. The next song is always loaded ahead, so songs play back to back with no gap.</span></div>
<div class="slider-row"><input type="range" class="range" id="xfRange" min="0" max="12" step="1" value="0" aria-label="Crossfade length" /><span class="slider-val" id="xfVal">Off</span></div>
</div>
<label class="setting"><div><strong>Even out volume</strong><span>Plays quiet and loud songs at a similar level, like streaming apps do. Each song is measured once; your files aren't changed.</span></div><input type="checkbox" class="switch" id="levelToggle" /></label>
</div>
<h2 id="set-files">Files</h2> <h2 id="set-files">Files</h2>
<div class="group"> <div class="group">
<div class="setting"> <div class="setting">
+27
View File
@@ -330,3 +330,30 @@ function bindPlayer() {
updateTime(); updateTime();
updateVolume(); updateVolume();
} }
/* playback settings */
function renderPlaybackSettings() {
const r = $("#xfRange");
if (!r) return;
if (document.activeElement !== r) r.value = String(Player.crossfade);
rangeFill(r);
$("#xfVal").textContent = Player.crossfade ? `${Player.crossfade} s` : "Off";
$("#xfNote").textContent = Player.crossfade
? `Songs blend over ${Player.crossfade} seconds. Songs from the same album still play gapless, so live and continuous albums flow.`
: "Off. The next song is always loaded ahead, so songs play back to back with no gap.";
$("#levelToggle").checked = Player.leveling;
}
function bindPlaybackSettings() {
const r = $("#xfRange");
if (!r) return;
r.addEventListener("input", () => {
Player.setCrossfade(r.value);
renderPlaybackSettings();
});
$("#levelToggle").addEventListener("change", (e) => Player.setLeveling(e.target.checked));
window.addEventListener("player", (e) => {
if (e.detail.type === "settings") renderPlaybackSettings();
});
renderPlaybackSettings();
}
+249 -30
View File
@@ -1,4 +1,4 @@
/* atmosphere · player.js · Audio engine: queue, shuffle/repeat, EQ presets, filters, reverb, 8D, pitch and tempo, media keys and resume. */ /* atmosphere · player.js · Audio engine: two-deck gapless playback, crossfade, volume levelling, queue, EQ and effects, media keys and resume. */
const MEDIA_BASE = /Windows/.test(navigator.userAgent) ? "http://atmo.localhost/" : "atmo://localhost/"; const MEDIA_BASE = /Windows/.test(navigator.userAgent) ? "http://atmo.localhost/" : "atmo://localhost/";
const mediaUrl = (kind, id) => `${MEDIA_BASE}${kind}/${encodeURIComponent(id)}`; const mediaUrl = (kind, id) => `${MEDIA_BASE}${kind}/${encodeURIComponent(id)}`;
const artUrl = (key) => (key ? mediaUrl("a", key) : null); const artUrl = (key) => (key ? mediaUrl("a", key) : null);
@@ -25,7 +25,20 @@ const PRESETS = [
]; ];
const Player = { const Player = {
audio: new Audio(), decks: [new Audio(), new Audio()],
deck: 0,
get audio() {
return this.decks[this.deck];
},
get standby() {
return this.decks[1 - this.deck];
},
standbyId: null,
standbyIndex: -1,
deckNodes: null,
transitionTimer: 0,
crossfade: 0,
leveling: false,
ctx: null, ctx: null,
nodes: null, nodes: null,
pitchReady: false, pitchReady: false,
@@ -65,7 +78,15 @@ const Player = {
const AC = window.AudioContext || window.webkitAudioContext; const AC = window.AudioContext || window.webkitAudioContext;
const ctx = new AC(); const ctx = new AC();
this.ctx = ctx; this.ctx = ctx;
const src = ctx.createMediaElementSource(this.audio); const input = ctx.createGain();
this.deckNodes = this.decks.map((el, i) => {
const src = ctx.createMediaElementSource(el);
const level = ctx.createGain();
const fade = ctx.createGain();
fade.gain.value = i === this.deck ? 1 : 0;
src.connect(level).connect(fade).connect(input);
return { src, level, fade };
});
let pitch = null; let pitch = null;
try { try {
await ctx.audioWorklet.addModule("pitch-worklet.js"); await ctx.audioWorklet.addModule("pitch-worklet.js");
@@ -100,7 +121,7 @@ const Player = {
const vol = ctx.createGain(); const vol = ctx.createGain();
const analyser = ctx.createAnalyser(); const analyser = ctx.createAnalyser();
analyser.fftSize = 256; analyser.fftSize = 256;
let head = src; let head = input;
if (pitch) head = head.connect(pitch); if (pitch) head = head.connect(pitch);
head = head.connect(hp).connect(lp); head = head.connect(hp).connect(lp);
for (const b of eq) head = head.connect(b); for (const b of eq) head = head.connect(b);
@@ -110,6 +131,7 @@ const Player = {
this.nodes = { pitch, hp, lp, eq, dry, wet, lfoDepth, vol, analyser }; this.nodes = { pitch, hp, lp, eq, dry, wet, lfoDepth, vol, analyser };
this.applyFx({}); this.applyFx({});
this.setVolume(this.volume); this.setVolume(this.volume);
this.decks.forEach((_, i) => this.applyLevel(i));
}, },
impulse(ctx, seconds, decay) { impulse(ctx, seconds, decay) {
@@ -126,9 +148,11 @@ const Player = {
this.fx = { ...this.fx, ...partial }; this.fx = { ...this.fx, ...partial };
if (presetId !== undefined) this.fx.preset = presetId; if (presetId !== undefined) this.fx.preset = presetId;
const fx = this.bypass ? FX_DEFAULT : this.fx; const fx = this.bypass ? FX_DEFAULT : this.fx;
this.audio.playbackRate = fx.tempo; for (const el of this.decks) {
this.audio.preservesPitch = !fx.vinyl; el.playbackRate = fx.tempo;
this.audio.webkitPreservesPitch = !fx.vinyl; el.preservesPitch = !fx.vinyl;
el.webkitPreservesPitch = !fx.vinyl;
}
const n = this.nodes; const n = this.nodes;
if (n) { if (n) {
const t = this.ctx.currentTime; const t = this.ctx.currentTime;
@@ -162,10 +186,10 @@ const Player = {
this.volume = Math.max(0, Math.min(1, v)); this.volume = Math.max(0, Math.min(1, v));
const level = this.muted ? 0 : this.volume * this.volume; const level = this.muted ? 0 : this.volume * this.volume;
if (this.nodes) { if (this.nodes) {
this.audio.volume = 1; for (const el of this.decks) el.volume = 1;
this.nodes.vol.gain.setTargetAtTime(level, this.ctx.currentTime, 0.015); this.nodes.vol.gain.setTargetAtTime(level, this.ctx.currentTime, 0.015);
} else { } else {
this.audio.volume = level; for (const el of this.decks) el.volume = level;
} }
this.persist(); this.persist();
this.emit("volume"); this.emit("volume");
@@ -178,17 +202,187 @@ const Player = {
async load(i, autoplay = true, startAt = 0) { async load(i, autoplay = true, startAt = 0) {
if (i < 0 || i >= this.queue.length) return; if (i < 0 || i >= this.queue.length) return;
this.cancelTransition();
this.flushListen(); this.flushListen();
const t = this.queue[i];
const preloaded = autoplay && !startAt && this.standbyIndex === i && this.standbyId === t.id && this.standby.readyState >= 2;
const old = this.audio;
if (preloaded) {
old.pause();
this.deck = 1 - this.deck;
this.audio.currentTime = 0;
} else {
if (this.standbyId === t.id) {
this.standbyId = null;
this.standbyIndex = -1;
}
this.audio.src = mediaUrl("t", t.id);
if (startAt) this.audio.addEventListener("loadedmetadata", () => (this.audio.currentTime = startAt), { once: true });
}
this.setFade(this.deck, 1);
this.setFade(1 - this.deck, 0);
if (preloaded) old.currentTime = 0;
this.index = i; this.index = i;
const t = this.current;
this.listenId = t.id; this.listenId = t.id;
this.countedPlay = false; this.countedPlay = false;
this.audio.src = mediaUrl("t", t.id); if (preloaded) {
if (startAt) this.audio.addEventListener("loadedmetadata", () => (this.audio.currentTime = startAt), { once: true }); this.standbyId = null;
this.standbyIndex = -1;
}
this.applyLevel(this.deck);
this.updateSession(); this.updateSession();
this.emit("track"); this.emit("track");
this.persist(); this.persist();
if (autoplay) await this.play(); if (autoplay) await this.play();
this.prime();
},
setFade(deck, value) {
const n = this.deckNodes?.[deck];
if (!n) return;
const t = this.ctx.currentTime;
n.fade.gain.cancelScheduledValues(t);
n.fade.gain.setValueAtTime(value, t);
},
nextIndex() {
if (this.repeat === "one" || !this.queue.length) return -1;
if (this.index + 1 < this.queue.length) return this.index + 1;
return this.repeat === "all" ? 0 : -1;
},
prime() {
const ni = this.nextIndex();
const t = this.queue[ni];
const sb = this.standby;
if (!t || (ni === this.index && this.queue.length === 1)) {
if (this.standbyId) {
sb.removeAttribute("src");
sb.load();
}
this.standbyId = null;
this.standbyIndex = -1;
return;
}
this.standbyIndex = ni;
if (this.standbyId === t.id) return;
this.standbyId = t.id;
sb.pause();
sb.src = mediaUrl("t", t.id);
sb.preload = "auto";
sb.load();
this.setFade(1 - this.deck, 0);
this.applyLevel(1 - this.deck);
},
fadeFor() {
const cur = this.current;
const nxt = this.queue[this.standbyIndex];
if (!this.crossfade || !cur || !nxt) return 0.02;
const sameAlbum = cur.album && nxt.album && lnormP(cur.album) === lnormP(nxt.album) && (!cur.trackNo || !nxt.trackNo || nxt.trackNo === cur.trackNo + 1);
return sameAlbum ? 0.02 : this.crossfade;
},
cancelTransition() {
clearTimeout(this.transitionTimer);
this.transitionTimer = 0;
},
scheduleTransition() {
const a = this.audio;
if (this.transitionTimer || a.paused || this.standbyIndex < 0 || !isFinite(a.duration)) return;
const rate = a.playbackRate || 1;
const remaining = (a.duration - a.currentTime) / rate;
const fade = this.fadeFor();
if (remaining > fade + 1.5) return;
const lead = Math.max(fade, 0.03);
this.transitionTimer = setTimeout(() => this.transition(fade), Math.max(0, (remaining - lead) * 1000));
},
async transition(fade) {
this.transitionTimer = 0;
const ni = this.standbyIndex;
const t = this.queue[ni];
if (ni < 0 || !t || this.standbyId !== t.id || this.audio.paused) return;
await this.ensureGraph();
const outDeck = this.deck;
const inDeck = 1 - this.deck;
const out = this.decks[outDeck];
const inn = this.decks[inDeck];
inn.currentTime = 0;
this.setFade(inDeck, 0);
try {
await inn.play();
} catch {
return;
}
const now = this.ctx.currentTime;
const fin = this.deckNodes[inDeck].fade.gain;
const fout = this.deckNodes[outDeck].fade.gain;
fin.cancelScheduledValues(now);
fout.cancelScheduledValues(now);
if (fade > 0.1) {
const steps = 32;
const up = new Float32Array(steps).map((_, k) => Math.sin(((k / (steps - 1)) * Math.PI) / 2));
const down = new Float32Array(steps).map((_, k) => Math.cos(((k / (steps - 1)) * Math.PI) / 2));
fin.setValueCurveAtTime(up, now, fade);
fout.setValueCurveAtTime(down, now, fade);
} else {
fin.setValueAtTime(0, now);
fin.linearRampToValueAtTime(1, now + fade);
fout.setValueAtTime(1, now);
fout.linearRampToValueAtTime(0, now + fade);
}
this.flushListen();
this.deck = inDeck;
this.index = ni;
this.listenId = t.id;
this.countedPlay = false;
this.lastTick = performance.now();
this.standbyId = null;
this.standbyIndex = -1;
this.updateSession();
this.emit("track");
this.emit("state");
this.persist();
setTimeout(() => {
if (this.audio !== out) {
out.pause();
this.prime();
}
}, fade * 1000 + 120);
},
applyLevel(deck) {
const n = this.deckNodes?.[deck];
const el = this.decks[deck];
const t = deck === this.deck ? this.current : this.queue[this.standbyIndex];
if (!n || !t) return;
const set = (db) => n.level.gain.setTargetAtTime(Math.pow(10, db / 20), this.ctx.currentTime, 0.25);
if (!this.leveling) return set(0);
if (typeof t.gainDb === "number") return set(t.gainDb);
set(0);
const id = t.id;
invoke("track_loudness", { id }).then((g) => {
if (typeof g !== "number") return;
t.gainDb = g;
const still = deck === this.deck ? this.current?.id === id : this.standbyId === id;
if (still && this.leveling && this.decks[deck] === el) set(g);
}).catch(() => {});
},
setCrossfade(seconds) {
this.crossfade = Math.max(0, Math.min(12, Number(seconds) || 0));
this.cancelTransition();
this.persist();
this.emit("settings");
},
setLeveling(on) {
this.leveling = !!on;
this.decks.forEach((_, i) => this.applyLevel(i));
this.persist();
this.emit("settings");
}, },
async play() { async play() {
@@ -232,28 +426,31 @@ const Player = {
playNext(tracks) { playNext(tracks) {
if (!this.current) return this.setQueue(tracks); if (!this.current) return this.setQueue(tracks);
this.queue.splice(this.index + 1, 0, ...tracks); this.queue.splice(this.index + 1, 0, ...tracks);
this.emit("queue"); this.queueChanged();
this.persist();
}, },
addToQueue(tracks) { addToQueue(tracks) {
if (!this.current) return this.setQueue(tracks); if (!this.current) return this.setQueue(tracks);
this.queue.push(...tracks); this.queue.push(...tracks);
this.emit("queue"); this.queueChanged();
this.persist();
}, },
removeAt(i) { removeAt(i) {
if (i === this.index) return; if (i === this.index) return;
this.queue.splice(i, 1); this.queue.splice(i, 1);
if (i < this.index) this.index--; if (i < this.index) this.index--;
this.emit("queue"); this.queueChanged();
this.persist();
}, },
clearUpNext() { clearUpNext() {
this.queue = this.current ? [this.current] : []; this.queue = this.current ? [this.current] : [];
this.index = this.current ? 0 : -1; this.index = this.current ? 0 : -1;
this.queueChanged();
},
queueChanged() {
this.cancelTransition();
this.prime();
this.emit("queue"); this.emit("queue");
this.persist(); this.persist();
}, },
@@ -299,12 +496,16 @@ const Player = {
this.index = 0; this.index = 0;
this.emit("queue"); this.emit("queue");
} }
this.cancelTransition();
this.prime();
this.persist(); this.persist();
this.emit("state"); this.emit("state");
}, },
cycleRepeat() { cycleRepeat() {
this.repeat = { off: "all", all: "one", one: "off" }[this.repeat]; this.repeat = { off: "all", all: "one", one: "off" }[this.repeat];
this.cancelTransition();
this.prime();
this.persist(); this.persist();
this.emit("state"); this.emit("state");
}, },
@@ -320,7 +521,7 @@ const Player = {
clearTimeout(this._persist); clearTimeout(this._persist);
this._persist = setTimeout(() => { this._persist = setTimeout(() => {
try { try {
localStorage.setItem("atmo.player", JSON.stringify({ queue: this.queue.map((t) => t.id), index: this.index, time: this.audio.currentTime || 0, volume: this.volume, shuffle: this.shuffle, repeat: this.repeat, fx: this.fx, bypass: this.bypass })); localStorage.setItem("atmo.player", JSON.stringify({ queue: this.queue.map((t) => t.id), index: this.index, time: this.audio.currentTime || 0, volume: this.volume, shuffle: this.shuffle, repeat: this.repeat, fx: this.fx, bypass: this.bypass, crossfade: this.crossfade, leveling: this.leveling }));
} catch {} } catch {}
}, 400); }, 400);
}, },
@@ -337,6 +538,8 @@ const Player = {
this.repeat = saved.repeat || "off"; this.repeat = saved.repeat || "off";
this.fx = { ...structuredClone(FX_DEFAULT), ...(saved.fx || {}) }; this.fx = { ...structuredClone(FX_DEFAULT), ...(saved.fx || {}) };
this.bypass = !!saved.bypass; this.bypass = !!saved.bypass;
this.crossfade = Math.max(0, Math.min(12, Number(saved.crossfade) || 0));
this.leveling = !!saved.leveling;
this.queue = (saved.queue || []).map(lookup).filter(Boolean); this.queue = (saved.queue || []).map(lookup).filter(Boolean);
if (this.queue.length) this.load(Math.min(Math.max(0, saved.index), this.queue.length - 1), false, saved.time || 0); if (this.queue.length) this.load(Math.min(Math.max(0, saved.index), this.queue.length - 1), false, saved.time || 0);
this.applyFx({}); this.applyFx({});
@@ -370,25 +573,39 @@ const Player = {
} else { } else {
this.index = cur ? this.queue.findIndex((t) => t.id === cur) : this.index; this.index = cur ? this.queue.findIndex((t) => t.id === cur) : this.index;
} }
this.prime();
this.emit("queue"); this.emit("queue");
this.emit("track"); this.emit("track");
this.persist(); this.persist();
}, },
}; };
const lnormP = (s) => (s || "").trim().toLowerCase();
Player.on = (type, fn) => Player.decks.forEach((el) => el.addEventListener(type, (e) => { if (el === Player.audio) fn(e); }));
(() => { (() => {
const a = Player.audio; for (const el of Player.decks) {
a.preload = "auto"; el.preload = "auto";
a.crossOrigin = "anonymous"; el.crossOrigin = "anonymous";
a.addEventListener("play", () => Player.emit("state")); }
a.addEventListener("pause", () => Player.emit("state")); const on = Player.on;
a.addEventListener("ended", () => { Player.flushListen(); Player.next(true); }); on("play", () => Player.emit("state"));
a.addEventListener("playing", () => (Player.lastTick = performance.now())); on("pause", () => { Player.cancelTransition(); Player.emit("state"); });
on("seeking", () => Player.cancelTransition());
on("ended", () => {
Player.cancelTransition();
Player.flushListen();
if (Player.standbyIndex >= 0 && Player.standbyIndex === Player.nextIndex()) Player.load(Player.standbyIndex);
else Player.next(true);
});
on("playing", () => (Player.lastTick = performance.now()));
document.addEventListener("visibilitychange", () => { if (document.visibilityState === "hidden") { Player.flushListen(); } }); document.addEventListener("visibilitychange", () => { if (document.visibilityState === "hidden") { Player.flushListen(); } });
window.addEventListener("beforeunload", () => Player.flushListen()); window.addEventListener("beforeunload", () => Player.flushListen());
let streak = 0; let streak = 0;
a.addEventListener("playing", () => (streak = 0)); on("playing", () => (streak = 0));
a.addEventListener("error", () => { on("error", () => {
const a = Player.audio;
if (!a.src || !Player.current) return; if (!a.src || !Player.current) return;
streak++; streak++;
if (streak === 1) toast(`Couldn't play “${Player.current.title}”. The file may have moved or be unreadable.`, "err"); if (streak === 1) toast(`Couldn't play “${Player.current.title}”. The file may have moved or be unreadable.`, "err");
@@ -398,7 +615,9 @@ const Player = {
} }
if (Player.index + 1 < Player.queue.length) Player.next(true); if (Player.index + 1 < Player.queue.length) Player.next(true);
}); });
a.addEventListener("timeupdate", () => { on("timeupdate", () => {
const a = Player.audio;
Player.scheduleTransition();
Player.emit("time"); Player.emit("time");
const nowTick = performance.now(); const nowTick = performance.now();
if (!a.paused && Player.lastTick) { if (!a.paused && Player.lastTick) {
@@ -414,7 +633,7 @@ const Player = {
} }
if (Math.floor(a.currentTime) % 5 === 0) Player.persist(); if (Math.floor(a.currentTime) % 5 === 0) Player.persist();
}); });
a.addEventListener("loadedmetadata", () => Player.emit("time")); on("loadedmetadata", () => Player.emit("time"));
if ("mediaSession" in navigator) { if ("mediaSession" in navigator) {
const ms = navigator.mediaSession; const ms = navigator.mediaSession;
ms.setActionHandler("play", () => Player.play()); ms.setActionHandler("play", () => Player.play());
+5
View File
@@ -1065,3 +1065,8 @@ body.mini-mode > *:not(#mini):not(.toasts):not(.modal-wrap):not(script) { displa
/* featured on */ /* featured on */
.tile-kind { font-weight: 600; color: var(--text-2); } .tile-kind { font-weight: 600; color: var(--text-2); }
.tile-sub.on { color: var(--text-3); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .tile-sub.on { color: var(--text-3); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* playback settings */
.slider-row { display: flex; align-items: center; gap: var(--s3); flex-shrink: 0; }
.slider-row .range { width: 180px; }
.slider-val { min-width: 34px; text-align: right; font-size: 12.5px; color: var(--text-2); font-variant-numeric: tabular-nums; }