Files
party-player/server/index.js
SiandClaude Opus 5 554b946235 Slow every animation down for a low-res screen
Every speed in config.js is in pixels per second, so the same numbers cross a
small screen in less time than a big one: on 1280x800 the frame covers the
width in two thirds of the time it takes on 1920x1080, and the player reads as
hurried.

One factor now sits behind every animation clock — tickSeconds() for the
frame loops, `speed` for the corners timer, and a --motion-stretch custom
property for the two CSS fades — so the Speed switch on the queue page slows
the drift, the glides, the pong rally, the drag beats, the wash lap, the
screenshot intervals and the fades together. It is read per frame rather than
baked into the constants, so flipping the switch lands on the next frame: no
animation restarts, and one part-way through a beat keeps its place.

The trail's stills now age on animation time rather than wall-clock time, so a
still fades at the rate the frame that dropped it is moving. The audio
crossfade is deliberately left out, being tied to the track that is ending.

The flag is saved with the queue, unlike `paused`: it describes the screen the
player is on, which a restart does not change.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011vCaS2whbFjExShoPNnS3A
2026-08-14 12:53:33 +02:00

209 lines
6.1 KiB
JavaScript

// Express serves the two frontends; a single WebSocket keeps them in sync.
import { createServer } from 'node:http';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import express from 'express';
import { WebSocketServer } from 'ws';
import * as config from '../config.js';
import { PORT } from '../config.js';
import { parseVideoId, fetchTitle } from './youtube.js';
import * as screen from './screen.js';
import * as store from './state.js';
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
store.load();
const app = express();
// Declared before the static middleware, which would otherwise redirect
// /queue to /queue/ on its way to the directory index.
app.get('/', (_req, res) => res.sendFile(join(ROOT, 'public/player/index.html')));
app.get('/queue', (_req, res) => res.sendFile(join(ROOT, 'public/queue/index.html')));
app.use('/assets', express.static(join(ROOT, 'assets'), { maxAge: '1h' }));
app.use(express.static(join(ROOT, 'public')));
// Client-side mirror of the shared config, so the constants live in one place.
// Generated from the module's exports rather than listed by hand: a constant
// added to config.js and imported by the frontend used to break the whole
// module graph — and with it the player — until this list was updated too.
// PORT is server-only; everything else travels.
const CLIENT_CONFIG = Object.entries(config).filter(([name]) => name !== 'PORT');
app.get('/config.js', (_req, res) => {
res
.type('application/javascript')
.send(
CLIENT_CONFIG.map(([name, value]) => `export const ${name} = ${JSON.stringify(value)};\n`).join(''),
);
});
// Screenshots of the player's own frame (see server/screen.js). The player
// points an <img> straight at this, so the response has to be the finished
// crop — there is no canvas step on the other end.
app.get('/shot', async (req, res) => {
const rect = {
x: Number(req.query.x),
y: Number(req.query.y),
width: Number(req.query.w),
height: Number(req.query.h),
// The viewport the page measured its rect against. The crop is in CSS
// pixels, and this is what lets the server work out what one of those is
// worth on screen — see server/screen.js.
viewportWidth: Number(req.query.vw),
viewportHeight: Number(req.query.vh),
};
if (Object.values(rect).some((value) => !Number.isFinite(value))) {
res.sendStatus(400);
return;
}
// The page's own document.title, which is how its window is picked out.
rect.title = String(req.query.title ?? '');
if (!rect.title) {
res.sendStatus(400);
return;
}
// 501, not 404: the player probes this route to decide whether to fall back
// to getDisplayMedia, and needs to tell "wrong machine" from "no route".
if (!(await screen.available())) {
res.sendStatus(501);
return;
}
const jpeg = await screen.capture(rect);
if (!jpeg) {
res.sendStatus(422);
return;
}
// Every request carries a fresh nonce, so a cached copy would only ever be a
// stale photograph of a moment that has passed.
res.type('image/jpeg').set('Cache-Control', 'no-store').send(jpeg);
});
const server = createServer(app);
const wss = new WebSocketServer({ server });
function broadcast(message) {
const payload = JSON.stringify(message);
for (const client of wss.clients) {
if (client.readyState === client.OPEN) client.send(payload);
}
}
function broadcastState() {
broadcast({ type: 'state', state: store.getState() });
}
/** Persist and push in one go — every structural change ends with this. */
function commit() {
store.save();
broadcastState();
}
const handlers = {
async add(_ws, msg) {
const videoId = parseVideoId(msg.url);
if (!videoId) throw new Error('Not a YouTube video URL');
const title = await fetchTitle(videoId);
store.addItem({ videoId, title });
commit();
},
remove(_ws, msg) {
if (store.removeItem(msg.id)) commit();
},
reorder(_ws, msg) {
if (!Array.isArray(msg.ids)) return;
store.reorder(msg.ids);
commit();
},
jump(_ws, msg) {
if (store.indexOf(msg.id) === -1) return;
store.getState().currentId = msg.id;
commit();
},
duration(_ws, msg) {
if (store.setDuration(msg.id, msg.seconds)) commit();
},
// The player finished its crossfade and wants the pointer moved along.
trackEnded(_ws, msg) {
const state = store.getState();
// Ignore stale reports from a track we already moved past.
if (msg.id !== state.currentId) return;
const next = store.nextItem(msg.id);
state.currentId = next ? next.id : null;
commit();
},
// Broadcast without saving: `paused` is not part of the persisted state.
setPaused(_ws, msg) {
if (typeof msg.paused !== 'boolean') return;
if (store.getState().paused === msg.paused) return;
store.getState().paused = msg.paused;
broadcastState();
},
setBackground(_ws, msg) {
if (!store.isBackground(msg.key)) return;
store.getState().background = msg.key;
commit();
},
setAnimation(_ws, msg) {
if (!store.isAnimation(msg.key)) return;
store.getState().animation = msg.key;
commit();
},
setLowRes(_ws, msg) {
if (typeof msg.key !== 'boolean') return;
if (store.getState().lowRes === msg.key) return;
store.getState().lowRes = msg.key;
commit();
},
// Relayed straight through: this arrives once a second and must never
// touch the disk.
progress(_ws, msg) {
broadcast({ type: 'progress', id: msg.id, currentTime: msg.currentTime });
},
};
wss.on('connection', (ws) => {
ws.send(JSON.stringify({ type: 'state', state: store.getState() }));
ws.on('message', async (raw) => {
let msg;
try {
msg = JSON.parse(raw);
} catch {
return;
}
const handler = handlers[msg.type];
if (!handler) return;
try {
await handler(ws, msg);
} catch (err) {
ws.send(JSON.stringify({ type: 'error', message: err.message, forType: msg.type }));
}
});
});
server.listen(PORT, () => {
console.log(`\n Player : http://localhost:${PORT}/`);
console.log(` Queue : http://localhost:${PORT}/queue\n`);
});