Wideband autonomous SDR analysis engine forked from sdr-visual-suite
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2218 lines
78KB

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