|
- 'use strict';
-
- // ── DOM refs ──────────────────────────────────────────────────────────────────
- const $ = id => document.getElementById(id);
-
- const statusDot = $('winamp-status');
- const stateLabel = $('state-label');
- const trackTitle = $('track-title');
- const playlistPos = $('playlist-pos');
- const progressFill = $('progress-fill');
- const timeCurrent = $('time-current');
- const timeLength = $('time-length');
- const volumeFill = $('volume-fill');
- const volumePct = $('volume-pct');
- const btnMute = $('btn-mute');
- const btnPlay = $('btn-play');
- const killistPanel = $('killist-panel');
- const killistItems = $('killist-items');
- const playlistOverlay = $('playlist-overlay');
- const playlistList = $('playlist-list');
- const canvas = $('viz');
- const ctx2d = canvas.getContext('2d');
-
- // ── State ─────────────────────────────────────────────────────────────────────
- let currentVolume = 50;
- let currentPlaylistPos = 0; // 1-based, updated from status
- let ws = null;
- let reconnectTimer = null;
-
- // Viz state
- const NUM_BARS = 64;
- const peaks = new Float32Array(NUM_BARS);
- let lastBars = new Float32Array(NUM_BARS);
- let rafId = null;
- let lastVizAt = 0; // timestamp of last received viz frame
- let winampPlaying = false;
-
- // Canvas display mode — cycles on click: viz → actual → remaining → viz
- const VIZ_MODES = ['viz', 'actual', 'remaining'];
- let vizMode = 'viz';
- let currentPosition = 0;
- let currentLength = 0;
-
- // ── WebSocket ─────────────────────────────────────────────────────────────────
- function connect() {
- const proto = location.protocol === 'https:' ? 'wss' : 'ws';
- ws = new WebSocket(`${proto}://${location.host}/ws`);
-
- ws.addEventListener('open', () => {
- statusDot.className = 'ok';
- stateLabel.textContent = 'Verbunden';
- clearTimeout(reconnectTimer);
- });
-
- ws.addEventListener('close', () => {
- statusDot.className = 'err';
- stateLabel.textContent = 'Verbindung unterbrochen…';
- ws = null;
- reconnectTimer = setTimeout(connect, 3000);
- });
-
- ws.addEventListener('error', () => ws.close());
-
- ws.addEventListener('message', e => {
- let msg;
- try { msg = JSON.parse(e.data); } catch { return; }
-
- if (msg.type === 'status') applyStatus(msg);
- if (msg.type === 'viz') applyViz(msg.bars);
- });
- }
-
- function send(obj) {
- if (ws && ws.readyState === WebSocket.OPEN) {
- ws.send(JSON.stringify(obj));
- }
- }
-
- // ── Status handler ────────────────────────────────────────────────────────────
- function applyStatus(st) {
- if (!st.running) {
- statusDot.className = 'err';
- stateLabel.textContent = 'Winamp nicht gestartet';
- trackTitle.textContent = '–';
- playlistPos.textContent = '';
- return;
- }
-
- statusDot.className = 'ok';
- const stateMap = { playing: '▶ Spielt', paused: '⏸ Pause', stopped: '⏹ Stop' };
- stateLabel.textContent = stateMap[st.state] ?? st.state;
-
- trackTitle.textContent = st.title || '–';
- playlistPos.textContent = st.playlist_length
- ? `${st.playlist_pos} / ${st.playlist_length}` : '';
-
- if (st.playlist_pos !== currentPlaylistPos) {
- currentPlaylistPos = st.playlist_pos;
- updatePlaylistHighlight();
- }
-
- if (st.length > 0) {
- currentPosition = st.position;
- currentLength = st.length;
- progressFill.style.width = (st.position / st.length * 100).toFixed(1) + '%';
- timeCurrent.textContent = fmtTime(st.position);
- timeLength.textContent = '-' + fmtTime(st.length - st.position);
- } else {
- progressFill.style.width = '0%';
- timeCurrent.textContent = '0:00';
- timeLength.textContent = '-0:00';
- }
-
- btnPlay.textContent = st.state === 'playing' ? '⏸' : '▶';
- winampPlaying = st.state === 'playing';
-
- if (typeof st.volume === 'number') {
- currentVolume = st.volume;
- updateVolumeFill(st.muted);
- updateMuteBtn(st.muted);
- }
- }
-
- // ── Controls ──────────────────────────────────────────────────────────────────
- btnPlay.addEventListener('click', () => {
- // Optimistic toggle — server will push the real state back immediately.
- const playing = btnPlay.textContent === '⏸';
- send({ cmd: playing ? 'pause' : 'play' });
- });
-
- $('btn-stop').addEventListener('click', () => send({ cmd: 'stop' }));
- $('btn-next').addEventListener('click', () => send({ cmd: 'next' }));
- $('btn-prev').addEventListener('click', () => send({ cmd: 'prev' }));
-
- document.querySelectorAll('.btn-seek').forEach(btn => {
- btn.addEventListener('click', () =>
- send({ cmd: 'seek', delta: parseInt(btn.dataset.delta, 10) }));
- });
-
- $('progress-bar').addEventListener('click', async e => {
- // Derive total from current + remaining (timeLength shows "-mm:ss").
- const current = parseTime(timeCurrent.textContent);
- const remaining = parseTime(timeLength.textContent.replace('-', ''));
- const total = current + remaining;
- if (!total) return;
- const rect = e.currentTarget.getBoundingClientRect();
- const target = Math.round((e.clientX - rect.left) / rect.width * total);
- send({ cmd: 'seek', delta: target - current });
- });
-
- // ── Volume ────────────────────────────────────────────────────────────────────
- $('btn-vol-up').addEventListener('click', () => {
- currentVolume = Math.min(100, currentVolume + 5);
- send({ cmd: 'volume', level: currentVolume });
- updateVolumeFill();
- });
- $('btn-vol-down').addEventListener('click', () => {
- currentVolume = Math.max(0, currentVolume - 5);
- send({ cmd: 'volume', level: currentVolume });
- updateVolumeFill();
- });
- $('volume-bar').addEventListener('click', e => {
- const rect = e.currentTarget.getBoundingClientRect();
- currentVolume = Math.round((e.clientX - rect.left) / rect.width * 100);
- send({ cmd: 'volume', level: currentVolume });
- updateVolumeFill();
- });
- btnMute.addEventListener('click', () => {
- const nowMuted = btnMute.classList.contains('muted');
- send({ cmd: 'mute', muted: !nowMuted });
- updateMuteBtn(!nowMuted);
- updateVolumeFill(!nowMuted);
- });
-
- function updateVolumeFill(muted = btnMute.classList.contains('muted')) {
- volumeFill.style.width = currentVolume + '%';
- volumePct.textContent = currentVolume + ' %';
- volumeFill.classList.toggle('muted', muted);
- }
- function updateMuteBtn(muted) {
- btnMute.textContent = muted ? '🔇' : '🔊';
- btnMute.classList.toggle('muted', muted);
- }
-
- // ── KillList ──────────────────────────────────────────────────────────────────
- $('btn-kill').addEventListener('click', () => {
- send({ cmd: 'killist_add' });
- showToast('🚫 Track zur Skip-Liste hinzugefügt');
- });
-
- $('btn-show-killist').addEventListener('click', async () => {
- const list = await fetch('/api/killist').then(r => r.json()).catch(() => []);
- killistItems.innerHTML = '';
- (list || []).forEach(title => {
- const li = document.createElement('li');
- li.innerHTML = `<span>${escHtml(title)}</span>`;
- const btn = document.createElement('button');
- btn.textContent = '✕';
- btn.onclick = () => {
- send({ cmd: 'killist_remove', title });
- li.remove();
- };
- li.appendChild(btn);
- killistItems.appendChild(li);
- });
- killistPanel.classList.remove('hidden');
- });
-
- $('btn-close-killist').addEventListener('click', () =>
- killistPanel.classList.add('hidden'));
-
- // ── Visualisation (Canvas) ────────────────────────────────────────────────────
- canvas.addEventListener('click', () => {
- vizMode = VIZ_MODES[(VIZ_MODES.indexOf(vizMode) + 1) % VIZ_MODES.length];
- });
-
- function applyViz(bars) {
- if (!bars || bars.length === 0) return;
- lastBars = new Float32Array(bars);
- lastVizAt = performance.now();
- }
-
- function renderFrame(ts = 0) {
- rafId = requestAnimationFrame(renderFrame);
-
- // Resize canvas to CSS size (handles window resize / DPR).
- // Setting canvas.width resets the transform, so we re-apply scale.
- const dpr = window.devicePixelRatio || 1;
- const cssW = canvas.clientWidth;
- const cssH = canvas.clientHeight;
- if (canvas.width !== Math.round(cssW * dpr) || canvas.height !== Math.round(cssH * dpr)) {
- canvas.width = Math.round(cssW * dpr);
- canvas.height = Math.round(cssH * dpr);
- ctx2d.scale(dpr, dpr);
- }
-
- const w = cssW;
- const h = cssH;
- if (w === 0 || h === 0) return;
-
- // Background
- ctx2d.fillStyle = '#000';
- ctx2d.fillRect(0, 0, w, h);
-
- // ── Time display modes ──────────────────────────────────────────────────────
- if (vizMode === 'actual' || vizMode === 'remaining') {
- const isActual = vizMode === 'actual';
- const secs = isActual ? currentPosition : Math.max(0, currentLength - currentPosition);
- const prefix = isActual ? '' : '-';
- const timeStr = prefix + fmtTimeLong(secs);
- const label = isActual ? 'ELAPSED' : 'REMAINING';
-
- ctx2d.textAlign = 'center';
- ctx2d.textBaseline = 'middle';
-
- // Large time
- ctx2d.font = `bold ${Math.round(h * 0.52)}px monospace`;
- ctx2d.fillStyle = isActual ? '#e0e0e0' : '#e94560';
- ctx2d.fillText(timeStr, w / 2, h * 0.48);
-
- // Small label below
- ctx2d.font = `${Math.round(h * 0.18)}px monospace`;
- ctx2d.fillStyle = '#444';
- ctx2d.fillText(label, w / 2, h * 0.82);
- return;
- }
-
- // ── Spectrum mode ───────────────────────────────────────────────────────────
- // Check if real viz data is fresh (< 1.5 s old) and Winamp is playing.
- const hasSignal = winampPlaying && (performance.now() - lastVizAt) < 1500;
-
- // Classic fixed vertical gradient: green at bottom → yellow → red at top.
- // Defined in canvas coords so every bar shows the same colour at the same
- // height — no per-frame hue calculation, no flicker.
- const grad = ctx2d.createLinearGradient(0, h, 0, 0);
- if (hasSignal) {
- grad.addColorStop(0, '#00aa00');
- grad.addColorStop(0.6, '#aaaa00');
- grad.addColorStop(1, '#cc0000');
- } else {
- // Idle: same palette but much dimmer
- grad.addColorStop(0, '#003300');
- grad.addColorStop(0.6, '#333300');
- grad.addColorStop(1, '#330000');
- }
-
- const n = NUM_BARS;
- const gap = 1;
- const barW = Math.max(1, (w - gap * (n - 1)) / n);
-
- for (let i = 0; i < n; i++) {
- let val;
-
- if (hasSignal) {
- val = lastBars[i] || 0;
- if (val > peaks[i]) peaks[i] = val;
- else peaks[i] = Math.max(0, peaks[i] - 0.008); // gentle decay
- } else {
- // Idle: slow sine breathing
- const phase = (ts / 1800) + (i / n) * Math.PI * 2;
- const breath = (Math.sin(ts / 2000) * 0.5 + 0.5) * 0.08;
- val = Math.max(0, Math.sin(phase) * breath);
- peaks[i] = Math.max(0, peaks[i] - 0.02);
- }
-
- const x = Math.round(i * (barW + gap));
- const barH = val * h;
-
- if (barH > 0.5) {
- ctx2d.fillStyle = grad;
- ctx2d.fillRect(x, h - barH, barW, barH);
- }
-
- // Peak dot — 1 px taller slice of the same gradient, slightly brighter
- if (peaks[i] > 0.02) {
- const py = Math.round(h - peaks[i] * h) - 1;
- ctx2d.fillStyle = hasSignal ? 'rgba(255,255,255,0.6)' : 'rgba(255,255,255,0.15)';
- ctx2d.fillRect(x, py, barW, 2);
- }
- }
-
- // "No signal" label when disconnected or stopped
- if (!ws || ws.readyState !== WebSocket.OPEN) {
- drawLabel(ctx2d, w, h, '● NO SIGNAL', '#333');
- } else if (!winampPlaying) {
- drawLabel(ctx2d, w, h, '▶ PLAY', '#1a3a1a');
- }
- }
-
- function drawLabel(ctx, w, h, text, color) {
- ctx.font = `bold ${Math.round(h * 0.22)}px monospace`;
- ctx.textAlign = 'center';
- ctx.textBaseline = 'middle';
- ctx.fillStyle = color;
- ctx.fillText(text, w / 2, h / 2);
- }
-
- // ── Helpers ───────────────────────────────────────────────────────────────────
- function fmtTime(secs) {
- const m = Math.floor(secs / 60);
- const s = String(Math.floor(secs % 60)).padStart(2, '0');
- return `${m}:${s}`;
- }
-
- // Like fmtTime but always zero-pads to hh:mm:ss for the canvas display.
- function fmtTimeLong(secs) {
- secs = Math.floor(secs);
- const h = Math.floor(secs / 3600);
- const m = Math.floor((secs % 3600) / 60);
- const s = secs % 60;
- return `${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
- }
-
- function parseTime(str) {
- const [m, s] = (str || '0:00').split(':').map(Number);
- return m * 60 + (s || 0);
- }
-
- function escHtml(s) {
- return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
- }
-
- let toastTimer;
- function showToast(msg) {
- let el = $('toast');
- if (!el) {
- el = document.createElement('div');
- el.id = 'toast';
- el.style.cssText = [
- 'position:fixed', 'bottom:24px', 'left:50%', 'transform:translateX(-50%)',
- 'background:#333', 'color:#fff', 'padding:10px 20px', 'border-radius:8px',
- 'font-size:14px', 'z-index:999', 'opacity:0', 'transition:opacity .2s',
- 'pointer-events:none',
- ].join(';');
- document.body.appendChild(el);
- }
- el.textContent = msg;
- el.style.opacity = '1';
- clearTimeout(toastTimer);
- toastTimer = setTimeout(() => { el.style.opacity = '0'; }, 2500);
- }
-
- // ── Playlist ──────────────────────────────────────────────────────────────────
- $('btn-show-playlist').addEventListener('click', openPlaylist);
- $('btn-close-playlist').addEventListener('click', () => {
- playlistOverlay.classList.add('hidden');
- });
-
- async function openPlaylist() {
- playlistOverlay.classList.remove('hidden');
- playlistList.innerHTML = '<li id="playlist-loading">Lade…</li>';
-
- let tracks;
- try {
- tracks = await fetch('/api/playlist').then(r => r.json());
- } catch {
- playlistList.innerHTML = '<li id="playlist-loading">Fehler beim Laden</li>';
- return;
- }
-
- if (!tracks || tracks.length === 0) {
- playlistList.innerHTML = '<li id="playlist-loading">Playlist leer</li>';
- return;
- }
-
- const frag = document.createDocumentFragment();
- tracks.forEach(t => {
- const li = document.createElement('li');
- li.dataset.index = t.index - 1; // store 0-based for jump
- if (t.index === currentPlaylistPos) li.classList.add('current');
-
- const idx = document.createElement('span');
- idx.className = 'pl-idx';
- idx.textContent = t.index;
-
- const title = document.createElement('span');
- title.className = 'pl-title';
- title.textContent = t.title || '–';
-
- li.appendChild(idx);
- li.appendChild(title);
- li.addEventListener('click', () => {
- send({ cmd: 'jump', index: parseInt(li.dataset.index, 10) });
- playlistOverlay.classList.add('hidden');
- });
- frag.appendChild(li);
- });
-
- playlistList.innerHTML = '';
- playlistList.appendChild(frag);
- scrollToCurrentTrack();
- }
-
- function updatePlaylistHighlight() {
- if (playlistOverlay.classList.contains('hidden')) return;
- playlistList.querySelectorAll('li').forEach(li => {
- const isCurrent = parseInt(li.dataset.index, 10) === currentPlaylistPos - 1;
- li.classList.toggle('current', isCurrent);
- });
- scrollToCurrentTrack();
- }
-
- function scrollToCurrentTrack() {
- const current = playlistList.querySelector('li.current');
- if (current) current.scrollIntoView({ block: 'center', behavior: 'smooth' });
- }
-
- // ── Boot ──────────────────────────────────────────────────────────────────────
- connect();
- renderFrame();
|