Web-based Winamp controller for CarPC � Go backend, mobile-first UI
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

396 line
14KB

  1. 'use strict';
  2. // ── DOM refs ──────────────────────────────────────────────────────────────────
  3. const $ = id => document.getElementById(id);
  4. const statusDot = $('winamp-status');
  5. const stateLabel = $('state-label');
  6. const trackTitle = $('track-title');
  7. const playlistPos = $('playlist-pos');
  8. const progressFill = $('progress-fill');
  9. const timeCurrent = $('time-current');
  10. const timeLength = $('time-length');
  11. const volumeFill = $('volume-fill');
  12. const volumePct = $('volume-pct');
  13. const btnMute = $('btn-mute');
  14. const btnPlay = $('btn-play');
  15. const killistPanel = $('killist-panel');
  16. const killistItems = $('killist-items');
  17. const playlistOverlay = $('playlist-overlay');
  18. const playlistList = $('playlist-list');
  19. const canvas = $('viz');
  20. const ctx2d = canvas.getContext('2d');
  21. // ── State ─────────────────────────────────────────────────────────────────────
  22. let currentVolume = 50;
  23. let currentPlaylistPos = 0; // 1-based, updated from status
  24. let ws = null;
  25. let reconnectTimer = null;
  26. // Viz state
  27. const NUM_BARS = 64;
  28. const peaks = new Float32Array(NUM_BARS);
  29. let lastBars = new Float32Array(NUM_BARS);
  30. let rafId = null;
  31. let lastVizAt = 0; // timestamp of last received viz frame
  32. let winampPlaying = false;
  33. // ── WebSocket ─────────────────────────────────────────────────────────────────
  34. function connect() {
  35. const proto = location.protocol === 'https:' ? 'wss' : 'ws';
  36. ws = new WebSocket(`${proto}://${location.host}/ws`);
  37. ws.addEventListener('open', () => {
  38. statusDot.className = 'ok';
  39. stateLabel.textContent = 'Verbunden';
  40. clearTimeout(reconnectTimer);
  41. });
  42. ws.addEventListener('close', () => {
  43. statusDot.className = 'err';
  44. stateLabel.textContent = 'Verbindung unterbrochen…';
  45. ws = null;
  46. reconnectTimer = setTimeout(connect, 3000);
  47. });
  48. ws.addEventListener('error', () => ws.close());
  49. ws.addEventListener('message', e => {
  50. let msg;
  51. try { msg = JSON.parse(e.data); } catch { return; }
  52. if (msg.type === 'status') applyStatus(msg);
  53. if (msg.type === 'viz') applyViz(msg.bars);
  54. });
  55. }
  56. function send(obj) {
  57. if (ws && ws.readyState === WebSocket.OPEN) {
  58. ws.send(JSON.stringify(obj));
  59. }
  60. }
  61. // ── Status handler ────────────────────────────────────────────────────────────
  62. function applyStatus(st) {
  63. if (!st.running) {
  64. statusDot.className = 'err';
  65. stateLabel.textContent = 'Winamp nicht gestartet';
  66. trackTitle.textContent = '–';
  67. playlistPos.textContent = '';
  68. return;
  69. }
  70. statusDot.className = 'ok';
  71. const stateMap = { playing: '▶ Spielt', paused: '⏸ Pause', stopped: '⏹ Stop' };
  72. stateLabel.textContent = stateMap[st.state] ?? st.state;
  73. trackTitle.textContent = st.title || '–';
  74. playlistPos.textContent = st.playlist_length
  75. ? `${st.playlist_pos} / ${st.playlist_length}` : '';
  76. if (st.playlist_pos !== currentPlaylistPos) {
  77. currentPlaylistPos = st.playlist_pos;
  78. updatePlaylistHighlight();
  79. }
  80. if (st.length > 0) {
  81. progressFill.style.width = (st.position / st.length * 100).toFixed(1) + '%';
  82. timeCurrent.textContent = fmtTime(st.position);
  83. timeLength.textContent = '-' + fmtTime(st.length - st.position);
  84. } else {
  85. progressFill.style.width = '0%';
  86. timeCurrent.textContent = '0:00';
  87. timeLength.textContent = '-0:00';
  88. }
  89. btnPlay.textContent = st.state === 'playing' ? '⏸' : '▶';
  90. winampPlaying = st.state === 'playing';
  91. if (typeof st.volume === 'number') {
  92. currentVolume = st.volume;
  93. updateVolumeFill(st.muted);
  94. updateMuteBtn(st.muted);
  95. }
  96. }
  97. // ── Controls ──────────────────────────────────────────────────────────────────
  98. btnPlay.addEventListener('click', () => {
  99. // Optimistic toggle — server will push the real state back immediately.
  100. const playing = btnPlay.textContent === '⏸';
  101. send({ cmd: playing ? 'pause' : 'play' });
  102. });
  103. $('btn-stop').addEventListener('click', () => send({ cmd: 'stop' }));
  104. $('btn-next').addEventListener('click', () => send({ cmd: 'next' }));
  105. $('btn-prev').addEventListener('click', () => send({ cmd: 'prev' }));
  106. document.querySelectorAll('.btn-seek').forEach(btn => {
  107. btn.addEventListener('click', () =>
  108. send({ cmd: 'seek', delta: parseInt(btn.dataset.delta, 10) }));
  109. });
  110. $('progress-bar').addEventListener('click', async e => {
  111. // Derive total from current + remaining (timeLength shows "-mm:ss").
  112. const current = parseTime(timeCurrent.textContent);
  113. const remaining = parseTime(timeLength.textContent.replace('-', ''));
  114. const total = current + remaining;
  115. if (!total) return;
  116. const rect = e.currentTarget.getBoundingClientRect();
  117. const target = Math.round((e.clientX - rect.left) / rect.width * total);
  118. send({ cmd: 'seek', delta: target - current });
  119. });
  120. // ── Volume ────────────────────────────────────────────────────────────────────
  121. $('btn-vol-up').addEventListener('click', () => {
  122. currentVolume = Math.min(100, currentVolume + 5);
  123. send({ cmd: 'volume', level: currentVolume });
  124. updateVolumeFill();
  125. });
  126. $('btn-vol-down').addEventListener('click', () => {
  127. currentVolume = Math.max(0, currentVolume - 5);
  128. send({ cmd: 'volume', level: currentVolume });
  129. updateVolumeFill();
  130. });
  131. $('volume-bar').addEventListener('click', e => {
  132. const rect = e.currentTarget.getBoundingClientRect();
  133. currentVolume = Math.round((e.clientX - rect.left) / rect.width * 100);
  134. send({ cmd: 'volume', level: currentVolume });
  135. updateVolumeFill();
  136. });
  137. btnMute.addEventListener('click', () => {
  138. const nowMuted = btnMute.classList.contains('muted');
  139. send({ cmd: 'mute', muted: !nowMuted });
  140. updateMuteBtn(!nowMuted);
  141. updateVolumeFill(!nowMuted);
  142. });
  143. function updateVolumeFill(muted = btnMute.classList.contains('muted')) {
  144. volumeFill.style.width = currentVolume + '%';
  145. volumePct.textContent = currentVolume + ' %';
  146. volumeFill.classList.toggle('muted', muted);
  147. }
  148. function updateMuteBtn(muted) {
  149. btnMute.textContent = muted ? '🔇' : '🔊';
  150. btnMute.classList.toggle('muted', muted);
  151. }
  152. // ── KillList ──────────────────────────────────────────────────────────────────
  153. $('btn-kill').addEventListener('click', () => {
  154. send({ cmd: 'killist_add' });
  155. showToast('🚫 Track zur Skip-Liste hinzugefügt');
  156. });
  157. $('btn-show-killist').addEventListener('click', async () => {
  158. const list = await fetch('/api/killist').then(r => r.json()).catch(() => []);
  159. killistItems.innerHTML = '';
  160. (list || []).forEach(title => {
  161. const li = document.createElement('li');
  162. li.innerHTML = `<span>${escHtml(title)}</span>`;
  163. const btn = document.createElement('button');
  164. btn.textContent = '✕';
  165. btn.onclick = () => {
  166. send({ cmd: 'killist_remove', title });
  167. li.remove();
  168. };
  169. li.appendChild(btn);
  170. killistItems.appendChild(li);
  171. });
  172. killistPanel.classList.remove('hidden');
  173. });
  174. $('btn-close-killist').addEventListener('click', () =>
  175. killistPanel.classList.add('hidden'));
  176. // ── Visualisation (Canvas) ────────────────────────────────────────────────────
  177. function applyViz(bars) {
  178. if (!bars || bars.length === 0) return;
  179. lastBars = new Float32Array(bars);
  180. lastVizAt = performance.now();
  181. }
  182. function renderFrame(ts = 0) {
  183. rafId = requestAnimationFrame(renderFrame);
  184. // Resize canvas to CSS size (handles window resize / DPR).
  185. // Setting canvas.width resets the transform, so we re-apply scale.
  186. const dpr = window.devicePixelRatio || 1;
  187. const cssW = canvas.clientWidth;
  188. const cssH = canvas.clientHeight;
  189. if (canvas.width !== Math.round(cssW * dpr) || canvas.height !== Math.round(cssH * dpr)) {
  190. canvas.width = Math.round(cssW * dpr);
  191. canvas.height = Math.round(cssH * dpr);
  192. ctx2d.scale(dpr, dpr);
  193. }
  194. const w = cssW;
  195. const h = cssH;
  196. if (w === 0 || h === 0) return;
  197. // Check if real viz data is fresh (< 1.5 s old) and Winamp is playing.
  198. const hasSignal = winampPlaying && (performance.now() - lastVizAt) < 1500;
  199. // Background
  200. ctx2d.fillStyle = '#000';
  201. ctx2d.fillRect(0, 0, w, h);
  202. const n = NUM_BARS;
  203. const gap = 1;
  204. const barW = Math.max(1, (w - gap * (n - 1)) / n);
  205. for (let i = 0; i < n; i++) {
  206. let val;
  207. if (hasSignal) {
  208. // Real spectrum data
  209. val = lastBars[i] || 0;
  210. if (val > peaks[i]) peaks[i] = val;
  211. else peaks[i] = Math.max(0, peaks[i] - 0.012);
  212. } else {
  213. // Idle animation: slow sine "breathing" across the bars.
  214. // Amplitude fades out when paused/stopped.
  215. const phase = (ts / 1800) + (i / n) * Math.PI * 2;
  216. const breath = (Math.sin(ts / 2000) * 0.5 + 0.5) * 0.08; // 0..0.08
  217. val = Math.max(0, Math.sin(phase) * breath);
  218. peaks[i] = Math.max(0, peaks[i] - 0.02); // let peaks fall quickly
  219. }
  220. const x = Math.round(i * (barW + gap));
  221. const barH = val * h;
  222. if (barH > 0.5) {
  223. // Bar colour: green (120°) → yellow (60°) → red (0°)
  224. const hue = Math.round((1 - val) * 120);
  225. const lit = hasSignal ? 42 : 25; // dimmer in idle
  226. ctx2d.fillStyle = `hsl(${hue},100%,${lit}%)`;
  227. ctx2d.fillRect(x, h - barH, barW, barH);
  228. }
  229. // Peak indicator
  230. if (peaks[i] > 0.02) {
  231. const py = Math.round(h - peaks[i] * h) - 1;
  232. ctx2d.fillStyle = hasSignal ? 'rgba(255,255,255,0.75)' : 'rgba(255,255,255,0.2)';
  233. ctx2d.fillRect(x, py, barW, 2);
  234. }
  235. }
  236. // "No signal" label when disconnected or stopped
  237. if (!ws || ws.readyState !== WebSocket.OPEN) {
  238. drawLabel(ctx2d, w, h, '● NO SIGNAL', '#333');
  239. } else if (!winampPlaying) {
  240. drawLabel(ctx2d, w, h, '▶ PLAY', '#1a3a1a');
  241. }
  242. }
  243. function drawLabel(ctx, w, h, text, color) {
  244. ctx.font = `bold ${Math.round(h * 0.22)}px monospace`;
  245. ctx.textAlign = 'center';
  246. ctx.textBaseline = 'middle';
  247. ctx.fillStyle = color;
  248. ctx.fillText(text, w / 2, h / 2);
  249. }
  250. // ── Helpers ───────────────────────────────────────────────────────────────────
  251. function fmtTime(secs) {
  252. const m = Math.floor(secs / 60);
  253. const s = String(Math.floor(secs % 60)).padStart(2, '0');
  254. return `${m}:${s}`;
  255. }
  256. function parseTime(str) {
  257. const [m, s] = (str || '0:00').split(':').map(Number);
  258. return m * 60 + (s || 0);
  259. }
  260. function escHtml(s) {
  261. return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  262. }
  263. let toastTimer;
  264. function showToast(msg) {
  265. let el = $('toast');
  266. if (!el) {
  267. el = document.createElement('div');
  268. el.id = 'toast';
  269. el.style.cssText = [
  270. 'position:fixed', 'bottom:24px', 'left:50%', 'transform:translateX(-50%)',
  271. 'background:#333', 'color:#fff', 'padding:10px 20px', 'border-radius:8px',
  272. 'font-size:14px', 'z-index:999', 'opacity:0', 'transition:opacity .2s',
  273. 'pointer-events:none',
  274. ].join(';');
  275. document.body.appendChild(el);
  276. }
  277. el.textContent = msg;
  278. el.style.opacity = '1';
  279. clearTimeout(toastTimer);
  280. toastTimer = setTimeout(() => { el.style.opacity = '0'; }, 2500);
  281. }
  282. // ── Playlist ──────────────────────────────────────────────────────────────────
  283. $('btn-show-playlist').addEventListener('click', openPlaylist);
  284. $('btn-close-playlist').addEventListener('click', () => {
  285. playlistOverlay.classList.add('hidden');
  286. });
  287. async function openPlaylist() {
  288. playlistOverlay.classList.remove('hidden');
  289. playlistList.innerHTML = '<li id="playlist-loading">Lade…</li>';
  290. let tracks;
  291. try {
  292. tracks = await fetch('/api/playlist').then(r => r.json());
  293. } catch {
  294. playlistList.innerHTML = '<li id="playlist-loading">Fehler beim Laden</li>';
  295. return;
  296. }
  297. if (!tracks || tracks.length === 0) {
  298. playlistList.innerHTML = '<li id="playlist-loading">Playlist leer</li>';
  299. return;
  300. }
  301. const frag = document.createDocumentFragment();
  302. tracks.forEach(t => {
  303. const li = document.createElement('li');
  304. li.dataset.index = t.index - 1; // store 0-based for jump
  305. if (t.index === currentPlaylistPos) li.classList.add('current');
  306. const idx = document.createElement('span');
  307. idx.className = 'pl-idx';
  308. idx.textContent = t.index;
  309. const title = document.createElement('span');
  310. title.className = 'pl-title';
  311. title.textContent = t.title || '–';
  312. li.appendChild(idx);
  313. li.appendChild(title);
  314. li.addEventListener('click', () => {
  315. send({ cmd: 'jump', index: parseInt(li.dataset.index, 10) });
  316. playlistOverlay.classList.add('hidden');
  317. });
  318. frag.appendChild(li);
  319. });
  320. playlistList.innerHTML = '';
  321. playlistList.appendChild(frag);
  322. scrollToCurrentTrack();
  323. }
  324. function updatePlaylistHighlight() {
  325. if (playlistOverlay.classList.contains('hidden')) return;
  326. playlistList.querySelectorAll('li').forEach(li => {
  327. const isCurrent = parseInt(li.dataset.index, 10) === currentPlaylistPos - 1;
  328. li.classList.toggle('current', isCurrent);
  329. });
  330. scrollToCurrentTrack();
  331. }
  332. function scrollToCurrentTrack() {
  333. const current = playlistList.querySelector('li.current');
  334. if (current) current.scrollIntoView({ block: 'center', behavior: 'smooth' });
  335. }
  336. // ── Boot ──────────────────────────────────────────────────────────────────────
  337. connect();
  338. renderFrame();