Wideband autonomous SDR analysis engine forked from sdr-visual-suite
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

2190 lines
77KB

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