Wideband autonomous SDR analysis engine forked from sdr-visual-suite
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

2271 lignes
81KB

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