diff --git a/server/stemserve.py b/server/stemserve.py index 4ec6e35..b926cce 100644 --- a/server/stemserve.py +++ b/server/stemserve.py @@ -30,6 +30,7 @@ import glob import hashlib import json import operator +import re import os import shutil import signal @@ -63,6 +64,35 @@ PEAK_RATE = 2000 # Hz the envelope is computed at; plenty for a few hundred bar CHUNK = 1 << 20 # The web player. Served without the token; it asks for one in its settings when TOKEN is set. WEB_DIR = os.path.realpath(os.environ.get("WEB_DIR", os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "web"))) + + +# Web player build stamp: changes whenever any file in web/ does. +_web_cache = {} + + +def web_version(): + try: + sig = sorted((e.name, e.stat().st_mtime_ns, e.stat().st_size) for e in os.scandir(WEB_DIR) if e.is_file()) + except OSError: + return "0" + return hashlib.sha1(repr(sig).encode()).hexdigest()[:10] + + +def web_file(full, ver): + """File body with local asset URLs stamped with ?v=ver (html and js), and its ETag.""" + hit = _web_cache.get(full) + if hit and hit[0] == ver: + return hit[1], hit[2] + with open(full, "rb") as f: + body = f.read() + ext = os.path.splitext(full)[1] + if ext == ".html": + body = re.sub(rb'((?:src|href)="(?:\./)?[\w-]+\.(?:js|css))"', rb'\1?v=' + ver.encode() + rb'"', body) + elif ext == ".js": + body = re.sub(rb'((?:from |import\()"\./[\w-]+\.js)"', rb'\1?v=' + ver.encode() + rb'"', body) + etag = '"%s-%s"' % (ver, hashlib.sha1(body).hexdigest()[:8]) + _web_cache[full] = (ver, body, etag) + return body, etag WEB_TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon", ".json": "application/json"} @@ -315,7 +345,9 @@ class Handler(BaseHTTPRequestHandler): def _error(self, status, msg): self._send(status, json.dumps({"error": msg}).encode()) - def _web(self, path): + def _web(self, path, query=""): + """The web player. index.html and the modules point at ?v= URLs, so a new + build is picked up on a plain reload and the versioned files cache for good.""" if not SERVE_WEB: return self._error(404, "not found") if path == "/": @@ -323,10 +355,16 @@ class Handler(BaseHTTPRequestHandler): full = os.path.realpath(os.path.join(WEB_DIR, path.lstrip("/"))) if not full.startswith(WEB_DIR + os.sep) or not os.path.isfile(full): return self._error(404, "not found") - with open(full, "rb") as f: - body = f.read() + ver = web_version() + body, etag = web_file(full, ver) ctype = WEB_TYPES.get(os.path.splitext(full)[1], "application/octet-stream") - self._send(200, body, ctype, {"Cache-Control": "no-cache"}) + if "v=" + ver in query.split("&"): + cache = "public, max-age=31536000, immutable" + else: + cache = "no-cache" + if self.headers.get("If-None-Match") == etag: + return self._send(304, b"", ctype, {"Cache-Control": cache, "ETag": etag}) + self._send(200, body, ctype, {"Cache-Control": cache, "ETag": etag}) def do_HEAD(self): self.do_GET() @@ -341,7 +379,7 @@ class Handler(BaseHTTPRequestHandler): if path.startswith("/plex/") and PLEX_URL: return self._plex_proxy(path[len("/plex"):], url.query, query) if not path.startswith(("/api/", "/file/")): - return self._web(path) + return self._web(path, url.query) if not self._authorized(query): return self._error(HTTPStatus.UNAUTHORIZED, "bad token") try: diff --git a/web/app.js b/web/app.js index 78c885d..fab4343 100644 --- a/web/app.js +++ b/web/app.js @@ -3,7 +3,7 @@ import { $, $$, esc, fmtTime, fmtBytes, plural, on, emit, toast, ICON, store, uuid } from "./util.js"; import { S, save, songMixes, saveSongMix, forgetSongMix, playlists, savePlaylists, newPlaylist, addToPlaylist, Offline } from "./store.js"; -import { px, img, track, sources, liveServers, server, refreshServer, addServer, manualServer, signIn, sortState, pickSort, comparator, sortTracks, Pager, everything } from "./plex.js"; +import { px, img, rawImg, track, sources, liveServers, server, refreshServer, addServer, manualServer, signIn, sortState, pickSort, comparator, sortTracks, Pager, everything } from "./plex.js"; import { Stems, Live, stemNow, stemTrack, stemBase, api } from "./stems.js"; import { E, Q, setting, stemGain, presets, allPresets, presetLabel, applyPreset, currentPreset, nextPreset, savePreset, deletePreset, movePreset, restorePresets, deleteAllCustom, toggleLock, mixChanged, setKaraoke, setKaraokeMode, sameMix, setSpeed, saveQueue, saveOffline, Radio } from "./player.js"; @@ -219,23 +219,19 @@ const karaokeHtml = () => `
${[["off", "No vocals"], ["soft", "Soft vocals"], ["on", "Vocals on"]].map(([m, l]) => ``).join("")}
${S.karaokeMode === "soft" ? `` : ""}
`; -function mixerHtml() { - const names = mixNames(); - if (!names.length) return `

${E.loading ? "Loading stems…" : Q.cur() ? "This track has no stems yet. Right-click it and pick Stem Now." : "Play something with stems to mix it."}

`; - const cur = currentPreset(names), key = E.entry.key, saved = songMixes[key]; +// Stem colours match the iOS app. +const STEM_COLORS = { vocals: "#ff7ab6", drums: "#ffb547", bass: "#7c8cff", other: "#4cd07d", guitar: "#ff8a5c", piano: "#b48cff", instrumental: "#3dd6c6" }; +const pct = v => Math.round(v * 100) + "%"; +function presetsHtml(names) { + const cur = currentPreset(names), lock = S.lockedPreset && allPresets().find(p => p.id === S.lockedPreset); + return presets().map(p => ``).join("") + ``; +} +function mixFoot(names) { + const saved = songMixes[E.entry.key]; const lock = S.lockedPreset && allPresets().find(p => p.id === S.lockedPreset); const savedNote = saved ? (sameMix(saved, S.mix, names) ? "Using this song's saved mix." : "Changed from this song's saved mix.") : ""; - return karaokeHtml() + ` -
${presets().map(p => ``).join("")}
- ${names.map(n => { - const s = setting(n), g = stemGain(n, names); - return `
${esc(n)} - - -
`; - }).join("")} -
+ return `
${saved ? `` : ""} @@ -243,6 +239,41 @@ function mixerHtml() {

${savedNote} ${S.karaoke ? "Karaoke is on, so saved mixes are ignored until you turn it off." : lock ? `${esc(presetLabel(lock.name))} is locked, so every song starts with it. Long press it to unlock.` : (S.keepMix ? "Songs without a saved mix keep this mix." : "Songs without a saved mix start at full mix.") + " Long press a preset to lock it."}

`; } +function mixerHtml() { + const names = mixNames(); + if (!names.length) return `

${E.loading ? "Loading stems…" : Q.cur() ? "This track has no stems yet. Right-click it and pick Stem Now." : "Play something with stems to mix it."}

`; + return `
+
${presetsHtml(names)}
+ ${names.map(n => { + const s = setting(n); + return `
+ ${esc(n)} + + ${pct(s.level)} + +
`; + }).join("")} +
${mixFoot(names)}
`; +} +// Updates the open mixer in place, so taps answer at once and the slider being dragged keeps +// its grip. False when the stems changed and it needs a full render. +function syncMixer() { + const box = $("#mixer"), names = mixNames(); + if (!box || box.dataset.names !== names.join(",")) return false; + const presetBox = box.querySelector(".presets"), html = presetsHtml(names); + if (presetBox.innerHTML !== html) presetBox.innerHTML = html; + for (const row of box.querySelectorAll(".stem")) { + const n = row.dataset.stem, st = setting(n), r = row.querySelector("input"); + row.classList.toggle("silent", !stemGain(n, names)); + row.classList.toggle("muted", !!st.muted); + row.querySelector(".mute").classList.toggle("on", !!st.muted); + row.querySelector(".solo").classList.toggle("on", !!st.solo); + if (document.activeElement !== r) r.value = st.level; + row.querySelector(".pct").textContent = pct(st.level); + } + box.querySelector("#mixfoot").innerHTML = mixFoot(names); + return true; +} function queueHtml() { if (!Q.items.length) return `

Empty.

`; @@ -292,8 +323,8 @@ d$.addEventListener("click", ev => { else if (ds.solo) { S.mix[ds.solo] = { ...setting(ds.solo), solo: !setting(ds.solo).solo }; mixChanged(); } else if ("kara" in ds) setKaraoke(!S.karaoke); else if (ds.kmode) setKaraokeMode(ds.kmode); - else if ("savemix" in ds) { saveSongMix(E.entry.key, S.mix); toast("Saved the mix for this song"); UI.drawer(); } - else if ("forgetmix" in ds) { forgetSongMix(E.entry.key); UI.drawer(); } + else if ("savemix" in ds) { saveSongMix(E.entry.key, S.mix); toast("Saved the mix for this song"); syncMixer() || UI.drawer(); } + else if ("forgetmix" in ds) { forgetSongMix(E.entry.key); syncMixer() || UI.drawer(); } else if ("mixtopl" in ds) { const r = b.getBoundingClientRect(); pickPlaylist(r.left, r.bottom, [Q.cur()], S.mix); } else if ("qclear" in ds) Q.clear(); else if (ds.qx) Q.remove(+ds.qx); @@ -302,11 +333,14 @@ d$.addEventListener("click", ev => { }); d$.addEventListener("input", ev => { const ds = ev.target.dataset; - if (ds.level) { S.mix[ds.level] = { ...setting(ds.level), level: +ev.target.value }; E.applyGains(); Wave.draw(); save(); } + if (ds.level) { + S.mix[ds.level] = { ...setting(ds.level), level: +ev.target.value }; E.applyGains(); Wave.draw(); + const p = ev.target.parentElement.querySelector(".pct"); if (p) p.textContent = pct(+ev.target.value); + } if (ds.softdb) $("#softdb").textContent = ev.target.value + " dB"; }); d$.addEventListener("change", ev => { - if (ev.target.dataset.level) UI.drawer(); + if (ev.target.dataset.level) { save(); syncMixer(); } if (ev.target.dataset.softdb) setKaraokeMode("soft", +ev.target.value); }); // Long press (or right-click) a preset chip to lock it. @@ -420,21 +454,24 @@ on("queue", () => { if (drawer === "queue") UI.drawer(); }); on("radio", () => { UI.track(); UI.transport(); const el = $("#stations"); if (el) el.innerHTML = stationsHtml(); }); on("mix", () => { Wave.draw(); UI.transport(); - if (drawer === "mixer") UI.drawer(); + if (drawer === "mixer") syncMixer() || UI.drawer(); else if (drawer === "lyrics" && $("#lyrhead")) $("#lyrhead").innerHTML = mixNames().includes("vocals") ? karaokeHtml() : ""; }); // ---- live stem status --------------------------------------------------------------------------- const base = p => (p || "").split("/").pop().replace(/\.[^.]+$/, ""); +// Stems are the norm, so only songs without them get a tag (once the index has loaded). const badge = t => { - if (Stems.find(t)) return 'STEMS'; + if (Stems.find(t)) return ""; const s = Live.state(t); - return s ? `${{ queued: "QUEUED", stemming: "STEMMING", failed: "FAILED" }[s]}` : ""; + if (s) return `${{ queued: "QUEUED", stemming: "STEMMING", failed: "FAILED" }[s]}`; + return Stems.entries.length ? 'NO STEMS' : ""; }; // Refreshes playing, stem and download markers in whatever is on screen. function marks() { const id = Q.cur()?.id; + document.body.classList.toggle("stems-ready", Stems.entries.length > 0); for (const r of $$("tr[data-list]", view)) { const t = lists[r.dataset.list]?.[+r.dataset.i]; if (!t) continue; @@ -549,11 +586,13 @@ function playFrom(listId, i) { Q.playList(vis.includes(pick) ? vis : all, Math.max(0, (vis.includes(pick) ? vis : all).indexOf(pick)), false); } -function card({ href, img: src, t, s = "", round, kind, srv, key }) { +// A broken image tries its fallback (data-fb) once, then shows the placeholder. +const FB = `onerror="if(this.dataset.fb){this.src=this.dataset.fb;this.dataset.fb=''}else{this.onerror=null;this.src='data:image/gif;base64,R0lGODlhAQABAAAAACw='}"`; +function card({ href, img: src, fb, t, s = "", round, kind, srv, key }) { const nk = kind === "album" || kind === "artist" ? nameKey(t) : ""; const hide = nk && !stemSets()[kind].has(nk); return ` - ${src ? `` : `
`}
${esc(t)}
${esc(s)}
`; + ${src ? `` : `
`}
${esc(t)}
${esc(s)}
`; } const albumCard = m => card({ href: `#/album/${m._srv}:${m.ratingKey}`, img: img(m._srv, m.thumb), t: m.title, s: [m.parentTitle, m.year].filter(Boolean).join(" · "), kind: "album", srv: m._srv, key: m.ratingKey }); const artistCard = m => card({ href: `#/artist/${m._srv}:${m.ratingKey}`, img: img(m._srv, m.thumb), t: m.title, round: true, kind: "artist", srv: m._srv, key: m.ratingKey }); @@ -588,7 +627,7 @@ const actions = id => `
`; -const hero = (src, kind, title, sub, id, round) => `
${src ? `` : `
`} +const hero = (src, kind, title, sub, id, round, fb) => `
${src ? `` : `
`}
${kind}

${esc(title)}

${sub}
${id ? actions(id) : ""}
`; function needPlex() { @@ -775,7 +814,7 @@ const routes = { if (my !== seq) return; pls = st.random ? pls.sort(() => Math.random() - 0.5) : pls.sort(comparator(st.param)); count(pls.length + playlists.length, "playlist"); - $("#plexpl").innerHTML = pls.length ? `
${pls.map(p => card({ href: `#/playlist/${p._srv}:${p.ratingKey}`, img: img(p._srv, p.composite || p.thumb), t: p.title, s: plural(p.leafCount || 0, "track") })).join("")}
` + $("#plexpl").innerHTML = pls.length ? `
${pls.map(p => card({ href: `#/playlist/${p._srv}:${p.ratingKey}`, img: img(p._srv, p.thumb || p.composite), fb: p.composite && rawImg(p._srv, p.composite), t: p.title, s: plural(p.leafCount || 0, "track") })).join("")}
` : `

No music playlists.

`; }, async album(my, arg) { @@ -805,7 +844,7 @@ const routes = { const [info, items] = await Promise.all([px(srv, `/playlists/${key}`), px(srv, `/playlists/${key}/items`)]); if (my !== seq) return; const p = info.Metadata?.[0] || {}, tracks = sortTracks((items.Metadata || []).map(m => track(srv, m)), sortState("playlist")); - view.innerHTML = hero(img(srv, p.composite || p.thumb, 420), "Playlist", p.title, plural(tracks.length, "track"), "playlist") + view.innerHTML = hero(img(srv, p.thumb || p.composite, 420), "Playlist", p.title, plural(tracks.length, "track"), "playlist", false, p.composite && rawImg(srv, p.composite, 420)) + `
${stemsChip()}${sortControl("playlist")}
` + trackTable("playlist", tracks); }, async stemplaylist(my, id) { diff --git a/web/index.html b/web/index.html index 42e0ebd..ca2b304 100644 --- a/web/index.html +++ b/web/index.html @@ -29,10 +29,13 @@
diff --git a/web/plex.js b/web/plex.js index 2431262..191e4be 100644 --- a/web/plex.js +++ b/web/plex.js @@ -26,14 +26,17 @@ export async function px(srv, path, params = {}) { export function img(srvId, thumb, size = 300) { const s = server(srvId); if (!thumb || !s) return ""; - // Playlist composites are already images Plex renders at any size; the photo transcoder - // can't fetch them, so ask for them directly. - if (thumb.includes("/composite/")) return `${s.url}${thumb}${thumb.includes("?") ? "&" : "?"}width=${size}&height=${size}&X-Plex-Token=${s.token}`; return thumb && s ? `${s.url}/photo/:/transcode?width=${size}&height=${size}&minSize=1&upscale=1&url=${encodeURIComponent(thumb)}&X-Plex-Token=${s.token}` : ""; } +// Straight from Plex, no transcoder: the fallback for playlist composites. +export function rawImg(srvId, path, size = 300) { + const s = server(srvId); + return s && path ? `${s.url}${path}${path.includes("?") ? "&" : "?"}width=${size}&height=${size}&X-Plex-Token=${s.token}` : ""; +} + export function partUrl(t) { const s = server(t.srv); return s && t.part ? `${s.url}${t.part}?X-Plex-Token=${s.token}` : null; diff --git a/web/style.css b/web/style.css index ab3fd79..9ffb745 100644 --- a/web/style.css +++ b/web/style.css @@ -45,7 +45,7 @@ h2 { font-size: 17px; margin: 28px 0 12px; } select, textarea, input[type=text], input[type=url], input[type=password] { background: var(--raised); border: 1px solid var(--line); border-radius: 8px; padding: 7px 10px; outline: none; } .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 22px 18px; } -.card { display: block; min-width: 0; } +.card { display: block; min-width: 0; content-visibility: auto; contain-intrinsic-size: auto 210px; } .card img, .card .ph { width: 100%; aspect-ratio: 1; border-radius: 10px; object-fit: cover; background: var(--raised); display: block; transition: transform .15s; } .card:hover img { transform: translateY(-2px); } .card.round img, .card.round .ph { border-radius: 50%; } @@ -77,7 +77,8 @@ select, textarea, input[type=text], input[type=url], input[type=password] { back .tracks tr:hover .acts button { opacity: 1; } .tracks .acts button:hover { color: var(--text); background: var(--raised); } .tag { display: inline-block; font-size: 10px; font-weight: 700; letter-spacing: .05em; color: var(--muted); border: 1px solid currentColor; border-radius: 4px; padding: 0 4px; margin-left: 8px; vertical-align: 1px; } -.tag.stems { color: var(--accent); } +.tag.nostems { color: var(--muted); opacity: .8; } +body.stems-ready .card.nostem .t::after { content: "NO STEMS"; font-size: 9px; font-weight: 700; letter-spacing: .05em; color: var(--muted); border: 1px solid currentColor; border-radius: 4px; padding: 0 4px; margin-left: 6px; vertical-align: 1px; } .tag.queued { color: var(--muted); } .tag.stemming { color: var(--accent); animation: pulse 1.4s ease-in-out infinite; } .tag.failed { color: #e5534b; } @@ -175,13 +176,20 @@ input[type=color] { width: 40px; height: 28px; padding: 0; border: 1px solid var .chip { background: var(--raised); border-radius: 999px; padding: 5px 12px; font-size: 13px; font-weight: 500; } .chip.on { background: var(--accent); color: var(--accent-ink); } .chip:disabled { opacity: .35; cursor: default; } -.stem { display: grid; grid-template-columns: 1fr auto auto; gap: 8px 6px; align-items: center; padding: 12px 0; border-top: 1px solid var(--line); } -.stem .name { text-transform: capitalize; font-weight: 600; } -.stem.silent .name { color: var(--muted); } -.stem input { grid-column: 1 / -1; width: 100%; } -.ms { width: 30px; height: 26px; border-radius: 6px; background: var(--raised); font-size: 12px; font-weight: 700; color: var(--muted); } -.ms.on { background: var(--text); color: var(--bg); } -.ms.solo.on { background: var(--accent); color: var(--accent-ink); } +.stem { --c: #8e8e93; display: grid; grid-template-columns: 96px 1fr 40px auto auto; gap: 8px; align-items: center; padding: 10px 0; border-top: 1px solid var(--line); } +.stem .name { text-transform: capitalize; font-weight: 600; display: flex; align-items: center; gap: 8px; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.stem .name i { width: 9px; height: 9px; border-radius: 50%; background: var(--c); flex: none; } +.stem input { width: 100%; accent-color: var(--c); } +.stem .pct { font-size: 12px; color: var(--muted); text-align: right; font-variant-numeric: tabular-nums; } +.stem.silent .name, .stem.silent .pct { color: var(--muted); } +.stem.silent .name i, .stem.silent input { opacity: .35; } +.ms { width: 32px; height: 30px; border-radius: 8px; background: var(--raised); font-size: 12px; font-weight: 800; color: var(--muted); + transition: transform .08s, background-color .12s, color .12s; touch-action: manipulation; -webkit-tap-highlight-color: transparent; } +.ms:active { transform: scale(.88); } +.ms.mute.on { background: #ff453a; color: #fff; } +.ms.solo.on { background: #ffcc00; color: #1a1400; } +.chip, .pill, .seg button, .transport button { touch-action: manipulation; -webkit-tap-highlight-color: transparent; } +.chip:active:not(:disabled), .pill:active { transform: scale(.94); } .q-item { display: flex; gap: 10px; align-items: center; padding: 7px 6px; border-radius: 8px; cursor: pointer; } .q-item:hover { background: var(--raised); } .q-item img { width: 38px; height: 38px; border-radius: 6px; object-fit: cover; background: var(--raised); flex: none; } @@ -194,9 +202,11 @@ input[type=color] { width: 40px; height: 28px; padding: 0; border: 1px solid var .q-item .x { color: var(--muted); font-size: 18px; padding: 0 4px; opacity: 0; } .q-item:hover .x { opacity: 1; } -#player { position: fixed; left: 0; right: 0; bottom: 0; height: var(--player-h); background: var(--glass); backdrop-filter: blur(20px); +#player { position: fixed; left: 0; right: 0; bottom: 0; height: var(--player-h); background: var(--panel); border-top: 1px solid var(--line); display: grid; grid-template-columns: minmax(180px, 1fr) minmax(320px, 1.6fr) minmax(180px, 1fr); align-items: center; gap: 20px; padding: 0 20px; } -#player.empty .center, #player.empty .right { opacity: .35; pointer-events: none; } +#player.empty .center, #player.empty .right, #player.empty #b-queue { opacity: .35; pointer-events: none; } +.left { display: flex; align-items: center; gap: 10px; min-width: 0; } +#b-queue { flex: none; } .np { display: flex; gap: 12px; align-items: center; min-width: 0; } #np-art { width: 58px; height: 58px; border-radius: 8px; object-fit: cover; background: var(--raised); flex: none; } #np-art:not([src]) { display: none; } @@ -244,6 +254,7 @@ input[type=range] { accent-color: var(--accent); } #player { grid-template-columns: 1fr auto; grid-template-rows: auto auto; gap: 8px 12px; padding: 10px 16px calc(10px + env(safe-area-inset-bottom)); } .center { grid-column: 1 / -1; grid-row: 2; } .right #volume { display: none; } + .stem { grid-template-columns: 78px 1fr 36px auto auto; gap: 6px; } .hero { flex-direction: column; align-items: flex-start; } .hero img { width: 160px; height: 160px; } .grid { grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 16px 12px; }