Add continuous mixer stream and sound sets

This commit is contained in:
Hermes Agent
2026-05-21 00:16:13 +02:00
parent 232e6923e3
commit 23391a2d3e
8 changed files with 680 additions and 570 deletions

View File

@@ -4,7 +4,7 @@ ENV NODE_ENV=production
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm install --omit=dev --no-audit --no-fund
RUN apk add --no-cache ffmpeg && npm install --omit=dev --no-audit --no-fund
COPY src ./src
COPY public ./public

View File

@@ -7,7 +7,7 @@
"scripts": {
"start": "node src/server.js",
"dev": "node --watch src/server.js",
"check": "node --check src/server.js && node --check src/filestash.js && node --check src/effects.js && node --check src/homeassistant.js && node --check src/routes.js"
"check": "node --check src/server.js && node --check src/filestash.js && node --check src/effects.js && node --check src/homeassistant.js && node --check src/streamMixer.js && node --check src/routes.js"
},
"engines": {
"node": ">=20"

View File

@@ -1,8 +1,12 @@
(() => {
'use strict';
const STORAGE_KEY = 'arcana-fx-sets-v2';
const els = {
grid: document.getElementById('grid'),
setGrid: document.getElementById('set-grid'),
setEmpty: document.getElementById('set-empty'),
empty: document.getElementById('empty'),
search: document.getElementById('search'),
categories: document.getElementById('categories'),
@@ -10,26 +14,44 @@
statusText: document.getElementById('status-text'),
refresh: document.getElementById('refresh-btn'),
stop: document.getElementById('stop-btn'),
stream: document.getElementById('stream-btn'),
streamStop: document.getElementById('stream-stop-btn'),
now: document.getElementById('now-btn'),
nowCount: document.getElementById('now-count'),
entityLabel: document.getElementById('entity-label'),
countLabel: document.getElementById('count-label'),
lights: document.getElementById('lights'),
setSelect: document.getElementById('set-select'),
newSet: document.getElementById('new-set-btn'),
renameSet: document.getElementById('rename-set-btn'),
deleteSet: document.getElementById('delete-set-btn'),
setTitle: document.getElementById('set-title'),
setCount: document.getElementById('set-count'),
drawer: document.getElementById('now-drawer'),
backdrop: document.getElementById('drawer-backdrop'),
drawerClose: document.getElementById('drawer-close'),
drawerStopAll: document.getElementById('drawer-stop-all'),
activeList: document.getElementById('active-list'),
activeEmpty: document.getElementById('active-empty'),
};
const state = {
effects: [],
byPath: new Map(),
categories: [],
activeCategory: 'all',
search: '',
playingPath: null,
busy: false,
streamOn: false,
active: [],
sets: loadSets(),
currentSetId: null,
};
const LIGHT_ICONS = {
flame: '\u{1F525}',
moon: '\u{1F319}',
sparkles: '\u{2728}',
droplet: '\u{1FA78}',
};
if (!state.sets.length) state.sets = [{ id: uid(), name: 'Session Favorites', paths: [] }];
state.currentSetId = state.sets[0].id;
function uid() { return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`; }
function currentSet() { return state.sets.find((s) => s.id === state.currentSetId) || state.sets[0]; }
function setStatus(kind, text) {
els.status.classList.remove('ok', 'busy', 'err');
@@ -38,190 +60,277 @@
}
function escapeHtml(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}
function renderCategories() {
const all = ['all', ...state.categories];
els.categories.innerHTML = all
.map((c) => {
const label = c === 'all' ? 'All' : c;
const active = state.activeCategory === c ? ' active' : '';
return `<button class="chip${active}" data-cat="${escapeHtml(c)}" type="button">${escapeHtml(label)}</button>`;
})
.join('');
function loadSets() {
try {
const parsed = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
return Array.isArray(parsed) ? parsed.filter((s) => s && s.id && s.name && Array.isArray(s.paths)) : [];
} catch { return []; }
}
function renderGrid() {
const q = state.search.trim().toLowerCase();
const filtered = state.effects.filter((e) => {
if (state.activeCategory !== 'all' && e.category !== state.activeCategory) return false;
if (!q) return true;
return (
e.name.toLowerCase().includes(q) ||
e.category.toLowerCase().includes(q) ||
e.path.toLowerCase().includes(q)
);
});
els.empty.hidden = filtered.length !== 0;
els.countLabel.textContent = `${filtered.length} of ${state.effects.length} effects`;
els.grid.innerHTML = filtered
.map((e) => {
const playing = state.playingPath === e.path ? ' playing' : '';
return `
<button class="tile${playing}" type="button" data-path="${escapeHtml(e.path)}">
<div class="name">${escapeHtml(e.name)}</div>
<div class="meta">
<span class="tag">${escapeHtml(e.category)}</span>
<span class="tag">${escapeHtml(e.type.toUpperCase())}</span>
</div>
<div class="path" title="${escapeHtml(e.path)}">${escapeHtml(e.path)}</div>
</button>`;
})
.join('');
}
function renderLights(cfg) {
if (!cfg || !Array.isArray(cfg.placeholders)) {
els.lights.innerHTML = '';
return;
}
els.lights.innerHTML = cfg.placeholders
.map((p) => {
const icon = LIGHT_ICONS[p.icon] || '✨';
return `
<div class="light" aria-disabled="true">
<span class="soon">Soon</span>
<span class="icon">${icon}</span>
<span class="lbl">${escapeHtml(p.name)}</span>
</div>`;
})
.join('');
}
function saveSets() { localStorage.setItem(STORAGE_KEY, JSON.stringify(state.sets)); }
async function fetchJson(url, opts) {
const res = await fetch(url, opts);
const text = await res.text();
let body = null;
if (text) {
try { body = JSON.parse(text); } catch { body = { error: text }; }
}
if (text) { try { body = JSON.parse(text); } catch { body = { error: text }; } }
if (!res.ok) {
const msg = (body && body.error) || `${res.status} ${res.statusText}`;
const err = new Error(msg);
const err = new Error((body && body.error) || `${res.status} ${res.statusText}`);
err.status = res.status;
throw err;
}
return body || {};
}
function renderCategories() {
const all = ['all', ...state.categories];
els.categories.innerHTML = all.map((c) => {
const active = state.activeCategory === c ? ' active' : '';
const label = c === 'all' ? 'All' : c;
return `<button class="chip${active}" data-cat="${escapeHtml(c)}" type="button">${escapeHtml(label)}</button>`;
}).join('');
}
function visibleEffects() {
const q = state.search.trim().toLowerCase();
return state.effects.filter((e) => {
if (state.activeCategory !== 'all' && e.category !== state.activeCategory) return false;
if (!q) return true;
const haystack = `${e.name} ${e.category} ${e.type} ${e.path.replace(/[/.\\_-]+/g, ' ')}`.toLowerCase();
return haystack.includes(q);
}).slice(0, 240);
}
function tile(effect, { inSetView = false } = {}) {
const set = currentSet();
const inSet = set.paths.includes(effect.path);
return `
<article class="tile" data-path="${escapeHtml(effect.path)}">
<button class="play-hit" type="button" data-action="play" title="Play ${escapeHtml(effect.name)}">
<div class="name">${escapeHtml(effect.name)}</div>
<div class="meta">
<span class="tag">${escapeHtml(effect.category)}</span>
<span class="tag">${escapeHtml(effect.type.toUpperCase())}</span>
</div>
</button>
<div class="tile-actions">
${inSetView ? `<button class="mini danger" data-action="remove-set" type="button">Remove</button>` : `<button class="mini ${inSet ? 'ok' : ''}" data-action="toggle-set" type="button">${inSet ? 'In set' : '+ Set'}</button>`}
</div>
</article>`;
}
function renderGrid() {
const filtered = visibleEffects();
els.empty.hidden = filtered.length !== 0;
els.countLabel.textContent = `${state.effects.length} effects · showing ${filtered.length}`;
els.grid.innerHTML = filtered.map((e) => tile(e)).join('');
renderSet();
}
function renderSetsSelect() {
els.setSelect.innerHTML = state.sets.map((s) => `<option value="${escapeHtml(s.id)}">${escapeHtml(s.name)}</option>`).join('');
els.setSelect.value = state.currentSetId;
}
function renderSet() {
renderSetsSelect();
const set = currentSet();
const effects = set.paths.map((p) => state.byPath.get(p)).filter(Boolean);
els.setTitle.textContent = set.name;
els.setCount.textContent = `${effects.length} item${effects.length === 1 ? '' : 's'}`;
els.setEmpty.hidden = effects.length > 0;
els.setGrid.innerHTML = effects.map((e) => tile(e, { inSetView: true })).join('');
}
function renderActive() {
els.nowCount.textContent = String(state.active.length);
els.activeEmpty.hidden = state.active.length > 0;
els.activeList.innerHTML = state.active.map((a) => `
<div class="active-row">
<div>
<strong>${escapeHtml(a.name)}</strong>
<span>${escapeHtml(a.category)} · ${Math.round((a.ageMs || 0) / 1000)}s</span>
${a.error ? `<em>${escapeHtml(a.error)}</em>` : ''}
</div>
<button class="mini danger" data-stop-id="${escapeHtml(a.id)}">Stop</button>
</div>`).join('');
}
async function loadConfig() {
try {
const cfg = await fetchJson('/api/config');
if (cfg.mediaPlayer) {
els.entityLabel.textContent = cfg.mediaPlayer;
}
renderLights(cfg.lightControl);
} catch (err) {
console.warn('config load failed', err);
}
if (cfg.mediaPlayer) els.entityLabel.textContent = cfg.mediaPlayer;
} catch (err) { console.warn('config load failed', err); }
}
async function loadEffects({ force = false } = {}) {
setStatus('busy', force ? 'Rescanning the share…' : 'Summoning effects…');
setStatus('busy', force ? 'Rescanning library…' : 'Loading effects…');
try {
const url = force ? '/api/effects?refresh=1' : '/api/effects';
const data = await fetchJson(url);
const data = await fetchJson(force ? '/api/effects?refresh=1' : '/api/effects');
state.effects = Array.isArray(data.effects) ? data.effects : [];
state.byPath = new Map(state.effects.map((e) => [e.path, e]));
state.categories = Array.isArray(data.categories) ? data.categories : [];
if (!state.categories.includes(state.activeCategory) && state.activeCategory !== 'all') {
state.activeCategory = 'all';
}
if (!state.categories.includes(state.activeCategory) && state.activeCategory !== 'all') state.activeCategory = 'all';
renderCategories();
renderGrid();
setStatus('ok', `Ready — ${state.effects.length} effect${state.effects.length === 1 ? '' : 's'} loaded`);
setStatus('ok', `Ready — ${state.effects.length} effects`);
} catch (err) {
console.error(err);
setStatus('err', `Failed to load effects: ${err.message}`);
setStatus('err', `Load failed: ${err.message}`);
}
}
async function play(effectPath) {
if (state.busy) return;
state.busy = true;
setStatus('busy', `Casting — ${effectPath.split('/').pop()}`);
setStatus('busy', `Injecting — ${effectPath.split('/').pop()}`);
try {
const res = await fetchJson('/api/play', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: effectPath }),
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path: effectPath }),
});
state.playingPath = effectPath;
renderGrid();
const name = (res.played && res.played.name) || effectPath;
setStatus('ok', `Playing — ${name}`);
state.active = (res.stream && res.stream.active) || state.active;
renderActive();
setStatus('ok', `Injected — ${(res.injected && res.injected.name) || effectPath}`);
} catch (err) {
console.error(err);
setStatus('err', `Play failed: ${err.message}`);
} finally {
state.busy = false;
}
}
async function stop() {
async function startStream() {
if (state.busy) return;
state.busy = true;
setStatus('busy', 'Silencing…');
setStatus('busy', 'Starting continuous device stream…');
try {
await fetchJson('/api/stop', { method: 'POST' });
state.playingPath = null;
renderGrid();
setStatus('ok', 'Stopped');
await fetchJson('/api/stream/start', { method: 'POST' });
state.streamOn = true;
els.stream.textContent = 'Restart device stream';
setStatus('ok', 'Device stream running — clicks will mix instead of replacing playback');
} catch (err) {
console.error(err);
setStatus('err', `Stop failed: ${err.message}`);
} finally {
state.busy = false;
}
setStatus('err', `Stream start failed: ${err.message}`);
} finally { state.busy = false; }
}
// --- Event wiring ---
async function stopDeviceStream() {
setStatus('busy', 'Stopping device stream…');
try {
await fetchJson('/api/stream/stop', { method: 'POST' });
state.streamOn = false;
state.active = [];
els.stream.textContent = 'Start device stream';
renderActive();
setStatus('ok', 'Device stream stopped');
} catch (err) { setStatus('err', `Stop failed: ${err.message}`); }
}
els.grid.addEventListener('click', (e) => {
const btn = e.target.closest('.tile');
if (!btn) return;
const path = btn.dataset.path;
if (path) play(path);
});
async function stopEffects() {
try {
const res = await fetchJson('/api/stop', { method: 'POST' });
state.active = (res.stream && res.stream.active) || [];
renderActive();
setStatus('ok', 'Stopped all injected effects');
} catch (err) { setStatus('err', `Stop failed: ${err.message}`); }
}
els.categories.addEventListener('click', (e) => {
const btn = e.target.closest('.chip');
if (!btn) return;
state.activeCategory = btn.dataset.cat || 'all';
renderCategories();
async function refreshActive() {
try {
const res = await fetchJson('/api/stream/status');
state.active = (res.stream && res.stream.active) || [];
renderActive();
} catch { /* status polling is best-effort */ }
}
function toggleSet(effectPath) {
const set = currentSet();
const idx = set.paths.indexOf(effectPath);
if (idx >= 0) set.paths.splice(idx, 1); else set.paths.push(effectPath);
saveSets();
renderGrid();
});
}
function removeFromSet(effectPath) {
const set = currentSet();
set.paths = set.paths.filter((p) => p !== effectPath);
saveSets();
renderGrid();
}
function newSet() {
const name = prompt('Set name?', 'New Encounter');
if (!name) return;
const set = { id: uid(), name: name.trim(), paths: [] };
state.sets.push(set);
state.currentSetId = set.id;
saveSets();
renderGrid();
}
function renameSet() {
const set = currentSet();
const name = prompt('Rename set:', set.name);
if (!name) return;
set.name = name.trim();
saveSets();
renderGrid();
}
function deleteSet() {
if (state.sets.length === 1) return alert('Keep at least one set.');
const set = currentSet();
if (!confirm(`Delete set "${set.name}"?`)) return;
state.sets = state.sets.filter((s) => s.id !== set.id);
state.currentSetId = state.sets[0].id;
saveSets();
renderGrid();
}
function openDrawer() { els.drawer.removeAttribute('aria-hidden'); els.backdrop.hidden = false; refreshActive(); }
function closeDrawer() { els.drawer.setAttribute('aria-hidden', 'true'); els.backdrop.hidden = true; }
function gridClick(e) {
const action = e.target.closest('[data-action]');
const tileEl = e.target.closest('.tile');
if (!action || !tileEl) return;
const path = tileEl.dataset.path;
if (action.dataset.action === 'play') play(path);
if (action.dataset.action === 'toggle-set') toggleSet(path);
if (action.dataset.action === 'remove-set') removeFromSet(path);
}
els.grid.addEventListener('click', gridClick);
els.setGrid.addEventListener('click', gridClick);
els.categories.addEventListener('click', (e) => {
const btn = e.target.closest('.chip'); if (!btn) return;
state.activeCategory = btn.dataset.cat || 'all'; renderCategories(); renderGrid();
});
let searchTimer = null;
els.search.addEventListener('input', () => {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => {
state.search = els.search.value;
renderGrid();
}, 80);
searchTimer = setTimeout(() => { state.search = els.search.value; renderGrid(); }, 80);
});
els.refresh.addEventListener('click', () => loadEffects({ force: true }));
els.stop.addEventListener('click', stopEffects);
els.stream.addEventListener('click', startStream);
els.streamStop.addEventListener('click', stopDeviceStream);
els.drawerStopAll.addEventListener('click', stopEffects);
els.now.addEventListener('click', openDrawer);
els.drawerClose.addEventListener('click', closeDrawer);
els.backdrop.addEventListener('click', closeDrawer);
els.setSelect.addEventListener('change', () => { state.currentSetId = els.setSelect.value; renderGrid(); });
els.newSet.addEventListener('click', newSet);
els.renameSet.addEventListener('click', renameSet);
els.deleteSet.addEventListener('click', deleteSet);
els.activeList.addEventListener('click', async (e) => {
const btn = e.target.closest('[data-stop-id]'); if (!btn) return;
await fetchJson('/api/play/stop', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: btn.dataset.stopId }) });
refreshActive();
});
els.refresh.addEventListener('click', () => loadEffects({ force: true }));
els.stop.addEventListener('click', stop);
// --- Boot ---
loadConfig();
loadEffects();
renderSetsSelect();
renderActive();
setInterval(refreshActive, 1500);
})();

View File

@@ -15,56 +15,80 @@
<span class="sigil">&#x1F52E;</span>
<div>
<h1>Arcana FX</h1>
<p class="tagline">Dungeon Master&rsquo;s Control Room</p>
<p class="tagline">D&D soundboard mixer</p>
</div>
</div>
<div class="status" id="status">
<span class="dot" id="status-dot"></span>
<span id="status-text">Summoning effects&hellip;</span>
<span id="status-text">Loading effects</span>
</div>
<div class="actions">
<button id="refresh-btn" class="ghost" title="Rescan share">Rescan</button>
<button id="stop-btn" class="danger" title="Stop current playback">&#x25A0; Stop</button>
<button id="stream-btn" class="primary" title="Start the continuous Home Assistant stream">Start device stream</button>
<button id="now-btn" class="ghost" title="Show currently playing effects">Now Playing <span id="now-count">0</span></button>
<button id="stop-btn" class="danger" title="Stop injected effects">Stop FX</button>
</div>
</header>
<main>
<section class="panel">
<div class="panel-head">
<h2>Sound Effects</h2>
<div class="panel-controls">
<input id="search" type="search" placeholder="Search the grimoire&hellip;" autocomplete="off" />
</div>
<section class="panel hero-panel">
<div>
<h2>Prepared Sets</h2>
<p class="muted">Main workflow: build encounter sets, then fire sounds from the set during play.</p>
</div>
<div class="set-tools">
<select id="set-select" aria-label="Current set"></select>
<button id="new-set-btn" class="ghost">New set</button>
<button id="rename-set-btn" class="ghost">Rename</button>
<button id="delete-set-btn" class="danger ghost">Delete</button>
</div>
<div id="categories" class="categories" role="tablist" aria-label="Categories"></div>
<div id="grid" class="grid" aria-live="polite"></div>
<p id="empty" class="empty" hidden>No effects match your incantation.</p>
</section>
<section class="panel future">
<section class="panel">
<div class="panel-head">
<h2>Light Control</h2>
<span class="badge">Coming soon</span>
<h2 id="set-title">Current Set</h2>
<span class="badge" id="set-count">0 items</span>
</div>
<p class="muted">
A scrying mirror for the lantern circuits. Coloured washes, flicker spells, and
power runes will appear here once the relays are bound.
</p>
<div id="lights" class="lights"></div>
<div id="set-grid" class="grid set-grid" aria-live="polite"></div>
<p id="set-empty" class="empty">No effects in this set yet. Search below and use + Set.</p>
</section>
<section class="panel library-panel">
<div class="panel-head">
<h2>Adhoc Library</h2>
<div class="panel-controls">
<input id="search" type="search" placeholder="Search names, categories, tags…" autocomplete="off" />
</div>
</div>
<div id="categories" class="categories" role="tablist" aria-label="Categories"></div>
<div id="grid" class="grid" aria-live="polite"></div>
<p id="empty" class="empty" hidden>No effects match the search.</p>
</section>
</main>
<footer>
<span>Bound to <code id="entity-label">media_player.&hellip;</code></span>
<span class="sep">&middot;</span>
<span>Device: <code id="entity-label">media_player.</code></span>
<span class="sep">·</span>
<span id="count-label">0 effects</span>
<span class="sep">·</span>
<button id="refresh-btn" class="linkish" title="Rescan share">Rescan library</button>
</footer>
<div id="drawer-backdrop" class="drawer-backdrop" hidden></div>
<aside id="now-drawer" class="drawer" aria-label="Now playing" aria-hidden="true">
<div class="drawer-head">
<h2>Now Playing</h2>
<button id="drawer-close" class="ghost">Close</button>
</div>
<div class="drawer-actions">
<button id="drawer-stop-all" class="danger">Stop all effects</button>
<button id="stream-stop-btn" class="danger ghost">Stop device stream</button>
</div>
<div id="active-list" class="active-list"></div>
<p id="active-empty" class="empty">Nothing is currently injected into the stream.</p>
</aside>
<script src="/app.js"></script>
</body>
</html>

View File

@@ -1,7 +1,6 @@
:root {
--bg: #0b0a14;
--bg-2: #131127;
--panel: rgba(20, 18, 40, 0.72);
--panel: rgba(20, 18, 40, 0.76);
--panel-border: rgba(140, 110, 220, 0.25);
--ink: #e8e3ff;
--ink-dim: #9c95c4;
@@ -14,355 +13,70 @@
--rune: "Cinzel", "Cormorant Garamond", "Trajan Pro", serif;
--body: "Inter", "Segoe UI", system-ui, sans-serif;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
padding: 0;
min-height: 100vh;
background: radial-gradient(1200px 700px at 20% -10%, #1d1640 0%, transparent 60%),
radial-gradient(900px 600px at 90% 0%, #1a2a44 0%, transparent 55%),
linear-gradient(180deg, var(--bg) 0%, #07060f 100%);
color: var(--ink);
font-family: var(--body);
-webkit-font-smoothing: antialiased;
margin: 0; padding: 0; min-height: 100vh;
background: radial-gradient(1200px 700px at 20% -10%, #1d1640 0%, transparent 60%), radial-gradient(900px 600px at 90% 0%, #1a2a44 0%, transparent 55%), linear-gradient(180deg, var(--bg) 0%, #07060f 100%);
color: var(--ink); font-family: var(--body); -webkit-font-smoothing: antialiased;
}
.aurora {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 0;
background:
radial-gradient(600px 240px at 12% 30%, rgba(110, 255, 200, 0.10), transparent 70%),
radial-gradient(600px 240px at 88% 70%, rgba(179, 136, 255, 0.10), transparent 70%);
filter: blur(20px);
animation: drift 22s ease-in-out infinite alternate;
}
@keyframes drift {
from { transform: translate3d(-15px, -10px, 0); }
to { transform: translate3d(15px, 10px, 0); }
}
.topbar {
position: relative;
z-index: 1;
display: flex;
align-items: center;
gap: 18px;
padding: 18px 28px;
border-bottom: 1px solid var(--panel-border);
backdrop-filter: blur(8px);
}
.brand {
display: flex;
align-items: center;
gap: 14px;
flex: 1;
}
.brand .sigil {
font-size: 34px;
filter: drop-shadow(0 0 12px rgba(179, 136, 255, 0.55));
}
.brand h1 {
margin: 0;
font-family: var(--rune);
letter-spacing: 0.12em;
text-transform: uppercase;
font-size: 22px;
color: var(--ink);
}
.brand .tagline {
margin: 2px 0 0;
color: var(--ink-dim);
font-size: 12px;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.status {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 6px 12px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.04);
border: 1px solid var(--panel-border);
font-size: 13px;
color: var(--ink-dim);
max-width: 50%;
}
.status .dot {
width: 8px; height: 8px; border-radius: 50%;
background: var(--ink-dim);
box-shadow: 0 0 0 0 currentColor;
}
.status.ok .dot { background: var(--accent-2); box-shadow: 0 0 10px var(--accent-2); }
.status.busy .dot { background: var(--warn); box-shadow: 0 0 10px var(--warn); animation: pulse 1.4s infinite; }
.status.err .dot { background: var(--danger); box-shadow: 0 0 10px var(--danger); }
@keyframes pulse {
0%, 100% { transform: scale(1); opacity: 0.95; }
50% { transform: scale(1.3); opacity: 0.6; }
}
.actions { display: flex; gap: 8px; }
button {
appearance: none;
border: 1px solid var(--panel-border);
background: rgba(255, 255, 255, 0.04);
color: var(--ink);
padding: 8px 14px;
border-radius: 10px;
cursor: pointer;
font-family: inherit;
font-size: 13px;
letter-spacing: 0.04em;
transition: transform 0.08s ease, background 0.15s ease, border-color 0.15s ease;
}
button:hover { background: rgba(179, 136, 255, 0.12); border-color: rgba(179, 136, 255, 0.55); }
.aurora { position: fixed; inset: 0; pointer-events: none; z-index: 0; background: radial-gradient(600px 240px at 12% 30%, rgba(110,255,200,.10), transparent 70%), radial-gradient(600px 240px at 88% 70%, rgba(179,136,255,.10), transparent 70%); filter: blur(20px); animation: drift 22s ease-in-out infinite alternate; }
@keyframes drift { from { transform: translate3d(-15px,-10px,0); } to { transform: translate3d(15px,10px,0); } }
.topbar { position: sticky; top: 0; z-index: 5; display: flex; align-items: center; gap: 18px; padding: 16px 28px; border-bottom: 1px solid var(--panel-border); backdrop-filter: blur(12px); background: rgba(10, 8, 20, .72); }
.brand { display: flex; align-items: center; gap: 14px; flex: 1; min-width: 220px; }
.brand .sigil { font-size: 34px; filter: drop-shadow(0 0 12px rgba(179,136,255,.55)); }
.brand h1 { margin: 0; font-family: var(--rune); letter-spacing: .12em; text-transform: uppercase; font-size: 22px; }
.brand .tagline { margin: 2px 0 0; color: var(--ink-dim); font-size: 12px; letter-spacing: .15em; text-transform: uppercase; }
.status { display: inline-flex; align-items: center; gap: 8px; padding: 6px 12px; border-radius: 999px; background: rgba(255,255,255,.04); border: 1px solid var(--panel-border); font-size: 13px; color: var(--ink-dim); max-width: 42%; }
.status .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--ink-dim); }
.status.ok .dot { background: var(--accent-2); box-shadow: 0 0 10px var(--accent-2); }
.status.busy .dot { background: var(--warn); box-shadow: 0 0 10px var(--warn); animation: pulse 1.4s infinite; }
.status.err .dot { background: var(--danger); box-shadow: 0 0 10px var(--danger); }
@keyframes pulse { 0%,100% { transform: scale(1); opacity:.95; } 50% { transform: scale(1.3); opacity:.6; } }
.actions, .set-tools, .drawer-actions { display: flex; gap: 8px; flex-wrap: wrap; }
button, select { appearance: none; border: 1px solid var(--panel-border); background: rgba(255,255,255,.04); color: var(--ink); padding: 8px 14px; border-radius: 10px; cursor: pointer; font-family: inherit; font-size: 13px; letter-spacing: .04em; transition: transform .08s ease, background .15s ease, border-color .15s ease; }
select { min-width: 220px; background: rgba(0,0,0,.25); }
button:hover { background: rgba(179,136,255,.12); border-color: rgba(179,136,255,.55); }
button:active { transform: translateY(1px); }
button.ghost { color: var(--ink-dim); }
button.danger { color: var(--danger); border-color: rgba(255, 91, 110, 0.4); }
button.danger:hover { background: rgba(255, 91, 110, 0.10); border-color: rgba(255, 91, 110, 0.7); }
button:disabled {
opacity: 0.4;
cursor: not-allowed;
filter: grayscale(0.3);
}
main {
position: relative;
z-index: 1;
display: flex;
flex-direction: column;
gap: 24px;
padding: 24px 28px 80px;
}
.panel {
background: var(--panel);
border: 1px solid var(--panel-border);
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: 18px 20px 22px;
backdrop-filter: blur(10px);
}
.panel-head {
display: flex;
align-items: center;
gap: 16px;
margin-bottom: 14px;
}
.panel-head h2 {
margin: 0;
font-family: var(--rune);
font-size: 16px;
letter-spacing: 0.18em;
text-transform: uppercase;
color: var(--ink);
}
button.primary { color: #06140f; background: linear-gradient(135deg, var(--accent-2), #a5ffe1); border-color: rgba(110,255,200,.7); font-weight: 700; }
button.ghost { color: var(--ink-dim); }
button.danger { color: var(--danger); border-color: rgba(255,91,110,.4); }
button.danger:hover { background: rgba(255,91,110,.10); border-color: rgba(255,91,110,.7); }
button.linkish { padding: 0; border: 0; background: transparent; color: var(--accent); }
main { position: relative; z-index: 1; display: flex; flex-direction: column; gap: 18px; padding: 24px 28px 80px; }
.panel { background: var(--panel); border: 1px solid var(--panel-border); border-radius: var(--radius); box-shadow: var(--shadow); padding: 18px 20px 22px; backdrop-filter: blur(10px); }
.hero-panel { display: flex; justify-content: space-between; align-items: center; gap: 18px; }
.panel-head { display: flex; align-items: center; gap: 16px; margin-bottom: 14px; }
h2 { margin: 0; font-family: var(--rune); font-size: 16px; letter-spacing: .18em; text-transform: uppercase; }
.muted { margin: 6px 0 0; color: var(--ink-dim); font-size: 13px; }
.panel-controls { margin-left: auto; }
input[type="search"] {
background: rgba(0, 0, 0, 0.25);
border: 1px solid var(--panel-border);
border-radius: 10px;
color: var(--ink);
padding: 8px 12px;
width: 280px;
font-family: inherit;
font-size: 13px;
outline: none;
}
input[type="search"] { background: rgba(0,0,0,.25); border: 1px solid var(--panel-border); border-radius: 10px; color: var(--ink); padding: 9px 12px; width: 360px; font-family: inherit; font-size: 13px; outline: none; }
input[type="search"]:focus { border-color: var(--accent); }
.badge {
margin-left: 10px;
padding: 3px 8px;
font-size: 11px;
letter-spacing: 0.18em;
text-transform: uppercase;
border-radius: 999px;
background: rgba(255, 180, 84, 0.12);
color: var(--warn);
border: 1px solid rgba(255, 180, 84, 0.35);
}
.categories {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 14px;
}
.chip {
background: rgba(255, 255, 255, 0.03);
border: 1px solid var(--panel-border);
color: var(--ink-dim);
border-radius: 999px;
padding: 5px 12px;
font-size: 12px;
cursor: pointer;
letter-spacing: 0.04em;
transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease;
}
.chip:hover { color: var(--ink); border-color: rgba(179, 136, 255, 0.6); }
.chip.active {
background: rgba(179, 136, 255, 0.15);
border-color: var(--accent);
color: var(--ink);
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
gap: 12px;
}
.tile {
position: relative;
background: linear-gradient(160deg, rgba(255, 255, 255, 0.03), rgba(255, 255, 255, 0.01));
border: 1px solid var(--panel-border);
border-radius: 12px;
padding: 14px 14px 12px;
cursor: pointer;
overflow: hidden;
text-align: left;
color: var(--ink);
transition: transform 0.08s ease, border-color 0.15s ease, background 0.15s ease;
}
.tile::before {
content: "";
position: absolute;
inset: 0;
background: radial-gradient(220px 80px at 30% 0%, rgba(179, 136, 255, 0.18), transparent 60%);
opacity: 0;
transition: opacity 0.2s ease;
pointer-events: none;
}
.tile:hover::before { opacity: 1; }
.tile:hover { border-color: rgba(179, 136, 255, 0.6); }
.tile:active { transform: translateY(1px); }
.tile.playing {
border-color: var(--accent-2);
box-shadow: 0 0 0 1px var(--accent-2), 0 0 22px rgba(110, 255, 200, 0.25);
}
.tile .name {
font-weight: 600;
font-size: 14px;
line-height: 1.3;
margin-bottom: 6px;
word-break: break-word;
}
.tile .meta {
display: flex;
gap: 6px;
flex-wrap: wrap;
font-size: 11px;
color: var(--ink-dim);
letter-spacing: 0.04em;
}
.tile .meta .tag {
background: rgba(255, 255, 255, 0.04);
border: 1px solid var(--panel-border);
border-radius: 999px;
padding: 2px 8px;
text-transform: uppercase;
}
.tile .path {
margin-top: 8px;
font-size: 10.5px;
color: rgba(156, 149, 196, 0.7);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.empty {
margin: 20px 4px 0;
color: var(--ink-dim);
font-style: italic;
}
.future .muted {
margin: 0 0 14px;
color: var(--ink-dim);
font-size: 13px;
max-width: 60ch;
}
.lights {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
gap: 10px;
}
.light {
border: 1px dashed rgba(140, 110, 220, 0.35);
border-radius: 12px;
padding: 16px;
text-align: center;
background: rgba(255, 255, 255, 0.02);
color: var(--ink-dim);
cursor: not-allowed;
position: relative;
user-select: none;
}
.light .icon { font-size: 22px; display: block; margin-bottom: 6px; }
.light .lbl { font-size: 13px; letter-spacing: 0.04em; }
.light .soon {
position: absolute; top: 8px; right: 10px;
font-size: 9.5px;
text-transform: uppercase;
color: var(--warn);
letter-spacing: 0.18em;
}
footer {
position: relative;
z-index: 1;
padding: 14px 28px 26px;
color: var(--ink-dim);
font-size: 12px;
display: flex;
gap: 10px;
align-items: center;
}
footer .sep { opacity: 0.5; }
footer code {
background: rgba(255, 255, 255, 0.05);
border-radius: 6px;
padding: 2px 6px;
font-size: 11.5px;
}
@media (max-width: 760px) {
.topbar { flex-wrap: wrap; }
.status { max-width: 100%; order: 3; }
input[type="search"] { width: 100%; }
.panel-head { flex-direction: column; align-items: flex-start; gap: 10px; }
.panel-controls { margin-left: 0; width: 100%; }
}
.badge { padding: 3px 8px; font-size: 11px; letter-spacing: .18em; text-transform: uppercase; border-radius: 999px; background: rgba(255,180,84,.12); color: var(--warn); border: 1px solid rgba(255,180,84,.35); }
.categories { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 14px; max-height: 112px; overflow: auto; }
.chip { background: rgba(255,255,255,.03); color: var(--ink-dim); border-radius: 999px; padding: 5px 12px; font-size: 12px; }
.chip.active { background: rgba(179,136,255,.15); border-color: var(--accent); color: var(--ink); }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 12px; }
.set-grid { grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); }
.tile { position: relative; display: flex; flex-direction: column; background: linear-gradient(160deg, rgba(255,255,255,.035), rgba(255,255,255,.01)); border: 1px solid var(--panel-border); border-radius: 12px; overflow: hidden; color: var(--ink); transition: transform .08s ease, border-color .15s ease, background .15s ease; }
.tile:hover { border-color: rgba(179,136,255,.6); }
.play-hit { border: 0; border-radius: 0; width: 100%; text-align: left; padding: 14px 14px 10px; background: transparent; min-height: 88px; }
.play-hit:hover { background: radial-gradient(220px 80px at 30% 0%, rgba(179,136,255,.18), transparent 65%); border: 0; }
.tile .name { font-weight: 700; font-size: 14px; line-height: 1.3; margin-bottom: 8px; word-break: break-word; }
.tile .meta { display: flex; gap: 6px; flex-wrap: wrap; font-size: 11px; color: var(--ink-dim); letter-spacing: .04em; }
.tag { background: rgba(255,255,255,.04); border: 1px solid var(--panel-border); border-radius: 999px; padding: 2px 8px; text-transform: uppercase; }
.tile-actions { display: flex; justify-content: flex-end; gap: 8px; padding: 0 10px 10px; }
.mini { padding: 5px 9px; font-size: 11px; border-radius: 8px; }
.mini.ok { color: var(--accent-2); border-color: rgba(110,255,200,.5); }
.empty { margin: 16px 4px 0; color: var(--ink-dim); font-style: italic; }
footer { position: relative; z-index: 1; padding: 14px 28px 26px; color: var(--ink-dim); font-size: 12px; display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
footer .sep { opacity: .5; } footer code { background: rgba(255,255,255,.05); border-radius: 6px; padding: 2px 6px; font-size: 11.5px; }
.drawer-backdrop { position: fixed; inset: 0; background: rgba(0,0,0,.45); z-index: 20; }
.drawer { position: fixed; top: 0; right: 0; width: min(460px, 94vw); height: 100vh; z-index: 21; padding: 20px; background: rgba(13, 11, 26, .96); border-left: 1px solid var(--panel-border); box-shadow: -16px 0 40px rgba(0,0,0,.45); transform: translateX(0); transition: transform .18s ease; overflow-y: auto; }
.drawer[aria-hidden="true"] { transform: translateX(105%); }
.drawer-head { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
.active-list { display: flex; flex-direction: column; gap: 10px; margin-top: 14px; }
.active-row { display: flex; justify-content: space-between; gap: 12px; border: 1px solid var(--panel-border); border-radius: 12px; padding: 12px; background: rgba(255,255,255,.035); }
.active-row strong { display: block; margin-bottom: 3px; }
.active-row span, .active-row em { display: block; color: var(--ink-dim); font-size: 12px; }
.active-row em { color: var(--danger); margin-top: 4px; }
@media (max-width: 860px) { .topbar { flex-wrap: wrap; } .status { max-width: 100%; order: 3; } .hero-panel, .panel-head { flex-direction: column; align-items: flex-start; } .panel-controls, input[type="search"] { width: 100%; } }

View File

@@ -4,11 +4,11 @@ const express = require('express');
const { isSafeRel } = require('./effects');
/**
* Builds the API router. Each route is intentionally narrow: clients can
* list effects, play a known effect path, stop, or pull a known effect
* via the media proxy. No arbitrary HA service / Filestash path passthrough.
* Builds the API router. Routes stay narrow: clients can list indexed effects,
* inject known effects into the backend mixer, control the one allowed Home
* Assistant media-player stream, and fetch/proxy only known Filestash paths.
*/
function createApiRouter({ config, effects, filestash, ha }) {
function createApiRouter({ config, effects, filestash, ha, mixer }) {
const router = express.Router();
const allowedEntity = config.homeAssistant.allowedMediaPlayer;
const publicBaseUrl = config.env.publicBaseUrl;
@@ -21,6 +21,8 @@ function createApiRouter({ config, effects, filestash, ha }) {
cacheAgeSec: effects.cache
? Math.round((Date.now() - effects.cacheLoadedAt) / 1000)
: null,
streamClients: mixer ? mixer.stats().clients : 0,
activeEffects: mixer ? mixer.stats().active.length : 0,
});
});
@@ -29,11 +31,7 @@ function createApiRouter({ config, effects, filestash, ha }) {
const force = req.query.refresh === '1' || req.query.refresh === 'true';
const list = await effects.list({ force });
const categories = [...new Set(list.map((e) => e.category))].sort();
res.json({
count: list.length,
categories,
effects: list,
});
res.json({ count: list.length, categories, effects: list });
} catch (err) {
next(err);
}
@@ -43,78 +41,90 @@ function createApiRouter({ config, effects, filestash, ha }) {
res.json({
mediaPlayer: allowedEntity,
publicBaseUrlConfigured: Boolean(publicBaseUrl),
streamUrl: publicBaseUrl ? `${publicBaseUrl}/stream/${encodeURIComponent(allowedEntity)}` : null,
lightControl: config.lightControl,
});
});
router.post('/api/play', express.json({ limit: '4kb' }), async (req, res, next) => {
router.get('/api/stream/status', (_req, res) => {
res.json({ ok: true, stream: mixer.stats(), entity: allowedEntity });
});
router.post('/api/stream/start', async (_req, res, next) => {
try {
const { path: effectPath } = req.body || {};
if (!isSafeRel(effectPath)) {
return res.status(400).json({ error: 'invalid effect path' });
}
const effect = await effects.findByPath(effectPath);
if (!effect) {
return res.status(404).json({ error: 'effect not found' });
}
if (!publicBaseUrl) {
return res.status(503).json({
error: 'PUBLIC_BASE_URL is not configured; Home Assistant cannot fetch /media',
error: 'PUBLIC_BASE_URL is not configured; Home Assistant cannot fetch /stream',
});
}
const mediaUrl = `${publicBaseUrl}/media?path=${encodeURIComponent(effect.path)}`;
const mediaContentType = effects.contentTypeFor(effect.fileName);
const streamUrl = `${publicBaseUrl}/stream/${encodeURIComponent(allowedEntity)}`;
await ha.playMedia({
entityId: allowedEntity,
mediaContentId: mediaUrl,
mediaContentType,
});
res.json({
ok: true,
played: {
name: effect.name,
path: effect.path,
category: effect.category,
mediaContentType,
mediaUrl,
entity: allowedEntity,
},
mediaContentId: streamUrl,
mediaContentType: 'audio/wav',
});
res.json({ ok: true, entity: allowedEntity, streamUrl });
} catch (err) {
next(err);
}
});
router.post('/api/stop', async (_req, res, next) => {
router.post('/api/stream/stop', async (_req, res, next) => {
try {
const stoppedEffects = mixer.stopAll();
await ha.stop({ entityId: allowedEntity });
res.json({ ok: true, stopped: allowedEntity });
res.json({ ok: true, stopped: allowedEntity, stoppedEffects });
} catch (err) {
next(err);
}
});
router.post('/api/play', express.json({ limit: '8kb' }), async (req, res, next) => {
try {
const { path: effectPath, volume } = req.body || {};
if (!isSafeRel(effectPath)) return res.status(400).json({ error: 'invalid effect path' });
const effect = await effects.findByPath(effectPath);
if (!effect) return res.status(404).json({ error: 'effect not found' });
const injected = await mixer.play(effect, { volume });
res.json({ ok: true, injected, stream: mixer.stats(), entity: allowedEntity });
} catch (err) {
next(err);
}
});
router.post('/api/play/stop', express.json({ limit: '4kb' }), async (req, res) => {
const id = req.body && req.body.id;
if (!id || typeof id !== 'string') return res.status(400).json({ error: 'id is required' });
const stopped = mixer.stopOne(id);
res.status(stopped ? 200 : 404).json({ ok: stopped, id });
});
router.post('/api/stop', async (_req, res, next) => {
try {
const stoppedEffects = mixer.stopAll();
res.json({ ok: true, stoppedEffects, stream: mixer.stats() });
} catch (err) {
next(err);
}
});
router.get('/stream/:entity', (req, res) => {
const entity = decodeURIComponent(req.params.entity || '');
if (entity !== allowedEntity) return res.status(403).json({ error: 'entity not permitted' });
mixer.stream(res);
});
router.get('/media', async (req, res, next) => {
try {
const effectPath = typeof req.query.path === 'string' ? req.query.path : '';
if (!isSafeRel(effectPath)) {
return res.status(400).json({ error: 'invalid path' });
}
if (!isSafeRel(effectPath)) return res.status(400).json({ error: 'invalid path' });
const effect = await effects.findByPath(effectPath);
if (!effect) {
return res.status(404).json({ error: 'effect not found' });
}
if (!effect) return res.status(404).json({ error: 'effect not found' });
const upstream = await filestash.streamFile(effect.path, {
range: req.headers.range,
});
const upstream = await filestash.streamFile(effect.path, { range: req.headers.range });
if (!upstream.ok && upstream.status !== 206) {
return res
.status(upstream.status || 502)
.json({ error: 'upstream fetch failed', status: upstream.status });
return res.status(upstream.status || 502).json({ error: 'upstream fetch failed', status: upstream.status });
}
const passthrough = ['content-length', 'content-range', 'accept-ranges', 'last-modified', 'etag'];
@@ -125,10 +135,7 @@ function createApiRouter({ config, effects, filestash, ha }) {
res.setHeader('Content-Type', effects.contentTypeFor(effect.fileName));
res.status(upstream.status === 206 ? 206 : 200);
if (!upstream.body) {
return res.end();
}
// upstream.body is a Web ReadableStream; pipe it to the Node response.
if (!upstream.body) return res.end();
const reader = upstream.body.getReader();
res.on('close', () => {
try { reader.cancel(); } catch { /* noop */ }
@@ -136,9 +143,7 @@ function createApiRouter({ config, effects, filestash, ha }) {
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (!res.write(Buffer.from(value))) {
await new Promise((resolve) => res.once('drain', resolve));
}
if (!res.write(Buffer.from(value))) await new Promise((resolve) => res.once('drain', resolve));
}
res.end();
} catch (err) {

View File

@@ -7,6 +7,7 @@ const { loadConfig } = require('./config');
const { FilestashClient } = require('./filestash');
const { EffectsService } = require('./effects');
const { HomeAssistantClient } = require('./homeassistant');
const { StreamMixer } = require('./streamMixer');
const { createApiRouter } = require('./routes');
function buildApp(config) {
@@ -48,6 +49,11 @@ function buildApp(config) {
};
}
const mixer = new StreamMixer({
effects,
localMediaBaseUrl: `http://127.0.0.1:${config.env.port}`,
});
const app = express();
app.disable('x-powered-by');
@@ -66,7 +72,7 @@ function buildApp(config) {
});
}
app.use(createApiRouter({ config, effects, filestash, ha }));
app.use(createApiRouter({ config, effects, filestash, ha, mixer }));
const publicDir = path.join(__dirname, '..', 'public');
app.use(express.static(publicDir, { fallthrough: true, index: 'index.html' }));
@@ -82,7 +88,7 @@ function buildApp(config) {
res.status(status).json({ error: err.message || 'internal error' });
});
return { app, effects, filestash };
return { app, effects, filestash, mixer };
}
function main() {

252
src/streamMixer.js Normal file
View File

@@ -0,0 +1,252 @@
'use strict';
const { spawn } = require('node:child_process');
const crypto = require('node:crypto');
const SAMPLE_RATE = 44100;
const CHANNELS = 2;
const BYTES_PER_SAMPLE = 2;
const FRAME_MS = 20;
const FRAME_BYTES = Math.floor(SAMPLE_RATE * CHANNELS * BYTES_PER_SAMPLE * FRAME_MS / 1000);
const MAX_ACTIVE = 24;
const MAX_QUEUE_BYTES = FRAME_BYTES * 250; // 5 seconds of decoded audio buffering per effect.
class StreamMixer {
constructor({ effects, localMediaBaseUrl }) {
if (!effects) throw new Error('StreamMixer requires effects');
if (!localMediaBaseUrl) throw new Error('StreamMixer requires localMediaBaseUrl');
this.effects = effects;
this.localMediaBaseUrl = localMediaBaseUrl.replace(/\/+$/, '');
this.clients = new Set();
this.active = new Map();
this.timer = null;
this.sequence = 0;
}
stream(res) {
res.status(200);
res.setHeader('Content-Type', 'audio/wav');
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
res.setHeader('Connection', 'keep-alive');
res.write(wavHeader());
const client = { res, connectedAt: Date.now(), mutedUntil: Date.now() + 80 };
this.clients.add(client);
this._ensureTimer();
res.on('close', () => {
this.clients.delete(client);
this._maybeStopTimer();
});
}
async play(effect, { volume = 1 } = {}) {
if (!effect || !effect.path) {
const err = new Error('effect is required');
err.status = 400;
throw err;
}
if (this.active.size >= MAX_ACTIVE) {
const oldest = [...this.active.values()].sort((a, b) => a.startedAt - b.startedAt)[0];
if (oldest) this.stopOne(oldest.id);
}
const id = `${Date.now().toString(36)}-${(++this.sequence).toString(36)}-${crypto.randomBytes(3).toString('hex')}`;
const mediaUrl = `${this.localMediaBaseUrl}/media?path=${encodeURIComponent(effect.path)}`;
const item = {
id,
path: effect.path,
name: effect.name,
category: effect.category,
type: effect.type,
volume: clamp(Number(volume) || 1, 0, 2),
startedAt: Date.now(),
queue: [],
queueBytes: 0,
ended: false,
error: null,
proc: null,
};
const args = [
'-hide_banner', '-loglevel', 'error',
'-i', mediaUrl,
'-f', 's16le',
'-acodec', 'pcm_s16le',
'-ac', String(CHANNELS),
'-ar', String(SAMPLE_RATE),
'pipe:1',
];
const proc = spawn('ffmpeg', args, { stdio: ['ignore', 'pipe', 'pipe'] });
item.proc = proc;
proc.stdout.on('data', (chunk) => {
if (!this.active.has(id)) return;
if (item.queueBytes > MAX_QUEUE_BYTES) {
proc.stdout.pause();
setTimeout(() => proc.stdout.resume(), 25);
return;
}
item.queue.push(Buffer.from(chunk));
item.queueBytes += chunk.length;
});
proc.stderr.on('data', (chunk) => {
item.error = String(chunk).slice(0, 500);
});
proc.on('close', (code) => {
item.ended = true;
if (code && code !== 0 && !item.error) item.error = `ffmpeg exited ${code}`;
});
proc.on('error', (err) => {
item.error = err.message;
item.ended = true;
});
this.active.set(id, item);
this._ensureTimer();
return publicItem(item);
}
listActive() {
return [...this.active.values()].map(publicItem);
}
stopOne(id) {
const item = this.active.get(id);
if (!item) return false;
this.active.delete(id);
if (item.proc && !item.proc.killed) item.proc.kill('SIGTERM');
this._maybeStopTimer();
return true;
}
stopAll() {
const count = this.active.size;
for (const item of this.active.values()) {
if (item.proc && !item.proc.killed) item.proc.kill('SIGTERM');
}
this.active.clear();
this._maybeStopTimer();
return count;
}
stats() {
return {
sampleRate: SAMPLE_RATE,
channels: CHANNELS,
clients: this.clients.size,
active: this.listActive(),
};
}
_ensureTimer() {
if (this.timer) return;
this.timer = setInterval(() => this._tick(), FRAME_MS);
this.timer.unref?.();
}
_maybeStopTimer() {
if (this.clients.size || this.active.size) return;
if (this.timer) clearInterval(this.timer);
this.timer = null;
}
_tick() {
const output = Buffer.alloc(FRAME_BYTES);
const mix = new Int32Array(FRAME_BYTES / BYTES_PER_SAMPLE);
const now = Date.now();
for (const item of [...this.active.values()]) {
const frame = consumeFrame(item, FRAME_BYTES);
if (frame) {
for (let i = 0; i < mix.length; i += 1) {
mix[i] += Math.round(frame.readInt16LE(i * 2) * item.volume);
}
}
if (item.ended && item.queueBytes === 0) {
this.active.delete(item.id);
}
}
for (let i = 0; i < mix.length; i += 1) {
output.writeInt16LE(clamp(mix[i], -32768, 32767), i * 2);
}
for (const client of [...this.clients]) {
if (now < client.mutedUntil) continue;
if (client.res.destroyed || client.res.writableEnded) {
this.clients.delete(client);
continue;
}
try {
client.res.write(output);
} catch {
this.clients.delete(client);
}
}
this._maybeStopTimer();
}
}
function consumeFrame(item, size) {
if (!item.queueBytes) return null;
const out = Buffer.alloc(size);
let offset = 0;
while (offset < size && item.queue.length) {
const chunk = item.queue[0];
const take = Math.min(size - offset, chunk.length);
chunk.copy(out, offset, 0, take);
offset += take;
item.queueBytes -= take;
if (take === chunk.length) {
item.queue.shift();
} else {
item.queue[0] = chunk.subarray(take);
}
}
return out;
}
function wavHeader() {
const h = Buffer.alloc(44);
h.write('RIFF', 0);
h.writeUInt32LE(0xffffffff, 4);
h.write('WAVE', 8);
h.write('fmt ', 12);
h.writeUInt32LE(16, 16);
h.writeUInt16LE(1, 20);
h.writeUInt16LE(CHANNELS, 22);
h.writeUInt32LE(SAMPLE_RATE, 24);
h.writeUInt32LE(SAMPLE_RATE * CHANNELS * BYTES_PER_SAMPLE, 28);
h.writeUInt16LE(CHANNELS * BYTES_PER_SAMPLE, 32);
h.writeUInt16LE(16, 34);
h.write('data', 36);
h.writeUInt32LE(0xffffffff, 40);
return h;
}
function publicItem(item) {
return {
id: item.id,
path: item.path,
name: item.name,
category: item.category,
type: item.type,
volume: item.volume,
startedAt: item.startedAt,
ageMs: Date.now() - item.startedAt,
error: item.error,
};
}
function clamp(n, min, max) {
return Math.max(min, Math.min(max, n));
}
module.exports = { StreamMixer };