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.

451 line
16KB

  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. // Canvas display mode — cycles on click: viz → actual → remaining → viz
  34. const VIZ_MODES = ['viz', 'actual', 'remaining'];
  35. let vizMode = 'viz';
  36. let currentPosition = 0;
  37. let currentLength = 0;
  38. // ── WebSocket ─────────────────────────────────────────────────────────────────
  39. function connect() {
  40. const proto = location.protocol === 'https:' ? 'wss' : 'ws';
  41. ws = new WebSocket(`${proto}://${location.host}/ws`);
  42. ws.addEventListener('open', () => {
  43. statusDot.className = 'ok';
  44. stateLabel.textContent = 'Verbunden';
  45. clearTimeout(reconnectTimer);
  46. });
  47. ws.addEventListener('close', () => {
  48. statusDot.className = 'err';
  49. stateLabel.textContent = 'Verbindung unterbrochen…';
  50. ws = null;
  51. reconnectTimer = setTimeout(connect, 3000);
  52. });
  53. ws.addEventListener('error', () => ws.close());
  54. ws.addEventListener('message', e => {
  55. let msg;
  56. try { msg = JSON.parse(e.data); } catch { return; }
  57. if (msg.type === 'status') applyStatus(msg);
  58. if (msg.type === 'viz') applyViz(msg.bars);
  59. });
  60. }
  61. function send(obj) {
  62. if (ws && ws.readyState === WebSocket.OPEN) {
  63. ws.send(JSON.stringify(obj));
  64. }
  65. }
  66. // ── Status handler ────────────────────────────────────────────────────────────
  67. function applyStatus(st) {
  68. if (!st.running) {
  69. statusDot.className = 'err';
  70. stateLabel.textContent = 'Winamp nicht gestartet';
  71. trackTitle.textContent = '–';
  72. playlistPos.textContent = '';
  73. return;
  74. }
  75. statusDot.className = 'ok';
  76. const stateMap = { playing: '▶ Spielt', paused: '⏸ Pause', stopped: '⏹ Stop' };
  77. stateLabel.textContent = stateMap[st.state] ?? st.state;
  78. trackTitle.textContent = st.title || '–';
  79. playlistPos.textContent = st.playlist_length
  80. ? `${st.playlist_pos} / ${st.playlist_length}` : '';
  81. if (st.playlist_pos !== currentPlaylistPos) {
  82. currentPlaylistPos = st.playlist_pos;
  83. updatePlaylistHighlight();
  84. }
  85. if (st.length > 0) {
  86. currentPosition = st.position;
  87. currentLength = st.length;
  88. progressFill.style.width = (st.position / st.length * 100).toFixed(1) + '%';
  89. timeCurrent.textContent = fmtTime(st.position);
  90. timeLength.textContent = '-' + fmtTime(st.length - st.position);
  91. } else {
  92. progressFill.style.width = '0%';
  93. timeCurrent.textContent = '0:00';
  94. timeLength.textContent = '-0:00';
  95. }
  96. btnPlay.textContent = st.state === 'playing' ? '⏸' : '▶';
  97. winampPlaying = st.state === 'playing';
  98. if (typeof st.volume === 'number') {
  99. currentVolume = st.volume;
  100. updateVolumeFill(st.muted);
  101. updateMuteBtn(st.muted);
  102. }
  103. }
  104. // ── Controls ──────────────────────────────────────────────────────────────────
  105. btnPlay.addEventListener('click', () => {
  106. // Optimistic toggle — server will push the real state back immediately.
  107. const playing = btnPlay.textContent === '⏸';
  108. send({ cmd: playing ? 'pause' : 'play' });
  109. });
  110. $('btn-stop').addEventListener('click', () => send({ cmd: 'stop' }));
  111. $('btn-next').addEventListener('click', () => send({ cmd: 'next' }));
  112. $('btn-prev').addEventListener('click', () => send({ cmd: 'prev' }));
  113. document.querySelectorAll('.btn-seek').forEach(btn => {
  114. btn.addEventListener('click', () =>
  115. send({ cmd: 'seek', delta: parseInt(btn.dataset.delta, 10) }));
  116. });
  117. $('progress-bar').addEventListener('click', async e => {
  118. // Derive total from current + remaining (timeLength shows "-mm:ss").
  119. const current = parseTime(timeCurrent.textContent);
  120. const remaining = parseTime(timeLength.textContent.replace('-', ''));
  121. const total = current + remaining;
  122. if (!total) return;
  123. const rect = e.currentTarget.getBoundingClientRect();
  124. const target = Math.round((e.clientX - rect.left) / rect.width * total);
  125. send({ cmd: 'seek', delta: target - current });
  126. });
  127. // ── Volume ────────────────────────────────────────────────────────────────────
  128. $('btn-vol-up').addEventListener('click', () => {
  129. currentVolume = Math.min(100, currentVolume + 5);
  130. send({ cmd: 'volume', level: currentVolume });
  131. updateVolumeFill();
  132. });
  133. $('btn-vol-down').addEventListener('click', () => {
  134. currentVolume = Math.max(0, currentVolume - 5);
  135. send({ cmd: 'volume', level: currentVolume });
  136. updateVolumeFill();
  137. });
  138. $('volume-bar').addEventListener('click', e => {
  139. const rect = e.currentTarget.getBoundingClientRect();
  140. currentVolume = Math.round((e.clientX - rect.left) / rect.width * 100);
  141. send({ cmd: 'volume', level: currentVolume });
  142. updateVolumeFill();
  143. });
  144. btnMute.addEventListener('click', () => {
  145. const nowMuted = btnMute.classList.contains('muted');
  146. send({ cmd: 'mute', muted: !nowMuted });
  147. updateMuteBtn(!nowMuted);
  148. updateVolumeFill(!nowMuted);
  149. });
  150. function updateVolumeFill(muted = btnMute.classList.contains('muted')) {
  151. volumeFill.style.width = currentVolume + '%';
  152. volumePct.textContent = currentVolume + ' %';
  153. volumeFill.classList.toggle('muted', muted);
  154. }
  155. function updateMuteBtn(muted) {
  156. btnMute.textContent = muted ? '🔇' : '🔊';
  157. btnMute.classList.toggle('muted', muted);
  158. }
  159. // ── KillList ──────────────────────────────────────────────────────────────────
  160. $('btn-kill').addEventListener('click', () => {
  161. send({ cmd: 'killist_add' });
  162. showToast('🚫 Track zur Skip-Liste hinzugefügt');
  163. });
  164. $('btn-show-killist').addEventListener('click', async () => {
  165. const list = await fetch('/api/killist').then(r => r.json()).catch(() => []);
  166. killistItems.innerHTML = '';
  167. (list || []).forEach(title => {
  168. const li = document.createElement('li');
  169. li.innerHTML = `<span>${escHtml(title)}</span>`;
  170. const btn = document.createElement('button');
  171. btn.textContent = '✕';
  172. btn.onclick = () => {
  173. send({ cmd: 'killist_remove', title });
  174. li.remove();
  175. };
  176. li.appendChild(btn);
  177. killistItems.appendChild(li);
  178. });
  179. killistPanel.classList.remove('hidden');
  180. });
  181. $('btn-close-killist').addEventListener('click', () =>
  182. killistPanel.classList.add('hidden'));
  183. // ── Visualisation (Canvas) ────────────────────────────────────────────────────
  184. canvas.addEventListener('click', () => {
  185. vizMode = VIZ_MODES[(VIZ_MODES.indexOf(vizMode) + 1) % VIZ_MODES.length];
  186. });
  187. function applyViz(bars) {
  188. if (!bars || bars.length === 0) return;
  189. lastBars = new Float32Array(bars);
  190. lastVizAt = performance.now();
  191. }
  192. function renderFrame(ts = 0) {
  193. rafId = requestAnimationFrame(renderFrame);
  194. // Resize canvas to CSS size (handles window resize / DPR).
  195. // Setting canvas.width resets the transform, so we re-apply scale.
  196. const dpr = window.devicePixelRatio || 1;
  197. const cssW = canvas.clientWidth;
  198. const cssH = canvas.clientHeight;
  199. if (canvas.width !== Math.round(cssW * dpr) || canvas.height !== Math.round(cssH * dpr)) {
  200. canvas.width = Math.round(cssW * dpr);
  201. canvas.height = Math.round(cssH * dpr);
  202. ctx2d.scale(dpr, dpr);
  203. }
  204. const w = cssW;
  205. const h = cssH;
  206. if (w === 0 || h === 0) return;
  207. // Background
  208. ctx2d.fillStyle = '#000';
  209. ctx2d.fillRect(0, 0, w, h);
  210. // ── Time display modes ──────────────────────────────────────────────────────
  211. if (vizMode === 'actual' || vizMode === 'remaining') {
  212. const isActual = vizMode === 'actual';
  213. const secs = isActual ? currentPosition : Math.max(0, currentLength - currentPosition);
  214. const prefix = isActual ? '' : '-';
  215. const timeStr = prefix + fmtTimeLong(secs);
  216. const label = isActual ? 'ELAPSED' : 'REMAINING';
  217. ctx2d.textAlign = 'center';
  218. ctx2d.textBaseline = 'middle';
  219. // Large time
  220. ctx2d.font = `bold ${Math.round(h * 0.52)}px monospace`;
  221. ctx2d.fillStyle = isActual ? '#e0e0e0' : '#e94560';
  222. ctx2d.fillText(timeStr, w / 2, h * 0.48);
  223. // Small label below
  224. ctx2d.font = `${Math.round(h * 0.18)}px monospace`;
  225. ctx2d.fillStyle = '#444';
  226. ctx2d.fillText(label, w / 2, h * 0.82);
  227. return;
  228. }
  229. // ── Spectrum mode ───────────────────────────────────────────────────────────
  230. // Check if real viz data is fresh (< 1.5 s old) and Winamp is playing.
  231. const hasSignal = winampPlaying && (performance.now() - lastVizAt) < 1500;
  232. // Classic fixed vertical gradient: green at bottom → yellow → red at top.
  233. // Defined in canvas coords so every bar shows the same colour at the same
  234. // height — no per-frame hue calculation, no flicker.
  235. const grad = ctx2d.createLinearGradient(0, h, 0, 0);
  236. if (hasSignal) {
  237. grad.addColorStop(0, '#00aa00');
  238. grad.addColorStop(0.6, '#aaaa00');
  239. grad.addColorStop(1, '#cc0000');
  240. } else {
  241. // Idle: same palette but much dimmer
  242. grad.addColorStop(0, '#003300');
  243. grad.addColorStop(0.6, '#333300');
  244. grad.addColorStop(1, '#330000');
  245. }
  246. const n = NUM_BARS;
  247. const gap = 1;
  248. const barW = Math.max(1, (w - gap * (n - 1)) / n);
  249. for (let i = 0; i < n; i++) {
  250. let val;
  251. if (hasSignal) {
  252. val = lastBars[i] || 0;
  253. if (val > peaks[i]) peaks[i] = val;
  254. else peaks[i] = Math.max(0, peaks[i] - 0.008); // gentle decay
  255. } else {
  256. // Idle: slow sine breathing
  257. const phase = (ts / 1800) + (i / n) * Math.PI * 2;
  258. const breath = (Math.sin(ts / 2000) * 0.5 + 0.5) * 0.08;
  259. val = Math.max(0, Math.sin(phase) * breath);
  260. peaks[i] = Math.max(0, peaks[i] - 0.02);
  261. }
  262. const x = Math.round(i * (barW + gap));
  263. const barH = val * h;
  264. if (barH > 0.5) {
  265. ctx2d.fillStyle = grad;
  266. ctx2d.fillRect(x, h - barH, barW, barH);
  267. }
  268. // Peak dot — 1 px taller slice of the same gradient, slightly brighter
  269. if (peaks[i] > 0.02) {
  270. const py = Math.round(h - peaks[i] * h) - 1;
  271. ctx2d.fillStyle = hasSignal ? 'rgba(255,255,255,0.6)' : 'rgba(255,255,255,0.15)';
  272. ctx2d.fillRect(x, py, barW, 2);
  273. }
  274. }
  275. // "No signal" label when disconnected or stopped
  276. if (!ws || ws.readyState !== WebSocket.OPEN) {
  277. drawLabel(ctx2d, w, h, '● NO SIGNAL', '#333');
  278. } else if (!winampPlaying) {
  279. drawLabel(ctx2d, w, h, '▶ PLAY', '#1a3a1a');
  280. }
  281. }
  282. function drawLabel(ctx, w, h, text, color) {
  283. ctx.font = `bold ${Math.round(h * 0.22)}px monospace`;
  284. ctx.textAlign = 'center';
  285. ctx.textBaseline = 'middle';
  286. ctx.fillStyle = color;
  287. ctx.fillText(text, w / 2, h / 2);
  288. }
  289. // ── Helpers ───────────────────────────────────────────────────────────────────
  290. function fmtTime(secs) {
  291. const m = Math.floor(secs / 60);
  292. const s = String(Math.floor(secs % 60)).padStart(2, '0');
  293. return `${m}:${s}`;
  294. }
  295. // Like fmtTime but always zero-pads to hh:mm:ss for the canvas display.
  296. function fmtTimeLong(secs) {
  297. secs = Math.floor(secs);
  298. const h = Math.floor(secs / 3600);
  299. const m = Math.floor((secs % 3600) / 60);
  300. const s = secs % 60;
  301. return `${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
  302. }
  303. function parseTime(str) {
  304. const [m, s] = (str || '0:00').split(':').map(Number);
  305. return m * 60 + (s || 0);
  306. }
  307. function escHtml(s) {
  308. return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  309. }
  310. let toastTimer;
  311. function showToast(msg) {
  312. let el = $('toast');
  313. if (!el) {
  314. el = document.createElement('div');
  315. el.id = 'toast';
  316. el.style.cssText = [
  317. 'position:fixed', 'bottom:24px', 'left:50%', 'transform:translateX(-50%)',
  318. 'background:#333', 'color:#fff', 'padding:10px 20px', 'border-radius:8px',
  319. 'font-size:14px', 'z-index:999', 'opacity:0', 'transition:opacity .2s',
  320. 'pointer-events:none',
  321. ].join(';');
  322. document.body.appendChild(el);
  323. }
  324. el.textContent = msg;
  325. el.style.opacity = '1';
  326. clearTimeout(toastTimer);
  327. toastTimer = setTimeout(() => { el.style.opacity = '0'; }, 2500);
  328. }
  329. // ── Playlist ──────────────────────────────────────────────────────────────────
  330. $('btn-show-playlist').addEventListener('click', openPlaylist);
  331. $('btn-close-playlist').addEventListener('click', () => {
  332. playlistOverlay.classList.add('hidden');
  333. });
  334. async function openPlaylist() {
  335. playlistOverlay.classList.remove('hidden');
  336. playlistList.innerHTML = '<li id="playlist-loading">Lade…</li>';
  337. let tracks;
  338. try {
  339. tracks = await fetch('/api/playlist').then(r => r.json());
  340. } catch {
  341. playlistList.innerHTML = '<li id="playlist-loading">Fehler beim Laden</li>';
  342. return;
  343. }
  344. if (!tracks || tracks.length === 0) {
  345. playlistList.innerHTML = '<li id="playlist-loading">Playlist leer</li>';
  346. return;
  347. }
  348. const frag = document.createDocumentFragment();
  349. tracks.forEach(t => {
  350. const li = document.createElement('li');
  351. li.dataset.index = t.index - 1; // store 0-based for jump
  352. if (t.index === currentPlaylistPos) li.classList.add('current');
  353. const idx = document.createElement('span');
  354. idx.className = 'pl-idx';
  355. idx.textContent = t.index;
  356. const title = document.createElement('span');
  357. title.className = 'pl-title';
  358. title.textContent = t.title || '–';
  359. li.appendChild(idx);
  360. li.appendChild(title);
  361. li.addEventListener('click', () => {
  362. send({ cmd: 'jump', index: parseInt(li.dataset.index, 10) });
  363. playlistOverlay.classList.add('hidden');
  364. });
  365. frag.appendChild(li);
  366. });
  367. playlistList.innerHTML = '';
  368. playlistList.appendChild(frag);
  369. scrollToCurrentTrack();
  370. }
  371. function updatePlaylistHighlight() {
  372. if (playlistOverlay.classList.contains('hidden')) return;
  373. playlistList.querySelectorAll('li').forEach(li => {
  374. const isCurrent = parseInt(li.dataset.index, 10) === currentPlaylistPos - 1;
  375. li.classList.toggle('current', isCurrent);
  376. });
  377. scrollToCurrentTrack();
  378. }
  379. function scrollToCurrentTrack() {
  380. const current = playlistList.querySelector('li.current');
  381. if (current) current.scrollIntoView({ block: 'center', behavior: 'smooth' });
  382. }
  383. // ── Boot ──────────────────────────────────────────────────────────────────────
  384. connect();
  385. renderFrame();