Wideband autonomous SDR analysis engine forked from sdr-visual-suite
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

2163 satır
76KB

  1. const qs = (id) => document.getElementById(id);
  2. const navCanvas = qs('navCanvas');
  3. const spectrumCanvas = qs('spectrum');
  4. const waterfallCanvas = qs('waterfall');
  5. const occupancyCanvas = qs('occupancy');
  6. const timelineCanvas = qs('timeline');
  7. const detailSpectrogram = qs('detailSpectrogram');
  8. const signalPopover = qs('signalPopover');
  9. const wsBadge = qs('wsBadge');
  10. const metaLine = qs('metaLine');
  11. const heroSubtitle = qs('heroSubtitle');
  12. const configStatusEl = qs('configStatus');
  13. const timelineRangeEl = qs('timelineRange');
  14. const metricCenter = qs('metricCenter');
  15. const metricSpan = qs('metricSpan');
  16. const metricRes = qs('metricRes');
  17. const metricSignals = qs('metricSignals');
  18. const metricGpu = qs('metricGpu');
  19. const metricSource = qs('metricSource');
  20. const centerInput = qs('centerInput');
  21. const spanInput = qs('spanInput');
  22. const sampleRateSelect = qs('sampleRateSelect');
  23. const bwSelect = qs('bwSelect');
  24. const fftSelect = qs('fftSelect');
  25. const gainRange = qs('gainRange');
  26. const gainInput = qs('gainInput');
  27. const thresholdRange = qs('thresholdRange');
  28. const thresholdInput = qs('thresholdInput');
  29. const cfarModeSelect = qs('cfarModeSelect');
  30. const cfarWrapToggle = qs('cfarWrapToggle');
  31. const cfarGuardHzInput = qs('cfarGuardHzInput');
  32. const cfarTrainHzInput = qs('cfarTrainHzInput');
  33. const cfarRankInput = qs('cfarRankInput');
  34. const classifierModeSelect = qs('classifierModeSelect');
  35. const edgeMarginInput = qs('edgeMarginInput');
  36. const mergeGapInput = qs('mergeGapInput');
  37. const classHistoryInput = qs('classHistoryInput');
  38. const classSwitchInput = qs('classSwitchInput');
  39. const cfarScaleInput = qs('cfarScaleInput');
  40. const minDurationInput = qs('minDurationInput');
  41. const holdInput = qs('holdInput');
  42. const emaAlphaInput = qs('emaAlphaInput');
  43. const hysteresisInput = qs('hysteresisInput');
  44. const stableFramesInput = qs('stableFramesInput');
  45. const gapToleranceInput = qs('gapToleranceInput');
  46. const agcToggle = qs('agcToggle');
  47. const dcToggle = qs('dcToggle');
  48. const iqToggle = qs('iqToggle');
  49. const avgSelect = qs('avgSelect');
  50. const maxHoldToggle = qs('maxHoldToggle');
  51. const gpuToggle = qs('gpuToggle');
  52. const recEnableToggle = qs('recEnableToggle');
  53. const recIQToggle = qs('recIQToggle');
  54. const recAudioToggle = qs('recAudioToggle');
  55. const recDemodToggle = qs('recDemodToggle');
  56. const recDecodeToggle = qs('recDecodeToggle');
  57. const recMinSNR = qs('recMinSNR');
  58. const recMaxDisk = qs('recMaxDisk');
  59. const recClassFilter = qs('recClassFilter');
  60. const signalList = qs('signalList');
  61. const eventList = qs('eventList');
  62. const recordingList = qs('recordingList');
  63. const signalCountBadge = qs('signalCountBadge');
  64. const eventCountBadge = qs('eventCountBadge');
  65. const recordingCountBadge = qs('recordingCountBadge');
  66. const healthBuffer = qs('healthBuffer');
  67. const healthDropped = qs('healthDropped');
  68. const healthResets = qs('healthResets');
  69. const healthAge = qs('healthAge');
  70. const healthGpu = qs('healthGpu');
  71. const healthFps = qs('healthFps');
  72. const drawerEl = qs('eventDrawer');
  73. const drawerCloseBtn = qs('drawerClose');
  74. const detailSubtitle = qs('detailSubtitle');
  75. const detailCenterEl = qs('detailCenter');
  76. const detailBwEl = qs('detailBw');
  77. const detailStartEl = qs('detailStart');
  78. const detailEndEl = qs('detailEnd');
  79. const detailSnrEl = qs('detailSnr');
  80. const detailDurEl = qs('detailDur');
  81. const detailClassEl = qs('detailClass');
  82. const jumpToEventBtn = qs('jumpToEventBtn');
  83. const exportEventBtn = qs('exportEventBtn');
  84. const liveListenEventBtn = qs('liveListenEventBtn');
  85. const decodeEventBtn = qs('decodeEventBtn');
  86. const decodeModeSelect = qs('decodeMode');
  87. const recordingMetaEl = qs('recordingMeta');
  88. const decodeResultEl = qs('decodeResult');
  89. const classifierScoresEl = qs('classifierScores');
  90. const classifierScoreBarsEl = qs('classifierScoreBars');
  91. const recordingMetaLink = qs('recordingMetaLink');
  92. const recordingIQLink = qs('recordingIQLink');
  93. const recordingAudioLink = qs('recordingAudioLink');
  94. const followBtn = qs('followBtn');
  95. const fitBtn = qs('fitBtn');
  96. const resetMaxBtn = qs('resetMaxBtn');
  97. const debugOverlayToggle = qs('debugOverlayToggle');
  98. const timelineFollowBtn = qs('timelineFollowBtn');
  99. const timelineFreezeBtn = qs('timelineFreezeBtn');
  100. const modeButtons = Array.from(document.querySelectorAll('.mode-btn'));
  101. const railTabs = Array.from(document.querySelectorAll('.rail-tab'));
  102. const tabPanels = Array.from(document.querySelectorAll('.tab-panel'));
  103. const presetButtons = Array.from(document.querySelectorAll('.preset-btn'));
  104. const liveListenBtn = qs('liveListenBtn');
  105. const listenSecondsInput = qs('listenSeconds');
  106. const listenModeSelect = qs('listenMode');
  107. let latest = null;
  108. let currentConfig = null;
  109. let liveAudio = null;
  110. let liveListenWS = null; // WebSocket-based live listen
  111. let liveListenTarget = null; // { freq, bw, mode }
  112. let stats = { buffer_samples: 0, dropped: 0, resets: 0, last_sample_ago_ms: -1 };
  113. // ---------------------------------------------------------------------------
  114. // LiveListenWS — WebSocket-based gapless audio streaming via /ws/audio
  115. // ---------------------------------------------------------------------------
  116. class LiveListenWS {
  117. constructor(freq, bw, mode) {
  118. this.freq = freq;
  119. this.bw = bw;
  120. this.mode = mode;
  121. this.ws = null;
  122. this.audioCtx = null;
  123. this.sampleRate = 48000;
  124. this.channels = 1;
  125. this.playing = false;
  126. this.queue = []; // buffered PCM chunks
  127. this.nextTime = 0; // next scheduled playback time
  128. this.started = false;
  129. this._onStop = null;
  130. }
  131. start() {
  132. const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
  133. const url = `${proto}//${location.host}/ws/audio?freq=${this.freq}&bw=${this.bw}&mode=${this.mode || ''}`;
  134. this.ws = new WebSocket(url);
  135. this.ws.binaryType = 'arraybuffer';
  136. this.playing = true;
  137. this.ws.onmessage = (ev) => {
  138. if (typeof ev.data === 'string') {
  139. // audio_info JSON message (initial or updated when session attached)
  140. try {
  141. const info = JSON.parse(ev.data);
  142. if (info.sample_rate || info.channels) {
  143. const newRate = info.sample_rate || 48000;
  144. const newCh = info.channels || 1;
  145. // If channels or rate changed, reinit AudioContext
  146. if (newRate !== this.sampleRate || newCh !== this.channels) {
  147. this.sampleRate = newRate;
  148. this.channels = newCh;
  149. if (this.audioCtx) {
  150. this.audioCtx.close().catch(() => {});
  151. this.audioCtx = null;
  152. }
  153. this.started = false;
  154. this.nextTime = 0;
  155. }
  156. this._initAudio();
  157. }
  158. } catch (e) { /* ignore */ }
  159. return;
  160. }
  161. // Binary PCM data (s16le)
  162. if (!this.audioCtx || !this.playing) return;
  163. this._playChunk(ev.data);
  164. };
  165. this.ws.onclose = () => {
  166. this.playing = false;
  167. if (this._onStop) this._onStop();
  168. };
  169. this.ws.onerror = () => {
  170. this.playing = false;
  171. if (this._onStop) this._onStop();
  172. };
  173. // If no audio_info arrives within 500ms, init with defaults
  174. setTimeout(() => {
  175. if (!this.audioCtx && this.playing) this._initAudio();
  176. }, 500);
  177. }
  178. stop() {
  179. this.playing = false;
  180. if (this.ws) {
  181. this.ws.close();
  182. this.ws = null;
  183. }
  184. if (this.audioCtx) {
  185. this.audioCtx.close().catch(() => {});
  186. this.audioCtx = null;
  187. }
  188. this.queue = [];
  189. this.nextTime = 0;
  190. this.started = false;
  191. }
  192. onStop(fn) { this._onStop = fn; }
  193. _initAudio() {
  194. if (this.audioCtx) return;
  195. this.audioCtx = new (window.AudioContext || window.webkitAudioContext)({
  196. sampleRate: this.sampleRate
  197. });
  198. this.nextTime = 0;
  199. this.started = false;
  200. }
  201. _playChunk(buf) {
  202. const ctx = this.audioCtx;
  203. if (!ctx) return;
  204. const samples = new Int16Array(buf);
  205. const nFrames = Math.floor(samples.length / this.channels);
  206. if (nFrames === 0) return;
  207. const audioBuffer = ctx.createBuffer(this.channels, nFrames, this.sampleRate);
  208. for (let ch = 0; ch < this.channels; ch++) {
  209. const channelData = audioBuffer.getChannelData(ch);
  210. for (let i = 0; i < nFrames; i++) {
  211. channelData[i] = samples[i * this.channels + ch] / 32768;
  212. }
  213. }
  214. const source = ctx.createBufferSource();
  215. source.buffer = audioBuffer;
  216. source.connect(ctx.destination);
  217. // Schedule gapless playback with drift correction.
  218. // We target a small jitter buffer (~100ms ahead of real time).
  219. // If nextTime falls behind currentTime, we resync with a small
  220. // buffer to avoid audible gaps.
  221. const now = ctx.currentTime;
  222. const targetLatency = 0.1; // 100ms jitter buffer
  223. if (!this.started || this.nextTime < now) {
  224. // First chunk or buffer underrun — resync
  225. this.nextTime = now + targetLatency;
  226. this.started = true;
  227. }
  228. // If we've drifted too far ahead (>500ms of buffered audio),
  229. // drop this chunk to reduce latency. This prevents the buffer
  230. // from growing unbounded when the server sends faster than realtime.
  231. if (this.nextTime > now + 0.5) {
  232. return; // drop — too much buffered
  233. }
  234. source.start(this.nextTime);
  235. this.nextTime += audioBuffer.duration;
  236. }
  237. }
  238. function resolveListenMode(detectedMode) {
  239. const manual = listenModeSelect?.value || '';
  240. if (manual) return manual;
  241. return detectedMode || 'NFM';
  242. }
  243. function setLiveListenUI(active) {
  244. if (liveListenBtn) {
  245. liveListenBtn.textContent = active ? '■ Stop' : 'Live Listen';
  246. liveListenBtn.classList.toggle('active', active);
  247. }
  248. if (liveListenEventBtn) {
  249. liveListenEventBtn.textContent = active ? '■ Stop' : 'Listen';
  250. liveListenEventBtn.classList.toggle('active', active);
  251. }
  252. }
  253. function stopLiveListen() {
  254. if (liveListenWS) {
  255. liveListenWS.onStop(() => {});
  256. liveListenWS.stop();
  257. liveListenWS = null;
  258. }
  259. liveListenTarget = null;
  260. setLiveListenUI(false);
  261. }
  262. function startLiveListen(freq, bw, detectedMode) {
  263. if (!Number.isFinite(freq)) return;
  264. const mode = resolveListenMode(detectedMode);
  265. const width = Number.isFinite(bw) && bw > 0 ? bw : 12000;
  266. // Stop any old HTTP audio
  267. if (liveAudio) { liveAudio.pause(); liveAudio = null; }
  268. // Switch on the fly if already listening
  269. if (liveListenWS) {
  270. liveListenWS.onStop(() => {});
  271. liveListenWS.stop();
  272. liveListenWS = null;
  273. }
  274. liveListenTarget = { freq, bw: width, mode };
  275. liveListenWS = new LiveListenWS(freq, width, mode);
  276. liveListenWS.onStop(() => {
  277. liveListenWS = null;
  278. liveListenTarget = null;
  279. setLiveListenUI(false);
  280. });
  281. liveListenWS.start();
  282. setLiveListenUI(true);
  283. }
  284. function matchesListenTarget(signal) {
  285. if (!liveListenTarget || !signal) return false;
  286. const bw = signal.bw_hz || liveListenTarget.bw || 0;
  287. const tol = Math.max(500, bw * 0.5);
  288. return Math.abs((signal.center_hz || 0) - liveListenTarget.freq) <= tol;
  289. }
  290. let gpuInfo = { available: false, active: false, error: '' };
  291. let zoom = 1;
  292. let pan = 0;
  293. let followLive = true;
  294. let maxHold = false;
  295. let avgAlpha = 0;
  296. let avgSpectrum = null;
  297. let maxSpectrum = null;
  298. let lastFFTSize = null;
  299. let processedSpectrum = null;
  300. let processedSpectrumSource = null;
  301. let processingDirty = true;
  302. let pendingConfigUpdate = null;
  303. let pendingSettingsUpdate = null;
  304. let configTimer = null;
  305. let settingsTimer = null;
  306. let isSyncingConfig = false;
  307. let isDraggingSpectrum = false;
  308. let dragStartX = 0;
  309. let dragStartPan = 0;
  310. let navDrag = false;
  311. let timelineFrozen = false;
  312. let renderFrames = 0;
  313. let renderFps = 0;
  314. let lastFpsTs = performance.now();
  315. let wsReconnectTimer = null;
  316. let eventsFetchInFlight = false;
  317. const events = [];
  318. const eventsById = new Map();
  319. let lastEventEndMs = 0;
  320. let selectedEventId = null;
  321. let timelineRects = [];
  322. let liveSignalRects = [];
  323. let recordings = [];
  324. let recordingsFetchInFlight = false;
  325. let showDebugOverlay = localStorage.getItem('spectre.debugOverlay') !== '0';
  326. let hoveredSignal = null;
  327. let popoverHideTimer = null;
  328. const GAIN_MAX = 60;
  329. const timelineWindowMs = 5 * 60 * 1000;
  330. function setConfigStatus(text) {
  331. configStatusEl.textContent = text;
  332. }
  333. function setWsBadge(text, kind = 'neutral') {
  334. wsBadge.textContent = text;
  335. wsBadge.style.borderColor = kind === 'ok'
  336. ? 'rgba(124, 251, 131, 0.35)'
  337. : kind === 'bad'
  338. ? 'rgba(255, 107, 129, 0.35)'
  339. : 'rgba(112, 150, 207, 0.18)';
  340. }
  341. function toMHz(hz) { return hz / 1e6; }
  342. function fromMHz(mhz) { return mhz * 1e6; }
  343. function fmtMHz(hz, digits = 3) { return `${(hz / 1e6).toFixed(digits)} MHz`; }
  344. function fmtKHz(hz, digits = 2) { return `${(hz / 1e3).toFixed(digits)} kHz`; }
  345. function fmtHz(hz) {
  346. if (hz >= 1e6) return `${(hz / 1e6).toFixed(3)} MHz`;
  347. if (hz >= 1e3) return `${(hz / 1e3).toFixed(2)} kHz`;
  348. return `${hz.toFixed(0)} Hz`;
  349. }
  350. function fmtMs(ms) {
  351. if (ms < 1000) return `${Math.max(0, Math.round(ms))} ms`;
  352. return `${(ms / 1000).toFixed(2)} s`;
  353. }
  354. function scoreEntries(scores, limit = 6) {
  355. if (!scores || typeof scores !== 'object') return [];
  356. return Object.entries(scores)
  357. .filter(([, v]) => Number.isFinite(Number(v)))
  358. .sort((a, b) => Number(b[1]) - Number(a[1]))
  359. .slice(0, limit);
  360. }
  361. function renderScoreBars(scores) {
  362. if (!classifierScoreBarsEl) return;
  363. const entries = scoreEntries(scores);
  364. if (!entries.length) {
  365. classifierScoreBarsEl.innerHTML = '';
  366. return;
  367. }
  368. const maxVal = Math.max(...entries.map(([, v]) => Number(v)), 1e-6);
  369. classifierScoreBarsEl.innerHTML = entries.map(([label, value]) => {
  370. const width = Math.max(4, (Number(value) / maxVal) * 100);
  371. return `<div class="score-bar"><span class="score-bar-label">${label}</span><span class="score-bar-track"><span class="score-bar-fill" style="width:${width}%"></span></span><span class="score-bar-value">${Number(value).toFixed(2)}</span></div>`;
  372. }).join('');
  373. }
  374. function hideSignalPopover() {
  375. hoveredSignal = null;
  376. if (!signalPopover) return;
  377. signalPopover.classList.remove('open');
  378. signalPopover.setAttribute('aria-hidden', 'true');
  379. }
  380. function renderSignalPopover(rect, signal) {
  381. if (!signalPopover || !signal) return;
  382. const entries = scoreEntries(signal.class?.scores || signal.debug_scores || {}, 4);
  383. const maxVal = Math.max(...entries.map(([, v]) => Number(v)), 1e-6);
  384. const rows = entries.map(([label, value]) => {
  385. const width = Math.max(4, (Number(value) / maxVal) * 100);
  386. return `<div class="signal-popover__row"><span>${label}</span><span class="signal-popover__bar"><span class="signal-popover__fill" style="width:${width}%"></span></span><span>${Number(value).toFixed(2)}</span></div>`;
  387. }).join('');
  388. signalPopover.innerHTML = `<div class="signal-popover__title">${signal.class?.mod_type || 'Signal'}${signal.class?.pll?.rds_station ? ' · ' + signal.class.pll.rds_station : ''}</div><div class="signal-popover__meta">${fmtMHz(signal.class?.pll?.exact_hz || signal.center_hz, 5)} · ${fmtKHz(signal.bw_hz || 0)} · ${(signal.snr_db || 0).toFixed(1)} dB SNR${signal.class?.pll?.locked ? ` · PLL ${signal.class.pll.method} LOCK` : ''}${signal.class?.pll?.stereo ? ' · STEREO' : ''}</div><div class="signal-popover__scores">${rows || '<div class="signal-popover__meta">No classifier scores</div>'}</div>`;
  389. const popW = 220;
  390. const left = rect.x + rect.w + 8;
  391. const top = rect.y + 8;
  392. const maxLeft = Math.max(8, spectrumCanvas.width - popW - 8);
  393. signalPopover.style.left = `${Math.max(8, Math.min(maxLeft, left))}px`;
  394. signalPopover.style.top = `${Math.max(8, top)}px`;
  395. signalPopover.classList.add('open');
  396. signalPopover.setAttribute('aria-hidden', 'false');
  397. }
  398. function colorMap(v) {
  399. const x = Math.max(0, Math.min(1, v));
  400. const r = Math.floor(255 * Math.pow(x, 0.55));
  401. const g = Math.floor(255 * Math.pow(x, 1.08));
  402. const b = Math.floor(220 * Math.pow(1 - x, 1.15));
  403. return [r, g, b];
  404. }
  405. function snrColor(snr) {
  406. const norm = Math.max(0, Math.min(1, (snr + 5) / 35));
  407. const [r, g, b] = colorMap(norm);
  408. return `rgb(${r}, ${g}, ${b})`;
  409. }
  410. // Modulation-type color map for signal boxes and badges
  411. function modColor(modType) {
  412. switch (modType) {
  413. case 'WFM': return { r: 72, g: 210, b: 120, label: '#48d278' }; // green
  414. case 'WFM_STEREO': return { r: 72, g: 230, b: 160, label: '#48e6a0' }; // bright green
  415. case 'NFM': return { r: 255, g: 170, b: 60, label: '#ffaa3c' }; // orange
  416. case 'AM': return { r: 90, g: 160, b: 255, label: '#5aa0ff' }; // blue
  417. case 'USB': case 'LSB':
  418. return { r: 160, g: 120, b: 255, label: '#a078ff' }; // purple
  419. case 'CW': return { r: 255, g: 100, b: 100, label: '#ff6464' }; // red
  420. case 'FT8': case 'WSPR': case 'FSK': case 'PSK':
  421. return { r: 255, g: 220, b: 80, label: '#ffdc50' }; // yellow
  422. default: return { r: 160, g: 190, b: 220, label: '#a0bedc' }; // grey-blue
  423. }
  424. }
  425. function modColorStr(modType, alpha) {
  426. const c = modColor(modType);
  427. return `rgba(${c.r}, ${c.g}, ${c.b}, ${alpha})`;
  428. }
  429. function binForFreq(freq, centerHz, sampleRate, n) {
  430. return Math.floor((freq - (centerHz - sampleRate / 2)) / (sampleRate / n));
  431. }
  432. function maxInBinRange(spectrum, b0, b1) {
  433. const n = spectrum.length;
  434. let start = Math.max(0, Math.min(n - 1, b0));
  435. let end = Math.max(0, Math.min(n - 1, b1));
  436. if (end < start) [start, end] = [end, start];
  437. let max = -1e9;
  438. for (let i = start; i <= end; i++) {
  439. if (spectrum[i] > max) max = spectrum[i];
  440. }
  441. return max;
  442. }
  443. function sampleOverlayAtX(overlay, x, width, centerHz, sampleRate) {
  444. if (!Array.isArray(overlay) || overlay.length === 0 || width <= 0) return null;
  445. const n = overlay.length;
  446. const span = sampleRate / zoom;
  447. const startHz = centerHz - span / 2 + pan * span;
  448. const endHz = centerHz + span / 2 + pan * span;
  449. const f1 = startHz + (x / width) * (endHz - startHz);
  450. const f2 = startHz + ((x + 1) / width) * (endHz - startHz);
  451. const b0 = binForFreq(f1, centerHz, sampleRate, n);
  452. const b1 = binForFreq(f2, centerHz, sampleRate, n);
  453. return maxInBinRange(overlay, b0, b1);
  454. }
  455. function drawThresholdOverlay(ctx, w, h, minDb, maxDb) {
  456. if (!showDebugOverlay) return;
  457. const thresholds = latest?.debug?.thresholds;
  458. if (!Array.isArray(thresholds) || thresholds.length === 0) return;
  459. ctx.save();
  460. ctx.strokeStyle = 'rgba(255, 196, 92, 0.9)';
  461. ctx.lineWidth = 1.25;
  462. if (ctx.setLineDash) ctx.setLineDash([6, 4]);
  463. ctx.beginPath();
  464. for (let x = 0; x < w; x++) {
  465. const v = sampleOverlayAtX(thresholds, x, w, latest.center_hz, latest.sample_rate);
  466. if (v == null || Number.isNaN(v)) continue;
  467. const y = h - ((v - minDb) / (maxDb - minDb)) * (h - 18) - 6;
  468. if (x === 0) ctx.moveTo(x, y);
  469. else ctx.lineTo(x, y);
  470. }
  471. ctx.stroke();
  472. if (ctx.setLineDash) ctx.setLineDash([]);
  473. ctx.fillStyle = 'rgba(255, 196, 92, 0.95)';
  474. ctx.font = '11px Inter, sans-serif';
  475. ctx.fillText('CFAR', 8, 14);
  476. ctx.restore();
  477. }
  478. function markSpectrumDirty() {
  479. processingDirty = true;
  480. }
  481. function processSpectrum(spectrum) {
  482. if (!spectrum) return spectrum;
  483. let base = spectrum;
  484. if (avgAlpha > 0) {
  485. if (!avgSpectrum || avgSpectrum.length !== spectrum.length) {
  486. avgSpectrum = spectrum.slice();
  487. } else {
  488. for (let i = 0; i < spectrum.length; i++) {
  489. avgSpectrum[i] = avgAlpha * spectrum[i] + (1 - avgAlpha) * avgSpectrum[i];
  490. }
  491. }
  492. base = avgSpectrum;
  493. }
  494. if (maxHold) {
  495. if (!maxSpectrum || maxSpectrum.length !== base.length) {
  496. maxSpectrum = base.slice();
  497. } else {
  498. for (let i = 0; i < base.length; i++) {
  499. if (base[i] > maxSpectrum[i]) maxSpectrum[i] = base[i];
  500. }
  501. }
  502. base = maxSpectrum;
  503. }
  504. return base;
  505. }
  506. function resetProcessingCaches() {
  507. avgSpectrum = null;
  508. maxSpectrum = null;
  509. processedSpectrum = null;
  510. processedSpectrumSource = null;
  511. processingDirty = true;
  512. }
  513. function getProcessedSpectrum() {
  514. if (!latest?.spectrum_db) return null;
  515. if (!processingDirty && processedSpectrumSource === latest.spectrum_db) return processedSpectrum;
  516. processedSpectrum = processSpectrum(latest.spectrum_db);
  517. processedSpectrumSource = latest.spectrum_db;
  518. processingDirty = false;
  519. return processedSpectrum;
  520. }
  521. function resizeCanvas(canvas) {
  522. if (!canvas) return;
  523. const rect = canvas.getBoundingClientRect();
  524. const dpr = window.devicePixelRatio || 1;
  525. const width = Math.max(1, Math.floor(rect.width * dpr));
  526. const height = Math.max(1, Math.floor(rect.height * dpr));
  527. if (canvas.width !== width || canvas.height !== height) {
  528. canvas.width = width;
  529. canvas.height = height;
  530. }
  531. }
  532. function resizeAll() {
  533. [navCanvas, spectrumCanvas, waterfallCanvas, occupancyCanvas, timelineCanvas, detailSpectrogram].forEach(resizeCanvas);
  534. }
  535. window.addEventListener('resize', resizeAll);
  536. resizeAll();
  537. function setSelectValueOrNearest(selectEl, numericValue) {
  538. if (!selectEl) return;
  539. const options = Array.from(selectEl.options || []);
  540. const exact = options.find(o => Number.parseFloat(o.value) === numericValue);
  541. if (exact) {
  542. selectEl.value = exact.value;
  543. return;
  544. }
  545. let best = options[0];
  546. let bestDist = Infinity;
  547. for (const opt of options) {
  548. const dist = Math.abs(Number.parseFloat(opt.value) - numericValue);
  549. if (dist < bestDist) {
  550. best = opt;
  551. bestDist = dist;
  552. }
  553. }
  554. if (best) selectEl.value = best.value;
  555. }
  556. function applyConfigToUI(cfg) {
  557. if (!cfg) return;
  558. isSyncingConfig = true;
  559. centerInput.value = toMHz(cfg.center_hz).toFixed(6);
  560. setSelectValueOrNearest(sampleRateSelect, cfg.sample_rate / 1e6);
  561. setSelectValueOrNearest(bwSelect, cfg.tuner_bw_khz || 1536);
  562. setSelectValueOrNearest(fftSelect, cfg.fft_size);
  563. if (lastFFTSize !== cfg.fft_size) {
  564. resetProcessingCaches();
  565. lastFFTSize = cfg.fft_size;
  566. }
  567. const uiGain = Math.max(0, Math.min(GAIN_MAX, GAIN_MAX - cfg.gain_db));
  568. gainRange.value = uiGain;
  569. gainInput.value = uiGain;
  570. thresholdRange.value = cfg.detector.threshold_db;
  571. thresholdInput.value = cfg.detector.threshold_db;
  572. if (cfarModeSelect) cfarModeSelect.value = cfg.detector.cfar_mode || 'OFF';
  573. if (cfarWrapToggle) cfarWrapToggle.checked = cfg.detector.cfar_wrap_around !== false;
  574. if (cfarGuardHzInput) cfarGuardHzInput.value = cfg.detector.cfar_guard_hz ?? 500;
  575. if (cfarTrainHzInput) cfarTrainHzInput.value = cfg.detector.cfar_train_hz ?? 5000;
  576. if (cfarRankInput) cfarRankInput.value = cfg.detector.cfar_rank ?? 24;
  577. if (cfarScaleInput) cfarScaleInput.value = cfg.detector.cfar_scale_db ?? 6;
  578. const rankRow = cfarRankInput?.closest('.field');
  579. if (rankRow) rankRow.style.display = (cfg.detector.cfar_mode === 'OS') ? '' : 'none';
  580. if (minDurationInput) minDurationInput.value = cfg.detector.min_duration_ms;
  581. if (holdInput) holdInput.value = cfg.detector.hold_ms;
  582. if (emaAlphaInput) emaAlphaInput.value = cfg.detector.ema_alpha ?? 0.2;
  583. if (hysteresisInput) hysteresisInput.value = cfg.detector.hysteresis_db ?? 3;
  584. if (stableFramesInput) stableFramesInput.value = cfg.detector.min_stable_frames ?? 3;
  585. if (gapToleranceInput) gapToleranceInput.value = cfg.detector.gap_tolerance_ms ?? cfg.detector.hold_ms;
  586. if (classifierModeSelect) classifierModeSelect.value = cfg.classifier_mode || 'combined';
  587. if (edgeMarginInput) edgeMarginInput.value = cfg.detector.edge_margin_db ?? 3.0;
  588. if (mergeGapInput) mergeGapInput.value = cfg.detector.merge_gap_hz ?? 5000;
  589. if (classHistoryInput) classHistoryInput.value = cfg.detector.class_history_size ?? 10;
  590. if (classSwitchInput) classSwitchInput.value = cfg.detector.class_switch_ratio ?? 0.6;
  591. agcToggle.checked = !!cfg.agc;
  592. dcToggle.checked = !!cfg.dc_block;
  593. iqToggle.checked = !!cfg.iq_balance;
  594. gpuToggle.checked = !!cfg.use_gpu_fft;
  595. maxHoldToggle.checked = maxHold;
  596. if (cfg.recorder) {
  597. if (recEnableToggle) recEnableToggle.checked = !!cfg.recorder.enabled;
  598. if (recIQToggle) recIQToggle.checked = !!cfg.recorder.record_iq;
  599. if (recAudioToggle) recAudioToggle.checked = !!cfg.recorder.record_audio;
  600. if (recDemodToggle) recDemodToggle.checked = !!cfg.recorder.auto_demod;
  601. if (recDecodeToggle) recDecodeToggle.checked = !!cfg.recorder.auto_decode;
  602. if (recMinSNR) recMinSNR.value = cfg.recorder.min_snr_db ?? 10;
  603. if (recMaxDisk) recMaxDisk.value = cfg.recorder.max_disk_mb ?? 0;
  604. if (recClassFilter) recClassFilter.value = (cfg.recorder.class_filter || []).join(', ');
  605. }
  606. spanInput.value = (cfg.sample_rate / zoom / 1e6).toFixed(3);
  607. isSyncingConfig = false;
  608. }
  609. async function loadConfig() {
  610. try {
  611. const res = await fetch('/api/config');
  612. if (!res.ok) throw new Error('config');
  613. currentConfig = await res.json();
  614. applyConfigToUI(currentConfig);
  615. setConfigStatus('Config synced');
  616. } catch {
  617. setConfigStatus('Config offline');
  618. }
  619. }
  620. async function loadSignals() {
  621. try {
  622. const res = await fetch('/api/signals');
  623. if (!res.ok) return;
  624. const sigs = await res.json();
  625. if (Array.isArray(sigs)) {
  626. latest = latest || {};
  627. latest.signals = sigs;
  628. renderLists();
  629. }
  630. } catch {}
  631. }
  632. async function loadDecoders() {
  633. if (!decodeModeSelect) return;
  634. try {
  635. const res = await fetch('/api/decoders');
  636. if (!res.ok) return;
  637. const list = await res.json();
  638. if (!Array.isArray(list)) return;
  639. const current = decodeModeSelect.value;
  640. decodeModeSelect.innerHTML = '';
  641. list.forEach((mode) => {
  642. const opt = document.createElement('option');
  643. opt.value = mode;
  644. opt.textContent = mode;
  645. decodeModeSelect.appendChild(opt);
  646. });
  647. if (current) decodeModeSelect.value = current;
  648. } catch {}
  649. }
  650. async function loadStats() {
  651. try {
  652. const res = await fetch('/api/stats');
  653. if (!res.ok) return;
  654. stats = await res.json();
  655. } catch {}
  656. }
  657. async function loadGPU() {
  658. try {
  659. const res = await fetch('/api/gpu');
  660. if (!res.ok) return;
  661. gpuInfo = await res.json();
  662. } catch {}
  663. }
  664. function queueConfigUpdate(partial) {
  665. if (isSyncingConfig) return;
  666. pendingConfigUpdate = { ...(pendingConfigUpdate || {}), ...partial };
  667. setConfigStatus('Applying…');
  668. clearTimeout(configTimer);
  669. configTimer = setTimeout(sendConfigUpdate, 180);
  670. }
  671. function queueSettingsUpdate(partial) {
  672. if (isSyncingConfig) return;
  673. pendingSettingsUpdate = { ...(pendingSettingsUpdate || {}), ...partial };
  674. setConfigStatus('Applying…');
  675. clearTimeout(settingsTimer);
  676. settingsTimer = setTimeout(sendSettingsUpdate, 120);
  677. }
  678. async function sendConfigUpdate() {
  679. if (!pendingConfigUpdate) return;
  680. const payload = pendingConfigUpdate;
  681. pendingConfigUpdate = null;
  682. try {
  683. const res = await fetch('/api/config', {
  684. method: 'POST',
  685. headers: { 'Content-Type': 'application/json' },
  686. body: JSON.stringify(payload),
  687. });
  688. if (!res.ok) throw new Error('apply');
  689. currentConfig = await res.json();
  690. applyConfigToUI(currentConfig);
  691. setConfigStatus('Config applied');
  692. } catch {
  693. setConfigStatus('Config apply failed');
  694. }
  695. }
  696. async function sendSettingsUpdate() {
  697. if (!pendingSettingsUpdate) return;
  698. const payload = pendingSettingsUpdate;
  699. pendingSettingsUpdate = null;
  700. try {
  701. const res = await fetch('/api/sdr/settings', {
  702. method: 'POST',
  703. headers: { 'Content-Type': 'application/json' },
  704. body: JSON.stringify(payload),
  705. });
  706. if (!res.ok) throw new Error('apply');
  707. currentConfig = await res.json();
  708. applyConfigToUI(currentConfig);
  709. setConfigStatus('Settings applied');
  710. } catch {
  711. setConfigStatus('Settings apply failed');
  712. }
  713. }
  714. function updateHeroMetrics() {
  715. if (!latest) return;
  716. const span = latest.sample_rate / zoom;
  717. const binHz = latest.sample_rate / Math.max(1, latest.spectrum_db?.length || latest.fft_size || 1);
  718. metricCenter.textContent = fmtMHz(latest.center_hz, 6);
  719. metricSpan.textContent = fmtHz(span);
  720. metricRes.textContent = `${binHz.toFixed(1)} Hz/bin`;
  721. metricSignals.textContent = String(latest.signals?.length || 0);
  722. metricGpu.textContent = gpuInfo.active ? 'ON' : (gpuInfo.available ? 'OFF' : 'N/A');
  723. metricSource.textContent = stats.last_sample_ago_ms >= 0 ? `${stats.last_sample_ago_ms} ms` : 'n/a';
  724. const gpuText = gpuInfo.active ? 'GPU active' : (gpuInfo.available ? 'GPU ready' : 'GPU n/a');
  725. const debug = latest.debug || {};
  726. const thresholdInfo = Array.isArray(debug.thresholds) && debug.thresholds.length
  727. ? `CFAR ${showDebugOverlay ? 'on' : 'hidden'} · noise ${(Number.isFinite(debug.noise_floor) ? debug.noise_floor.toFixed(1) : 'n/a')} dB`
  728. : `CFAR off · noise ${(Number.isFinite(debug.noise_floor) ? debug.noise_floor.toFixed(1) : 'n/a')} dB`;
  729. metaLine.textContent = `${fmtMHz(latest.center_hz, 3)} · ${fmtHz(span)} span · ${thresholdInfo} · ${gpuText}`;
  730. heroSubtitle.textContent = `${latest.signals?.length || 0} live signals · ${events.length} recent events tracked`;
  731. healthBuffer.textContent = String(stats.buffer_samples ?? '-');
  732. healthDropped.textContent = String(stats.dropped ?? '-');
  733. healthResets.textContent = String(stats.resets ?? '-');
  734. healthAge.textContent = stats.last_sample_ago_ms >= 0 ? `${stats.last_sample_ago_ms} ms` : 'n/a';
  735. healthGpu.textContent = gpuInfo.error ? `${gpuInfo.active ? 'ON' : 'OFF'} · ${gpuInfo.error}` : (gpuInfo.active ? 'ON' : (gpuInfo.available ? 'Ready' : 'N/A'));
  736. healthFps.textContent = `${renderFps.toFixed(0)} fps`;
  737. }
  738. function renderBandNavigator() {
  739. if (!latest) return;
  740. const ctx = navCanvas.getContext('2d');
  741. const w = navCanvas.width;
  742. const h = navCanvas.height;
  743. ctx.clearRect(0, 0, w, h);
  744. const display = getProcessedSpectrum();
  745. if (!display) return;
  746. const minDb = -120;
  747. const maxDb = 0;
  748. ctx.fillStyle = '#071018';
  749. ctx.fillRect(0, 0, w, h);
  750. ctx.strokeStyle = 'rgba(102, 169, 255, 0.25)';
  751. ctx.lineWidth = 1;
  752. ctx.beginPath();
  753. for (let x = 0; x < w; x++) {
  754. const idx = Math.min(display.length - 1, Math.floor((x / w) * display.length));
  755. const v = display[idx];
  756. const y = h - ((v - minDb) / (maxDb - minDb)) * (h - 10) - 5;
  757. if (x === 0) ctx.moveTo(x, y);
  758. else ctx.lineTo(x, y);
  759. }
  760. ctx.stroke();
  761. const span = latest.sample_rate / zoom;
  762. const fullStart = latest.center_hz - latest.sample_rate / 2;
  763. const viewStart = latest.center_hz - span / 2 + pan * span;
  764. const viewEnd = latest.center_hz + span / 2 + pan * span;
  765. const x1 = ((viewStart - fullStart) / latest.sample_rate) * w;
  766. const x2 = ((viewEnd - fullStart) / latest.sample_rate) * w;
  767. ctx.fillStyle = 'rgba(102, 240, 209, 0.10)';
  768. ctx.strokeStyle = 'rgba(102, 240, 209, 0.85)';
  769. ctx.lineWidth = 2;
  770. ctx.fillRect(x1, 4, Math.max(2, x2 - x1), h - 8);
  771. ctx.strokeRect(x1, 4, Math.max(2, x2 - x1), h - 8);
  772. }
  773. function drawSpectrumGrid(ctx, w, h, startHz, endHz) {
  774. ctx.strokeStyle = 'rgba(86, 109, 148, 0.18)';
  775. ctx.lineWidth = 1;
  776. for (let i = 1; i < 6; i++) {
  777. const y = (h / 6) * i;
  778. ctx.beginPath();
  779. ctx.moveTo(0, y);
  780. ctx.lineTo(w, y);
  781. ctx.stroke();
  782. }
  783. for (let i = 1; i < 8; i++) {
  784. const x = (w / 8) * i;
  785. ctx.beginPath();
  786. ctx.moveTo(x, 0);
  787. ctx.lineTo(x, h);
  788. ctx.stroke();
  789. const hz = startHz + (i / 8) * (endHz - startHz);
  790. ctx.fillStyle = 'rgba(173, 192, 220, 0.72)';
  791. ctx.font = `${Math.max(11, Math.floor(h / 26))}px Inter, sans-serif`;
  792. ctx.fillText((hz / 1e6).toFixed(3), x + 4, h - 8);
  793. }
  794. }
  795. function drawCfarEdgeOverlay(ctx, w, h, startHz, endHz) {
  796. if (!latest) return;
  797. const mode = currentConfig?.detector?.cfar_mode || 'OFF';
  798. if (mode === 'OFF') return;
  799. if (currentConfig?.detector?.cfar_wrap_around) return;
  800. const guardHz = currentConfig.detector.cfar_guard_hz ?? 500;
  801. const trainHz = currentConfig.detector.cfar_train_hz ?? 5000;
  802. const fftSize = latest.fft_size || latest.spectrum_db?.length;
  803. if (!fftSize || fftSize <= 0) return;
  804. const binW = (latest.sample_rate || 2048000) / fftSize;
  805. const bins = Math.ceil(guardHz / binW) + Math.ceil(trainHz / binW);
  806. if (bins <= 0) return;
  807. const binHz = latest.sample_rate / fftSize;
  808. const edgeHz = bins * binHz;
  809. const bandStart = latest.center_hz - latest.sample_rate / 2;
  810. const bandEnd = latest.center_hz + latest.sample_rate / 2;
  811. const leftEdgeEnd = bandStart + edgeHz;
  812. const rightEdgeStart = bandEnd - edgeHz;
  813. ctx.fillStyle = 'rgba(255, 204, 102, 0.08)';
  814. ctx.strokeStyle = 'rgba(255, 204, 102, 0.18)';
  815. ctx.lineWidth = 1;
  816. const leftStart = Math.max(startHz, bandStart);
  817. const leftEnd = Math.min(endHz, leftEdgeEnd);
  818. if (leftEnd > leftStart) {
  819. const x1 = ((leftStart - startHz) / (endHz - startHz)) * w;
  820. const x2 = ((leftEnd - startHz) / (endHz - startHz)) * w;
  821. ctx.fillRect(x1, 0, Math.max(2, x2 - x1), h);
  822. ctx.strokeRect(x1, 0, Math.max(2, x2 - x1), h);
  823. }
  824. const rightStart = Math.max(startHz, rightEdgeStart);
  825. const rightEnd = Math.min(endHz, bandEnd);
  826. if (rightEnd > rightStart) {
  827. const x1 = ((rightStart - startHz) / (endHz - startHz)) * w;
  828. const x2 = ((rightEnd - startHz) / (endHz - startHz)) * w;
  829. ctx.fillRect(x1, 0, Math.max(2, x2 - x1), h);
  830. ctx.strokeRect(x1, 0, Math.max(2, x2 - x1), h);
  831. }
  832. }
  833. function renderSpectrum() {
  834. if (!latest) return;
  835. const ctx = spectrumCanvas.getContext('2d');
  836. const w = spectrumCanvas.width;
  837. const h = spectrumCanvas.height;
  838. ctx.clearRect(0, 0, w, h);
  839. const display = getProcessedSpectrum();
  840. if (!display) return;
  841. const n = display.length;
  842. const span = latest.sample_rate / zoom;
  843. const startHz = latest.center_hz - span / 2 + pan * span;
  844. const endHz = latest.center_hz + span / 2 + pan * span;
  845. spanInput.value = (span / 1e6).toFixed(3);
  846. drawSpectrumGrid(ctx, w, h, startHz, endHz);
  847. drawCfarEdgeOverlay(ctx, w, h, startHz, endHz);
  848. const minDb = -120;
  849. const maxDb = 0;
  850. const fill = ctx.createLinearGradient(0, 0, 0, h);
  851. fill.addColorStop(0, 'rgba(102, 240, 209, 0.20)');
  852. fill.addColorStop(1, 'rgba(102, 240, 209, 0.02)');
  853. ctx.beginPath();
  854. for (let x = 0; x < w; x++) {
  855. const f1 = startHz + (x / w) * (endHz - startHz);
  856. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  857. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  858. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  859. const v = maxInBinRange(display, b0, b1);
  860. const y = h - ((v - minDb) / (maxDb - minDb)) * (h - 18) - 6;
  861. if (x === 0) ctx.moveTo(x, y);
  862. else ctx.lineTo(x, y);
  863. }
  864. ctx.lineTo(w, h);
  865. ctx.lineTo(0, h);
  866. ctx.closePath();
  867. ctx.fillStyle = fill;
  868. ctx.fill();
  869. ctx.strokeStyle = '#66f0d1';
  870. ctx.lineWidth = 2;
  871. ctx.beginPath();
  872. liveSignalRects = [];
  873. for (let x = 0; x < w; x++) {
  874. const f1 = startHz + (x / w) * (endHz - startHz);
  875. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  876. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  877. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  878. const v = maxInBinRange(display, b0, b1);
  879. const y = h - ((v - minDb) / (maxDb - minDb)) * (h - 18) - 6;
  880. if (x === 0) ctx.moveTo(x, y);
  881. else ctx.lineTo(x, y);
  882. }
  883. ctx.stroke();
  884. drawThresholdOverlay(ctx, w, h, minDb, maxDb);
  885. if (Array.isArray(latest.signals)) {
  886. latest.signals.forEach((s, index) => {
  887. const left = s.center_hz - s.bw_hz / 2;
  888. const right = s.center_hz + s.bw_hz / 2;
  889. if (right < startHz || left > endHz) return;
  890. const x1 = ((left - startHz) / (endHz - startHz)) * w;
  891. const x2 = ((right - startHz) / (endHz - startHz)) * w;
  892. const boxW = Math.max(2, x2 - x1);
  893. const mod = s.class?.mod_type || '';
  894. const mc = modColor(mod);
  895. const rdsName = s.class?.pll?.rds_station || '';
  896. // Signal box with modulation-based color
  897. ctx.fillStyle = modColorStr(mod, 0.10);
  898. ctx.strokeStyle = modColorStr(mod, 0.75);
  899. ctx.lineWidth = 1.5;
  900. ctx.fillRect(x1, 10, boxW, h - 28);
  901. ctx.strokeRect(x1, 10, boxW, h - 28);
  902. if (matchesListenTarget(s)) {
  903. ctx.strokeStyle = 'rgba(255, 92, 92, 0.95)';
  904. ctx.lineWidth = 2.5;
  905. ctx.strokeRect(x1 - 1, 9, boxW + 2, h - 26);
  906. }
  907. // Label badges with dark background for readability
  908. const labelX = Math.max(4, x1 + 4);
  909. const baseY = 14;
  910. const freqStr = `${(s.center_hz / 1e6).toFixed(4)} MHz`;
  911. // Badge background
  912. const badgeH = rdsName ? 42 : (mod ? 30 : 16);
  913. const freqW = ctx.measureText ? 0 : 0; // will measure below
  914. ctx.font = '11px Inter, sans-serif';
  915. const textW = Math.max(ctx.measureText(freqStr).width, mod ? ctx.measureText(mod).width : 0, rdsName ? ctx.measureText(rdsName).width : 0) + 8;
  916. ctx.fillStyle = 'rgba(7, 16, 24, 0.82)';
  917. ctx.fillRect(labelX - 3, baseY, textW, badgeH);
  918. // Line 1: Frequency (teal)
  919. ctx.fillStyle = 'rgba(102, 240, 209, 0.95)';
  920. ctx.font = '11px Inter, sans-serif';
  921. ctx.fillText(freqStr, labelX, baseY + 11);
  922. // Line 2: Mod type (modulation color)
  923. if (mod) {
  924. ctx.fillStyle = mc.label;
  925. ctx.font = 'bold 10px Inter, sans-serif';
  926. ctx.fillText(mod, labelX, baseY + 23);
  927. }
  928. // Line 3: RDS station name (white bold)
  929. if (rdsName) {
  930. ctx.fillStyle = 'rgba(255, 255, 255, 0.95)';
  931. ctx.font = 'bold 12px Inter, sans-serif';
  932. ctx.fillText(rdsName, labelX, baseY + 36);
  933. }
  934. const debugMatch = (latest?.debug?.scores || []).find((d) => Math.abs((d.center_hz || 0) - (s.center_hz || 0)) < Math.max(500, s.bw_hz || 0));
  935. if (debugMatch?.scores && (!s.class || !s.class.scores)) {
  936. s.debug_scores = debugMatch.scores;
  937. }
  938. liveSignalRects.push({
  939. x: x1,
  940. y: 10,
  941. w: boxW,
  942. h: h - 28,
  943. signal: s,
  944. });
  945. });
  946. }
  947. }
  948. function renderWaterfall() {
  949. if (!latest) return;
  950. const ctx = waterfallCanvas.getContext('2d');
  951. const w = waterfallCanvas.width;
  952. const h = waterfallCanvas.height;
  953. const prev = ctx.getImageData(0, 0, w, h - 1);
  954. ctx.putImageData(prev, 0, 1);
  955. const display = getProcessedSpectrum();
  956. if (!display) return;
  957. const n = display.length;
  958. const span = latest.sample_rate / zoom;
  959. const startHz = latest.center_hz - span / 2 + pan * span;
  960. const endHz = latest.center_hz + span / 2 + pan * span;
  961. const minDb = -120;
  962. const maxDb = 0;
  963. const row = ctx.createImageData(w, 1);
  964. for (let x = 0; x < w; x++) {
  965. const f1 = startHz + (x / w) * (endHz - startHz);
  966. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  967. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  968. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  969. const v = maxInBinRange(display, b0, b1);
  970. const norm = Math.max(0, Math.min(1, (v - minDb) / (maxDb - minDb)));
  971. const [r, g, b] = colorMap(norm);
  972. row.data[x * 4] = r;
  973. row.data[x * 4 + 1] = g;
  974. row.data[x * 4 + 2] = b;
  975. row.data[x * 4 + 3] = 255;
  976. }
  977. ctx.putImageData(row, 0, 0);
  978. drawCfarEdgeOverlay(ctx, w, h, startHz, endHz);
  979. // Waterfall signal markers: thin vertical lines at signal center frequencies
  980. if (Array.isArray(latest.signals)) {
  981. latest.signals.forEach(s => {
  982. if (!s.center_hz) return;
  983. const xc = ((s.center_hz - startHz) / (endHz - startHz)) * w;
  984. if (xc < 0 || xc > w) return;
  985. const mod = s.class?.mod_type || '';
  986. ctx.strokeStyle = modColorStr(mod, 0.35);
  987. ctx.lineWidth = 1;
  988. ctx.setLineDash([2, 3]);
  989. ctx.beginPath();
  990. ctx.moveTo(xc, 0);
  991. ctx.lineTo(xc, h);
  992. ctx.stroke();
  993. ctx.setLineDash([]);
  994. });
  995. }
  996. }
  997. function renderOccupancy() {
  998. const ctx = occupancyCanvas.getContext('2d');
  999. const w = occupancyCanvas.width;
  1000. const h = occupancyCanvas.height;
  1001. ctx.clearRect(0, 0, w, h);
  1002. ctx.fillStyle = '#071018';
  1003. ctx.fillRect(0, 0, w, h);
  1004. if (!latest || events.length === 0) return;
  1005. const bins = new Array(Math.max(32, Math.min(160, Math.floor(w / 8)))).fill(0);
  1006. const bandStart = latest.center_hz - latest.sample_rate / 2;
  1007. const bandEnd = latest.center_hz + latest.sample_rate / 2;
  1008. const now = Date.now();
  1009. const windowStart = now - timelineWindowMs;
  1010. for (const ev of events) {
  1011. if (ev.end_ms < windowStart || ev.start_ms > now) continue;
  1012. const left = ev.center_hz - ev.bandwidth_hz / 2;
  1013. const right = ev.center_hz + ev.bandwidth_hz / 2;
  1014. const normL = Math.max(0, Math.min(1, (left - bandStart) / (bandEnd - bandStart)));
  1015. const normR = Math.max(0, Math.min(1, (right - bandStart) / (bandEnd - bandStart)));
  1016. let b0 = Math.floor(normL * bins.length);
  1017. let b1 = Math.floor(normR * bins.length);
  1018. if (b1 < b0) [b0, b1] = [b1, b0];
  1019. for (let i = Math.max(0, b0); i <= Math.min(bins.length - 1, b1); i++) {
  1020. bins[i] += Math.max(0.3, (ev.snr_db || 0) / 12 + 1);
  1021. }
  1022. }
  1023. const maxBin = Math.max(1, ...bins);
  1024. bins.forEach((v, i) => {
  1025. const norm = v / maxBin;
  1026. const [r, g, b] = colorMap(norm);
  1027. ctx.fillStyle = `rgb(${r}, ${g}, ${b})`;
  1028. const x = (i / bins.length) * w;
  1029. const bw = Math.ceil(w / bins.length) + 1;
  1030. ctx.fillRect(x, 0, bw, h);
  1031. });
  1032. }
  1033. function renderTimeline() {
  1034. const ctx = timelineCanvas.getContext('2d');
  1035. const w = timelineCanvas.width;
  1036. const h = timelineCanvas.height;
  1037. ctx.clearRect(0, 0, w, h);
  1038. ctx.fillStyle = '#071018';
  1039. ctx.fillRect(0, 0, w, h);
  1040. if (events.length === 0) {
  1041. timelineRangeEl.textContent = 'No events yet';
  1042. return;
  1043. }
  1044. const endMs = Date.now();
  1045. const startMs = endMs - timelineWindowMs;
  1046. timelineRangeEl.textContent = `${new Date(startMs).toLocaleTimeString()} - ${new Date(endMs).toLocaleTimeString()}`;
  1047. let minHz = Infinity;
  1048. let maxHz = -Infinity;
  1049. if (latest) {
  1050. minHz = latest.center_hz - latest.sample_rate / 2;
  1051. maxHz = latest.center_hz + latest.sample_rate / 2;
  1052. } else {
  1053. for (const ev of events) {
  1054. minHz = Math.min(minHz, ev.center_hz - ev.bandwidth_hz / 2);
  1055. maxHz = Math.max(maxHz, ev.center_hz + ev.bandwidth_hz / 2);
  1056. }
  1057. }
  1058. if (!isFinite(minHz) || !isFinite(maxHz) || minHz === maxHz) {
  1059. minHz = 0;
  1060. maxHz = 1;
  1061. }
  1062. ctx.strokeStyle = 'rgba(86, 109, 148, 0.18)';
  1063. ctx.lineWidth = 1;
  1064. for (let i = 1; i < 6; i++) {
  1065. const y = (h / 6) * i;
  1066. ctx.beginPath();
  1067. ctx.moveTo(0, y);
  1068. ctx.lineTo(w, y);
  1069. ctx.stroke();
  1070. }
  1071. for (let i = 1; i < 8; i++) {
  1072. const x = (w / 8) * i;
  1073. ctx.beginPath();
  1074. ctx.moveTo(x, 0);
  1075. ctx.lineTo(x, h);
  1076. ctx.stroke();
  1077. }
  1078. timelineRects = [];
  1079. for (const ev of events) {
  1080. if (ev.end_ms < startMs || ev.start_ms > endMs) continue;
  1081. const x1 = ((Math.max(ev.start_ms, startMs) - startMs) / (endMs - startMs)) * w;
  1082. const x2 = ((Math.min(ev.end_ms, endMs) - startMs) / (endMs - startMs)) * w;
  1083. const topHz = ev.center_hz + ev.bandwidth_hz / 2;
  1084. const bottomHz = ev.center_hz - ev.bandwidth_hz / 2;
  1085. const y1 = ((maxHz - topHz) / (maxHz - minHz)) * h;
  1086. const y2 = ((maxHz - bottomHz) / (maxHz - minHz)) * h;
  1087. const rect = { x: x1, y: y1, w: Math.max(2, x2 - x1), h: Math.max(3, y2 - y1), id: ev.id };
  1088. timelineRects.push(rect);
  1089. ctx.fillStyle = snrColor(ev.snr_db || 0).replace('rgb', 'rgba').replace(')', ', 0.85)');
  1090. ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
  1091. }
  1092. if (selectedEventId) {
  1093. const hit = timelineRects.find(r => r.id === selectedEventId);
  1094. if (hit) {
  1095. ctx.strokeStyle = '#ffffff';
  1096. ctx.lineWidth = 2;
  1097. ctx.strokeRect(hit.x - 1, hit.y - 1, hit.w + 2, hit.h + 2);
  1098. }
  1099. }
  1100. }
  1101. function renderDetailSpectrogram() {
  1102. const ev = eventsById.get(selectedEventId);
  1103. const ctx = detailSpectrogram.getContext('2d');
  1104. const w = detailSpectrogram.width;
  1105. const h = detailSpectrogram.height;
  1106. ctx.clearRect(0, 0, w, h);
  1107. ctx.fillStyle = '#071018';
  1108. ctx.fillRect(0, 0, w, h);
  1109. if (!latest || !ev) return;
  1110. const display = getProcessedSpectrum();
  1111. if (!display) return;
  1112. const n = display.length;
  1113. const localSpan = Math.min(latest.sample_rate, Math.max(ev.bandwidth_hz * 4, latest.sample_rate / 10));
  1114. const startHz = ev.center_hz - localSpan / 2;
  1115. const endHz = ev.center_hz + localSpan / 2;
  1116. const minDb = -120;
  1117. const maxDb = 0;
  1118. const row = ctx.createImageData(w, 1);
  1119. for (let x = 0; x < w; x++) {
  1120. const f1 = startHz + (x / w) * (endHz - startHz);
  1121. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  1122. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  1123. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  1124. const v = maxInBinRange(display, b0, b1);
  1125. const norm = Math.max(0, Math.min(1, (v - minDb) / (maxDb - minDb)));
  1126. const [r, g, b] = colorMap(norm);
  1127. row.data[x * 4] = r;
  1128. row.data[x * 4 + 1] = g;
  1129. row.data[x * 4 + 2] = b;
  1130. row.data[x * 4 + 3] = 255;
  1131. }
  1132. for (let y = 0; y < h; y++) ctx.putImageData(row, 0, y);
  1133. const centerX = w / 2;
  1134. ctx.strokeStyle = 'rgba(255,255,255,0.65)';
  1135. ctx.lineWidth = 1;
  1136. ctx.beginPath();
  1137. ctx.moveTo(centerX, 0);
  1138. ctx.lineTo(centerX, h);
  1139. ctx.stroke();
  1140. }
  1141. let _lastEventListKey = '';
  1142. function _createSignalItem(s) {
  1143. const btn = document.createElement('button');
  1144. btn.className = 'list-item signal-item';
  1145. btn.type = 'button';
  1146. btn.dataset.center = s.center_hz;
  1147. btn.dataset.bw = s.bw_hz || 0;
  1148. btn.dataset.class = s.class?.mod_type || '';
  1149. btn.dataset.id = s.id || 0;
  1150. const mod = s.class?.mod_type || '';
  1151. const mc = modColor(mod);
  1152. const rds = s.class?.pll?.rds_station || '';
  1153. btn.innerHTML = `<div class="item-top"><span class="item-title" data-field="freq">${fmtMHz(s.center_hz, 6)}</span><span class="item-badge" data-field="snr" style="color:${snrColor(s.snr_db || 0)}">${(s.snr_db || 0).toFixed(1)} dB</span></div><div class="item-bottom"><span class="item-meta" data-field="mod" style="color:${mc.label};font-weight:600">${mod || 'carrier'}</span><span class="item-meta" data-field="bw" style="opacity:0.6">BW ${fmtKHz(s.bw_hz || 0)}</span>${rds ? `<span class="item-meta" data-field="rds" style="color:#fff;font-weight:700">${rds}</span>` : ''}</div>`;
  1154. btn.style.borderLeftColor = mc.label;
  1155. btn.style.borderLeftWidth = '3px';
  1156. btn.style.borderLeftStyle = 'solid';
  1157. if (matchesListenTarget(s)) btn.classList.add('listening');
  1158. return btn;
  1159. }
  1160. function _patchSignalItem(el, s) {
  1161. const freqEl = el.querySelector('[data-field="freq"]');
  1162. const snrEl = el.querySelector('[data-field="snr"]');
  1163. const bwEl = el.querySelector('[data-field="bw"]');
  1164. const modEl = el.querySelector('[data-field="mod"]');
  1165. const rdsEl = el.querySelector('[data-field="rds"]');
  1166. const mod = s.class?.mod_type || '';
  1167. const mc = modColor(mod);
  1168. const rds = s.class?.pll?.rds_station || '';
  1169. if (freqEl) freqEl.textContent = fmtMHz(s.center_hz, 6);
  1170. if (snrEl) { snrEl.textContent = `${(s.snr_db || 0).toFixed(1)} dB`; snrEl.style.color = snrColor(s.snr_db || 0); }
  1171. if (bwEl) bwEl.textContent = `BW ${fmtKHz(s.bw_hz || 0)}`;
  1172. if (modEl) { modEl.textContent = mod || 'carrier'; modEl.style.color = mc.label; }
  1173. if (rdsEl) { rdsEl.textContent = rds; } else if (rds && !rdsEl) {
  1174. const span = document.createElement('span');
  1175. span.className = 'item-meta';
  1176. span.dataset.field = 'rds';
  1177. span.style.color = '#fff';
  1178. span.style.fontWeight = '700';
  1179. span.textContent = rds;
  1180. el.querySelector('.item-bottom')?.appendChild(span);
  1181. }
  1182. el.dataset.center = s.center_hz;
  1183. el.dataset.bw = s.bw_hz || 0;
  1184. el.dataset.class = mod;
  1185. el.style.borderLeftColor = mc.label;
  1186. el.classList.toggle('listening', matchesListenTarget(s));
  1187. }
  1188. function renderLists() {
  1189. const signals = Array.isArray(latest?.signals) ? [...latest.signals] : [];
  1190. signals.sort((a, b) => (b.snr_db || 0) - (a.snr_db || 0));
  1191. signalCountBadge.textContent = `${signals.length} live`;
  1192. metricSignals.textContent = String(signals.length);
  1193. const displaySigs = signals.slice(0, 24);
  1194. const wantIds = new Set(displaySigs.map(s => String(s.id || 0)));
  1195. // Remove empty-state placeholder if signals exist
  1196. const emptyEl = signalList.querySelector('.empty-state');
  1197. if (emptyEl && displaySigs.length > 0) emptyEl.remove();
  1198. // Remove DOM items whose signal ID is no longer present
  1199. signalList.querySelectorAll('.signal-item').forEach(el => {
  1200. if (!wantIds.has(el.dataset.id)) el.remove();
  1201. });
  1202. if (displaySigs.length === 0) {
  1203. if (!signalList.querySelector('.empty-state')) {
  1204. signalList.innerHTML = '<div class="empty-state">No live signals yet.</div>';
  1205. }
  1206. } else {
  1207. // Build map of existing DOM items
  1208. const domById = new Map();
  1209. signalList.querySelectorAll('.signal-item').forEach(el => domById.set(el.dataset.id, el));
  1210. displaySigs.forEach(s => {
  1211. const id = String(s.id || 0);
  1212. const existing = domById.get(id);
  1213. if (existing) {
  1214. _patchSignalItem(existing, s);
  1215. } else {
  1216. const el = _createSignalItem(s);
  1217. // Auto-select if it matches the user's last selection
  1218. if (window._selectedSignal && Math.abs(s.center_hz - window._selectedSignal.freq) < 50000) {
  1219. el.classList.add('active');
  1220. }
  1221. signalList.appendChild(el);
  1222. }
  1223. });
  1224. }
  1225. const recent = [...events].sort((a, b) => b.end_ms - a.end_ms);
  1226. eventCountBadge.textContent = `${recent.length} stored`;
  1227. const evtKey = `${recent.length}:${selectedEventId}:${recent.slice(0, 5).map(e => e.id).join(',')}`;
  1228. if (evtKey !== _lastEventListKey) {
  1229. _lastEventListKey = evtKey;
  1230. if (recent.length === 0) {
  1231. eventList.innerHTML = '<div class="empty-state">No events yet.</div>';
  1232. } else {
  1233. eventList.innerHTML = recent.slice(0, 40).map((ev) => `
  1234. <button class="list-item event-item ${selectedEventId === ev.id ? 'active' : ''}" type="button" data-event-id="${ev.id}">
  1235. <div class="item-top">
  1236. <span class="item-title">${fmtMHz(ev.center_hz, 6)}</span>
  1237. <span class="item-badge" style="color:${snrColor(ev.snr_db || 0)}">${(ev.snr_db || 0).toFixed(1)} dB</span>
  1238. </div>
  1239. <div class="item-bottom">
  1240. <span class="item-meta">${fmtKHz(ev.bandwidth_hz || 0)} · ${fmtMs(ev.duration_ms || 0)}</span>
  1241. <span class="item-meta">${new Date(ev.end_ms).toLocaleTimeString()}</span>
  1242. </div>
  1243. </button>
  1244. `).join('');
  1245. }
  1246. }
  1247. if (recordingList && recordingCountBadge) {
  1248. recordingCountBadge.textContent = `${recordings.length}`;
  1249. if (recordings.length === 0) {
  1250. recordingList.innerHTML = '<div class="empty-state">No recordings yet.</div>';
  1251. } else {
  1252. recordingList.innerHTML = recordings.slice(0, 50).map((rec) => `
  1253. <button class="list-item recording-item" type="button" data-id="${rec.id}">
  1254. <div class="item-top">
  1255. <span class="item-title">${new Date(rec.start).toLocaleString()}</span>
  1256. <span class="item-badge">${fmtMHz(rec.center_hz || 0, 6)}</span>
  1257. </div>
  1258. <div class="item-bottom">
  1259. <span class="item-meta">${rec.id}</span>
  1260. <span class="item-meta">recording</span>
  1261. </div>
  1262. </button>
  1263. `).join('');
  1264. }
  1265. }
  1266. }
  1267. function normalizeEvent(ev) {
  1268. const startMs = new Date(ev.start).getTime();
  1269. const endMs = new Date(ev.end).getTime();
  1270. return {
  1271. ...ev,
  1272. start_ms: startMs,
  1273. end_ms: endMs,
  1274. duration_ms: Math.max(0, endMs - startMs),
  1275. };
  1276. }
  1277. function upsertEvents(list, replace = false) {
  1278. if (replace) {
  1279. events.length = 0;
  1280. eventsById.clear();
  1281. }
  1282. for (const raw of list) {
  1283. if (!raw || !raw.id || eventsById.has(raw.id)) continue;
  1284. const ev = normalizeEvent(raw);
  1285. eventsById.set(ev.id, ev);
  1286. events.push(ev);
  1287. }
  1288. events.sort((a, b) => a.end_ms - b.end_ms);
  1289. const maxEvents = 1500;
  1290. if (events.length > maxEvents) {
  1291. const drop = events.length - maxEvents;
  1292. for (let i = 0; i < drop; i++) eventsById.delete(events[i].id);
  1293. events.splice(0, drop);
  1294. }
  1295. if (events.length > 0) lastEventEndMs = events[events.length - 1].end_ms;
  1296. renderLists();
  1297. }
  1298. async function fetchEvents(initial) {
  1299. if (eventsFetchInFlight || timelineFrozen) return;
  1300. eventsFetchInFlight = true;
  1301. try {
  1302. let url = '/api/events?limit=1000';
  1303. if (!initial && lastEventEndMs > 0) url = `/api/events?since=${lastEventEndMs - 1}`;
  1304. const res = await fetch(url);
  1305. if (!res.ok) return;
  1306. const data = await res.json();
  1307. if (Array.isArray(data)) upsertEvents(data, initial);
  1308. } finally {
  1309. eventsFetchInFlight = false;
  1310. }
  1311. }
  1312. async function fetchRecordings() {
  1313. if (recordingsFetchInFlight || !recordingList) return;
  1314. recordingsFetchInFlight = true;
  1315. try {
  1316. const res = await fetch('/api/recordings');
  1317. if (!res.ok) return;
  1318. const data = await res.json();
  1319. if (Array.isArray(data)) {
  1320. recordings = data;
  1321. renderLists();
  1322. }
  1323. } finally {
  1324. recordingsFetchInFlight = false;
  1325. }
  1326. }
  1327. function openDrawer(ev) {
  1328. if (!ev) return;
  1329. selectedEventId = ev.id;
  1330. detailSubtitle.textContent = `Event ${ev.id}`;
  1331. detailCenterEl.textContent = fmtMHz(ev.center_hz, 6);
  1332. detailBwEl.textContent = fmtKHz(ev.bandwidth_hz || 0);
  1333. detailStartEl.textContent = new Date(ev.start_ms).toLocaleString();
  1334. detailEndEl.textContent = new Date(ev.end_ms).toLocaleString();
  1335. detailSnrEl.textContent = `${(ev.snr_db || 0).toFixed(1)} dB`;
  1336. detailDurEl.textContent = fmtMs(ev.duration_ms || 0);
  1337. detailClassEl.textContent = ev.class?.mod_type || '-';
  1338. if (classifierScoresEl) {
  1339. const scores = ev.class?.scores;
  1340. if (scores && typeof scores === 'object') {
  1341. const rows = Object.entries(scores)
  1342. .sort((a, b) => b[1] - a[1])
  1343. .slice(0, 6)
  1344. .map(([k, v]) => `${k}:${v.toFixed(2)}`)
  1345. .join(' · ');
  1346. classifierScoresEl.textContent = rows ? `Classifier scores: ${rows}` : 'Classifier scores: -';
  1347. renderScoreBars(scores);
  1348. } else {
  1349. const liveScores = (latest?.debug?.scores || []).find((s) => Math.abs((s.center_hz || 0) - (ev.center_hz || 0)) < Math.max(500, (ev.bandwidth_hz || 0)));
  1350. if (liveScores?.scores) {
  1351. const rows = Object.entries(liveScores.scores)
  1352. .sort((a, b) => b[1] - a[1])
  1353. .slice(0, 6)
  1354. .map(([k, v]) => `${k}:${Number(v).toFixed(2)}`)
  1355. .join(' · ');
  1356. classifierScoresEl.textContent = rows ? `Classifier scores: ${rows}` : 'Classifier scores: -';
  1357. renderScoreBars(liveScores.scores);
  1358. } else {
  1359. classifierScoresEl.textContent = 'Classifier scores: -';
  1360. renderScoreBars(null);
  1361. }
  1362. }
  1363. }
  1364. if (recordingMetaEl) {
  1365. recordingMetaEl.textContent = 'Recording: -';
  1366. }
  1367. if (recordingMetaLink) {
  1368. recordingMetaLink.href = '#';
  1369. recordingIQLink.href = '#';
  1370. recordingAudioLink.href = '#';
  1371. }
  1372. drawerEl.classList.add('open');
  1373. drawerEl.setAttribute('aria-hidden', 'false');
  1374. renderDetailSpectrogram();
  1375. renderLists();
  1376. }
  1377. function closeDrawer() {
  1378. drawerEl.classList.remove('open');
  1379. drawerEl.setAttribute('aria-hidden', 'true');
  1380. selectedEventId = null;
  1381. renderLists();
  1382. }
  1383. function fitView() {
  1384. zoom = 1;
  1385. pan = 0;
  1386. followLive = true;
  1387. }
  1388. function tuneToFrequency(centerHz) {
  1389. if (!Number.isFinite(centerHz)) return;
  1390. followLive = true;
  1391. centerInput.value = (centerHz / 1e6).toFixed(6);
  1392. queueConfigUpdate({ center_hz: centerHz });
  1393. }
  1394. function connect() {
  1395. clearTimeout(wsReconnectTimer);
  1396. const proto = location.protocol === 'https:' ? 'wss' : 'ws';
  1397. // Remote optimization: detect non-localhost and opt into binary + decimation
  1398. const hn = location.hostname;
  1399. const isLocal = ['localhost', '127.0.0.1', '::1'].includes(hn)
  1400. || hn.startsWith('192.168.')
  1401. || hn.startsWith('10.')
  1402. || /^172\.(1[6-9]|2\d|3[01])\./.test(hn)
  1403. || hn.endsWith('.local')
  1404. || hn.endsWith('.lan');
  1405. const params = new URLSearchParams(location.search);
  1406. const wantBinary = params.get('binary') === '1' || !isLocal;
  1407. const bins = parseInt(params.get('bins') || (isLocal ? '0' : '2048'), 10);
  1408. const fps = parseInt(params.get('fps') || (isLocal ? '0' : '10'), 10);
  1409. let wsUrl = `${proto}://${location.host}/ws`;
  1410. if (wantBinary || bins > 0 || fps > 0) {
  1411. const qp = [];
  1412. if (wantBinary) qp.push('binary=1');
  1413. if (bins > 0) qp.push(`bins=${bins}`);
  1414. if (fps > 0) qp.push(`fps=${fps}`);
  1415. wsUrl += '?' + qp.join('&');
  1416. }
  1417. const ws = new WebSocket(wsUrl);
  1418. ws.binaryType = 'arraybuffer';
  1419. setWsBadge('Connecting', 'neutral');
  1420. ws.onopen = () => setWsBadge('Live', 'ok');
  1421. ws.onmessage = (ev) => {
  1422. if (ev.data instanceof ArrayBuffer) {
  1423. try {
  1424. const decoded = decodeBinaryFrame(ev.data);
  1425. if (decoded) latest = decoded;
  1426. } catch (e) {
  1427. console.warn('binary frame decode error:', e);
  1428. return;
  1429. }
  1430. } else {
  1431. latest = JSON.parse(ev.data);
  1432. }
  1433. markSpectrumDirty();
  1434. if (followLive) pan = 0;
  1435. updateHeroMetrics();
  1436. renderLists();
  1437. };
  1438. ws.onclose = () => {
  1439. setWsBadge('Retrying', 'bad');
  1440. wsReconnectTimer = setTimeout(connect, 1000);
  1441. };
  1442. ws.onerror = () => ws.close();
  1443. }
  1444. // Decode binary spectrum frame v4 (hybrid: binary spectrum + JSON signals)
  1445. function decodeBinaryFrame(buf) {
  1446. const view = new DataView(buf);
  1447. if (buf.byteLength < 32) return null;
  1448. // Header: 32 bytes
  1449. const magic0 = view.getUint8(0);
  1450. const magic1 = view.getUint8(1);
  1451. if (magic0 !== 0x53 || magic1 !== 0x50) return null; // not "SP"
  1452. const version = view.getUint16(2, true);
  1453. const ts = Number(view.getBigInt64(4, true));
  1454. const centerHz = view.getFloat64(12, true);
  1455. const binCount = view.getUint32(20, true);
  1456. const sampleRateHz = view.getUint32(24, true);
  1457. const jsonOffset = view.getUint32(28, true);
  1458. if (buf.byteLength < 32 + binCount * 2) return null;
  1459. // Spectrum: binCount × int16 at offset 32
  1460. const spectrum = new Float64Array(binCount);
  1461. let off = 32;
  1462. for (let i = 0; i < binCount; i++) {
  1463. spectrum[i] = view.getInt16(off, true) / 100;
  1464. off += 2;
  1465. }
  1466. // JSON signals + debug after the spectrum data
  1467. let signals = [];
  1468. let debug = null;
  1469. if (jsonOffset > 0 && jsonOffset < buf.byteLength) {
  1470. try {
  1471. const jsonBytes = new Uint8Array(buf, jsonOffset);
  1472. const jsonStr = new TextDecoder().decode(jsonBytes);
  1473. const parsed = JSON.parse(jsonStr);
  1474. signals = parsed.signals || [];
  1475. debug = parsed.debug || null;
  1476. } catch (e) {
  1477. // JSON parse failed — continue with empty signals
  1478. }
  1479. }
  1480. return {
  1481. ts: ts,
  1482. center_hz: centerHz,
  1483. sample_rate: sampleRateHz,
  1484. fft_size: binCount,
  1485. spectrum_db: spectrum,
  1486. signals: signals,
  1487. debug: debug
  1488. };
  1489. }
  1490. function renderLoop() {
  1491. renderFrames += 1;
  1492. const now = performance.now();
  1493. if (now - lastFpsTs >= 1000) {
  1494. renderFps = (renderFrames * 1000) / (now - lastFpsTs);
  1495. renderFrames = 0;
  1496. lastFpsTs = now;
  1497. }
  1498. if (latest) {
  1499. renderBandNavigator();
  1500. renderSpectrum();
  1501. renderWaterfall();
  1502. renderOccupancy();
  1503. renderTimeline();
  1504. if (drawerEl.classList.contains('open')) renderDetailSpectrogram();
  1505. }
  1506. updateHeroMetrics();
  1507. requestAnimationFrame(renderLoop);
  1508. }
  1509. function handleSpectrumClick(ev) {
  1510. const rect = spectrumCanvas.getBoundingClientRect();
  1511. const x = (ev.clientX - rect.left) * (spectrumCanvas.width / rect.width);
  1512. const y = (ev.clientY - rect.top) * (spectrumCanvas.height / rect.height);
  1513. for (let i = liveSignalRects.length - 1; i >= 0; i--) {
  1514. const r = liveSignalRects[i];
  1515. if (x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h) {
  1516. const sig = r.signal;
  1517. const freq = sig.center_hz;
  1518. const bw = sig.bw_hz || 12000;
  1519. const mode = sig.class?.mod_type || '';
  1520. startLiveListen(freq, bw, mode);
  1521. window._selectedSignal = { freq, bw, mode };
  1522. // Update selected signal in list
  1523. signalList.querySelectorAll('.signal-item').forEach(el => {
  1524. const elFreq = parseFloat(el.dataset.center || '0');
  1525. el.classList.toggle('active', Math.abs(elFreq - freq) < Math.max(500, bw * 0.5));
  1526. });
  1527. return;
  1528. }
  1529. }
  1530. if (!latest) return;
  1531. const span = latest.sample_rate / zoom;
  1532. const startHz = latest.center_hz - span / 2 + pan * span;
  1533. const clickedHz = startHz + (x / spectrumCanvas.width) * span;
  1534. tuneToFrequency(clickedHz);
  1535. }
  1536. function handleNavPosition(ev) {
  1537. if (!latest) return;
  1538. const rect = navCanvas.getBoundingClientRect();
  1539. const x = Math.max(0, Math.min(rect.width, ev.clientX - rect.left));
  1540. const norm = x / rect.width;
  1541. const fullStart = latest.center_hz - latest.sample_rate / 2;
  1542. const newViewCenter = fullStart + norm * latest.sample_rate;
  1543. const span = latest.sample_rate / zoom;
  1544. const desiredPan = (newViewCenter - latest.center_hz) / span;
  1545. pan = Math.max(-0.5, Math.min(0.5, desiredPan));
  1546. followLive = false;
  1547. }
  1548. function exportSelectedEvent() {
  1549. const ev = eventsById.get(selectedEventId);
  1550. if (!ev) return;
  1551. const blob = new Blob([JSON.stringify(ev, null, 2)], { type: 'application/json' });
  1552. const a = document.createElement('a');
  1553. a.href = URL.createObjectURL(blob);
  1554. a.download = `event-${ev.id}.json`;
  1555. a.click();
  1556. URL.revokeObjectURL(a.href);
  1557. }
  1558. spectrumCanvas.addEventListener('wheel', (ev) => {
  1559. ev.preventDefault();
  1560. const direction = Math.sign(ev.deltaY);
  1561. zoom = Math.max(0.25, Math.min(24, zoom * (direction > 0 ? 1.12 : 0.89)));
  1562. followLive = false;
  1563. });
  1564. spectrumCanvas.addEventListener('mousedown', (ev) => {
  1565. isDraggingSpectrum = true;
  1566. dragStartX = ev.clientX;
  1567. dragStartPan = pan;
  1568. });
  1569. window.addEventListener('mouseup', () => {
  1570. isDraggingSpectrum = false;
  1571. navDrag = false;
  1572. });
  1573. spectrumCanvas.addEventListener('mouseleave', hideSignalPopover);
  1574. window.addEventListener('mousemove', (ev) => {
  1575. const rect = spectrumCanvas.getBoundingClientRect();
  1576. const x = (ev.clientX - rect.left) * (spectrumCanvas.width / rect.width);
  1577. const y = (ev.clientY - rect.top) * (spectrumCanvas.height / rect.height);
  1578. let hoverHit = null;
  1579. for (let i = liveSignalRects.length - 1; i >= 0; i--) {
  1580. const r = liveSignalRects[i];
  1581. if (x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h) {
  1582. hoverHit = r;
  1583. break;
  1584. }
  1585. }
  1586. if (hoverHit) {
  1587. hoveredSignal = hoverHit.signal;
  1588. renderSignalPopover(hoverHit, hoverHit.signal);
  1589. } else {
  1590. hideSignalPopover();
  1591. }
  1592. if (isDraggingSpectrum) {
  1593. const dx = ev.clientX - dragStartX;
  1594. pan = Math.max(-0.5, Math.min(0.5, dragStartPan - dx / spectrumCanvas.clientWidth));
  1595. followLive = false;
  1596. }
  1597. if (navDrag) handleNavPosition(ev);
  1598. });
  1599. spectrumCanvas.addEventListener('dblclick', fitView);
  1600. spectrumCanvas.addEventListener('click', handleSpectrumClick);
  1601. navCanvas.addEventListener('mousedown', (ev) => {
  1602. navDrag = true;
  1603. handleNavPosition(ev);
  1604. });
  1605. navCanvas.addEventListener('click', handleNavPosition);
  1606. centerInput.addEventListener('change', () => {
  1607. const mhz = parseFloat(centerInput.value);
  1608. if (Number.isFinite(mhz)) tuneToFrequency(fromMHz(mhz));
  1609. });
  1610. spanInput.addEventListener('change', () => {
  1611. const mhz = parseFloat(spanInput.value);
  1612. if (!Number.isFinite(mhz) || mhz <= 0) return;
  1613. const baseRate = currentConfig?.sample_rate || latest?.sample_rate;
  1614. if (!baseRate) return;
  1615. zoom = Math.max(0.25, Math.min(24, baseRate / fromMHz(mhz)));
  1616. followLive = false;
  1617. });
  1618. sampleRateSelect.addEventListener('change', () => {
  1619. const mhz = parseFloat(sampleRateSelect.value);
  1620. if (Number.isFinite(mhz)) queueConfigUpdate({ sample_rate: Math.round(fromMHz(mhz)) });
  1621. });
  1622. bwSelect.addEventListener('change', () => {
  1623. const bw = parseInt(bwSelect.value, 10);
  1624. if (Number.isFinite(bw)) queueConfigUpdate({ tuner_bw_khz: bw });
  1625. });
  1626. fftSelect.addEventListener('change', () => {
  1627. const size = parseInt(fftSelect.value, 10);
  1628. if (Number.isFinite(size)) queueConfigUpdate({ fft_size: size });
  1629. });
  1630. gainRange.addEventListener('input', () => {
  1631. gainInput.value = gainRange.value;
  1632. const uiVal = parseFloat(gainRange.value);
  1633. if (Number.isFinite(uiVal)) queueConfigUpdate({ gain_db: Math.max(0, Math.min(GAIN_MAX, GAIN_MAX - uiVal)) });
  1634. });
  1635. gainInput.addEventListener('change', () => {
  1636. const uiVal = parseFloat(gainInput.value);
  1637. if (Number.isFinite(uiVal)) {
  1638. gainRange.value = uiVal;
  1639. queueConfigUpdate({ gain_db: Math.max(0, Math.min(GAIN_MAX, GAIN_MAX - uiVal)) });
  1640. }
  1641. });
  1642. thresholdRange.addEventListener('input', () => {
  1643. thresholdInput.value = thresholdRange.value;
  1644. queueConfigUpdate({ detector: { threshold_db: parseFloat(thresholdRange.value) } });
  1645. });
  1646. thresholdInput.addEventListener('change', () => {
  1647. const v = parseFloat(thresholdInput.value);
  1648. if (Number.isFinite(v)) {
  1649. thresholdRange.value = v;
  1650. queueConfigUpdate({ detector: { threshold_db: v } });
  1651. }
  1652. });
  1653. if (cfarModeSelect) cfarModeSelect.addEventListener('change', () => {
  1654. queueConfigUpdate({ detector: { cfar_mode: cfarModeSelect.value } });
  1655. const rankRow = cfarRankInput?.closest('.field');
  1656. if (rankRow) rankRow.style.display = (cfarModeSelect.value === 'OS') ? '' : 'none';
  1657. });
  1658. if (cfarWrapToggle) cfarWrapToggle.addEventListener('change', () => {
  1659. queueConfigUpdate({ detector: { cfar_wrap_around: cfarWrapToggle.checked } });
  1660. });
  1661. if (cfarGuardHzInput) cfarGuardHzInput.addEventListener('change', () => {
  1662. const v = parseFloat(cfarGuardHzInput.value);
  1663. if (Number.isFinite(v) && v >= 0) queueConfigUpdate({ detector: { cfar_guard_hz: v } });
  1664. });
  1665. if (cfarTrainHzInput) cfarTrainHzInput.addEventListener('change', () => {
  1666. const v = parseFloat(cfarTrainHzInput.value);
  1667. if (Number.isFinite(v) && v > 0) queueConfigUpdate({ detector: { cfar_train_hz: v } });
  1668. });
  1669. if (cfarRankInput) cfarRankInput.addEventListener('change', () => {
  1670. const v = parseInt(cfarRankInput.value, 10);
  1671. if (Number.isFinite(v)) queueConfigUpdate({ detector: { cfar_rank: v } });
  1672. });
  1673. if (cfarScaleInput) cfarScaleInput.addEventListener('change', () => {
  1674. const v = parseFloat(cfarScaleInput.value);
  1675. if (Number.isFinite(v)) queueConfigUpdate({ detector: { cfar_scale_db: v } });
  1676. });
  1677. if (minDurationInput) minDurationInput.addEventListener('change', () => {
  1678. const v = parseInt(minDurationInput.value, 10);
  1679. if (Number.isFinite(v)) queueConfigUpdate({ detector: { min_duration_ms: v } });
  1680. });
  1681. if (holdInput) holdInput.addEventListener('change', () => {
  1682. const v = parseInt(holdInput.value, 10);
  1683. if (Number.isFinite(v)) queueConfigUpdate({ detector: { hold_ms: v } });
  1684. });
  1685. if (emaAlphaInput) emaAlphaInput.addEventListener('change', () => {
  1686. const v = parseFloat(emaAlphaInput.value);
  1687. if (Number.isFinite(v)) queueConfigUpdate({ detector: { ema_alpha: v } });
  1688. });
  1689. if (hysteresisInput) hysteresisInput.addEventListener('change', () => {
  1690. const v = parseFloat(hysteresisInput.value);
  1691. if (Number.isFinite(v)) queueConfigUpdate({ detector: { hysteresis_db: v } });
  1692. });
  1693. if (stableFramesInput) stableFramesInput.addEventListener('change', () => {
  1694. const v = parseInt(stableFramesInput.value, 10);
  1695. if (Number.isFinite(v)) queueConfigUpdate({ detector: { min_stable_frames: v } });
  1696. });
  1697. if (gapToleranceInput) gapToleranceInput.addEventListener('change', () => {
  1698. const v = parseInt(gapToleranceInput.value, 10);
  1699. if (Number.isFinite(v)) queueConfigUpdate({ detector: { gap_tolerance_ms: v } });
  1700. });
  1701. if (classifierModeSelect) classifierModeSelect.addEventListener('change', () => {
  1702. queueConfigUpdate({ classifier_mode: classifierModeSelect.value });
  1703. });
  1704. if (edgeMarginInput) edgeMarginInput.addEventListener('change', () => {
  1705. const v = parseFloat(edgeMarginInput.value);
  1706. if (Number.isFinite(v) && v >= 0) queueConfigUpdate({ detector: { edge_margin_db: v } });
  1707. });
  1708. if (mergeGapInput) mergeGapInput.addEventListener('change', () => {
  1709. const v = parseFloat(mergeGapInput.value);
  1710. if (Number.isFinite(v)) queueConfigUpdate({ detector: { merge_gap_hz: v } });
  1711. });
  1712. if (classHistoryInput) classHistoryInput.addEventListener('change', () => {
  1713. const v = parseInt(classHistoryInput.value, 10);
  1714. if (Number.isFinite(v) && v >= 1) queueConfigUpdate({ detector: { class_history_size: v } });
  1715. });
  1716. if (classSwitchInput) classSwitchInput.addEventListener('change', () => {
  1717. const v = parseFloat(classSwitchInput.value);
  1718. if (Number.isFinite(v) && v >= 0.1 && v <= 1.0) queueConfigUpdate({ detector: { class_switch_ratio: v } });
  1719. });
  1720. agcToggle.addEventListener('change', () => queueSettingsUpdate({ agc: agcToggle.checked }));
  1721. dcToggle.addEventListener('change', () => queueSettingsUpdate({ dc_block: dcToggle.checked }));
  1722. iqToggle.addEventListener('change', () => queueSettingsUpdate({ iq_balance: iqToggle.checked }));
  1723. gpuToggle.addEventListener('change', () => queueConfigUpdate({ use_gpu_fft: gpuToggle.checked }));
  1724. if (recEnableToggle) recEnableToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { enabled: recEnableToggle.checked } }));
  1725. if (recIQToggle) recIQToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { record_iq: recIQToggle.checked } }));
  1726. if (recAudioToggle) recAudioToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { record_audio: recAudioToggle.checked } }));
  1727. if (recDemodToggle) recDemodToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { auto_demod: recDemodToggle.checked } }));
  1728. if (recDecodeToggle) recDecodeToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { auto_decode: recDecodeToggle.checked } }));
  1729. if (recMinSNR) recMinSNR.addEventListener('change', () => queueConfigUpdate({ recorder: { min_snr_db: parseFloat(recMinSNR.value) } }));
  1730. if (recMaxDisk) recMaxDisk.addEventListener('change', () => queueConfigUpdate({ recorder: { max_disk_mb: parseInt(recMaxDisk.value || '0', 10) } }));
  1731. if (recClassFilter) recClassFilter.addEventListener('change', () => {
  1732. const list = (recClassFilter.value || '')
  1733. .split(',')
  1734. .map(s => s.trim())
  1735. .filter(Boolean);
  1736. queueConfigUpdate({ recorder: { class_filter: list } });
  1737. });
  1738. avgSelect.addEventListener('change', () => {
  1739. avgAlpha = parseFloat(avgSelect.value) || 0;
  1740. resetProcessingCaches();
  1741. });
  1742. maxHoldToggle.addEventListener('change', () => {
  1743. maxHold = maxHoldToggle.checked;
  1744. maxSpectrum = null;
  1745. markSpectrumDirty();
  1746. });
  1747. if (debugOverlayToggle) debugOverlayToggle.addEventListener('change', () => {
  1748. showDebugOverlay = debugOverlayToggle.checked;
  1749. localStorage.setItem('spectre.debugOverlay', showDebugOverlay ? '1' : '0');
  1750. markSpectrumDirty();
  1751. updateHeroMetrics();
  1752. });
  1753. resetMaxBtn.addEventListener('click', () => {
  1754. maxSpectrum = null;
  1755. markSpectrumDirty();
  1756. });
  1757. followBtn.addEventListener('click', () => { followLive = true; pan = 0; });
  1758. fitBtn.addEventListener('click', fitView);
  1759. timelineFollowBtn.addEventListener('click', () => { timelineFrozen = false; });
  1760. timelineFreezeBtn.addEventListener('click', () => {
  1761. timelineFrozen = !timelineFrozen;
  1762. timelineFreezeBtn.textContent = timelineFrozen ? 'Frozen' : 'Freeze';
  1763. });
  1764. presetButtons.forEach((btn) => {
  1765. btn.addEventListener('click', () => {
  1766. const mhz = parseFloat(btn.dataset.center);
  1767. if (Number.isFinite(mhz)) tuneToFrequency(fromMHz(mhz));
  1768. });
  1769. });
  1770. railTabs.forEach((tab) => {
  1771. tab.addEventListener('click', () => {
  1772. railTabs.forEach(t => t.classList.toggle('active', t === tab));
  1773. tabPanels.forEach(panel => panel.classList.toggle('active', panel.dataset.panel === tab.dataset.tab));
  1774. });
  1775. });
  1776. modeButtons.forEach((btn) => {
  1777. btn.addEventListener('click', () => {
  1778. modeButtons.forEach(b => b.classList.toggle('active', b === btn));
  1779. document.body.classList.remove('mode-live', 'mode-hunt', 'mode-review', 'mode-lab');
  1780. document.body.classList.add(`mode-${btn.dataset.mode}`);
  1781. });
  1782. });
  1783. document.body.classList.add('mode-live');
  1784. drawerCloseBtn.addEventListener('click', closeDrawer);
  1785. exportEventBtn.addEventListener('click', exportSelectedEvent);
  1786. if (liveListenEventBtn) {
  1787. liveListenEventBtn.addEventListener('click', () => {
  1788. const ev = eventsById.get(selectedEventId);
  1789. if (!ev) return;
  1790. // Toggle off if already listening
  1791. if (liveListenWS && liveListenWS.playing) {
  1792. stopLiveListen();
  1793. return;
  1794. }
  1795. const freq = ev.center_hz;
  1796. const bw = ev.bandwidth_hz || 12000;
  1797. const mode = ev.class?.mod_type || 'NFM';
  1798. startLiveListen(freq, bw, mode);
  1799. });
  1800. }
  1801. if (decodeEventBtn) {
  1802. decodeEventBtn.addEventListener('click', async () => {
  1803. const ev = eventsById.get(selectedEventId);
  1804. if (!ev) return;
  1805. if (!recordingMetaEl) return;
  1806. const rec = recordings.find(r => r.event_id === ev.id) || recordings.find(r => r.center_hz === ev.center_hz);
  1807. if (!rec) {
  1808. decodeResultEl.textContent = 'Decode: no recording';
  1809. return;
  1810. }
  1811. const mode = decodeModeSelect?.value || ev.class?.mod_type || 'FT8';
  1812. const res = await fetch(`/api/recordings/${rec.id}/decode?mode=${mode}`);
  1813. if (!res.ok) {
  1814. decodeResultEl.textContent = 'Decode: failed';
  1815. return;
  1816. }
  1817. const data = await res.json();
  1818. decodeResultEl.textContent = `Decode: ${String(data.stdout || '').slice(0, 80)}`;
  1819. });
  1820. }
  1821. jumpToEventBtn.addEventListener('click', () => {
  1822. const ev = eventsById.get(selectedEventId);
  1823. if (!ev) return;
  1824. tuneToFrequency(ev.center_hz);
  1825. });
  1826. timelineCanvas.addEventListener('click', (ev) => {
  1827. const rect = timelineCanvas.getBoundingClientRect();
  1828. const x = (ev.clientX - rect.left) * (timelineCanvas.width / rect.width);
  1829. const y = (ev.clientY - rect.top) * (timelineCanvas.height / rect.height);
  1830. for (let i = timelineRects.length - 1; i >= 0; i--) {
  1831. const r = timelineRects[i];
  1832. if (x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h) {
  1833. openDrawer(eventsById.get(r.id));
  1834. return;
  1835. }
  1836. }
  1837. });
  1838. signalList.addEventListener('click', (ev) => {
  1839. const target = ev.target.closest('.signal-item');
  1840. if (!target) return;
  1841. // Select this signal for live listening — don't retune the SDR
  1842. const allItems = signalList.querySelectorAll('.signal-item');
  1843. allItems.forEach(el => el.classList.remove('active'));
  1844. target.classList.add('active');
  1845. // Store selected signal data for Live Listen button
  1846. window._selectedSignal = {
  1847. freq: parseFloat(target.dataset.center),
  1848. bw: parseFloat(target.dataset.bw || '12000'),
  1849. mode: target.dataset.class || ''
  1850. };
  1851. });
  1852. if (liveListenBtn) {
  1853. liveListenBtn.addEventListener('click', async () => {
  1854. // Toggle: if already listening, stop
  1855. if (liveListenWS && liveListenWS.playing) {
  1856. stopLiveListen();
  1857. return;
  1858. }
  1859. // Use selected signal if available, otherwise first in list
  1860. let freq, bw, mode;
  1861. if (window._selectedSignal) {
  1862. freq = window._selectedSignal.freq;
  1863. bw = window._selectedSignal.bw;
  1864. mode = window._selectedSignal.mode;
  1865. } else {
  1866. const first = signalList.querySelector('.signal-item');
  1867. if (!first) return;
  1868. freq = parseFloat(first.dataset.center);
  1869. bw = parseFloat(first.dataset.bw || '12000');
  1870. mode = first.dataset.class || '';
  1871. }
  1872. if (!Number.isFinite(freq)) return;
  1873. startLiveListen(freq, bw, mode);
  1874. });
  1875. }
  1876. eventList.addEventListener('click', (ev) => {
  1877. const target = ev.target.closest('.event-item');
  1878. if (!target) return;
  1879. const id = target.dataset.eventId;
  1880. openDrawer(eventsById.get(id));
  1881. });
  1882. if (recordingList) {
  1883. recordingList.addEventListener('click', async (ev) => {
  1884. const target = ev.target.closest('.recording-item');
  1885. if (!target) return;
  1886. const id = target.dataset.id;
  1887. const audio = new Audio(`/api/recordings/${id}/audio`);
  1888. audio.play();
  1889. if (recordingMetaEl) recordingMetaEl.textContent = `Recording: ${id}`;
  1890. if (recordingMetaLink) {
  1891. recordingMetaLink.href = `/api/recordings/${id}`;
  1892. recordingIQLink.href = `/api/recordings/${id}/iq`;
  1893. recordingAudioLink.href = `/api/recordings/${id}/audio`;
  1894. }
  1895. try {
  1896. const res = await fetch(`/api/recordings/${id}`);
  1897. if (!res.ok) return;
  1898. const meta = await res.json();
  1899. if (decodeResultEl) {
  1900. const rds = meta.rds_ps ? `RDS: ${meta.rds_ps}` : '';
  1901. decodeResultEl.textContent = `Decode: ${rds}`;
  1902. }
  1903. if (classifierScoresEl) {
  1904. const scores = meta.classification?.scores;
  1905. if (scores && typeof scores === 'object') {
  1906. const rows = Object.entries(scores)
  1907. .sort((a, b) => b[1] - a[1])
  1908. .slice(0, 6)
  1909. .map(([k, v]) => `${k}:${v.toFixed(2)}`)
  1910. .join(' · ');
  1911. classifierScoresEl.textContent = rows ? `Classifier scores: ${rows}` : 'Classifier scores: -';
  1912. } else {
  1913. classifierScoresEl.textContent = 'Classifier scores: -';
  1914. }
  1915. }
  1916. } catch {}
  1917. });
  1918. }
  1919. if (debugOverlayToggle) debugOverlayToggle.checked = showDebugOverlay;
  1920. window.addEventListener('keydown', (ev) => {
  1921. if (ev.target && ['INPUT', 'SELECT', 'TEXTAREA'].includes(ev.target.tagName)) return;
  1922. if (ev.key === ' ') {
  1923. ev.preventDefault();
  1924. followLive = true;
  1925. pan = 0;
  1926. } else if (ev.key.toLowerCase() === 'f') {
  1927. fitView();
  1928. } else if (ev.key.toLowerCase() === 'm') {
  1929. maxHold = !maxHold;
  1930. maxHoldToggle.checked = maxHold;
  1931. if (!maxHold) maxSpectrum = null;
  1932. markSpectrumDirty();
  1933. } else if (ev.key.toLowerCase() === 'g') {
  1934. gpuToggle.checked = !gpuToggle.checked;
  1935. queueConfigUpdate({ use_gpu_fft: gpuToggle.checked });
  1936. } else if (ev.key === '[') {
  1937. zoom = Math.max(0.25, zoom * 0.88);
  1938. } else if (ev.key === ']') {
  1939. zoom = Math.min(24, zoom * 1.12);
  1940. } else if (ev.key === 'ArrowLeft') {
  1941. pan = Math.max(-0.5, pan - 0.04);
  1942. followLive = false;
  1943. } else if (ev.key === 'ArrowRight') {
  1944. pan = Math.min(0.5, pan + 0.04);
  1945. followLive = false;
  1946. }
  1947. });
  1948. loadConfig();
  1949. loadStats();
  1950. loadGPU();
  1951. fetchEvents(true);
  1952. fetchRecordings();
  1953. loadDecoders();
  1954. connect();
  1955. requestAnimationFrame(renderLoop);
  1956. setInterval(loadStats, 1000);
  1957. setInterval(loadGPU, 1000);
  1958. setInterval(() => fetchEvents(false), 2000);
  1959. setInterval(fetchRecordings, 5000);
  1960. setInterval(loadSignals, 1500);
  1961. setInterval(loadDecoders, 10000);