Wideband autonomous SDR analysis engine forked from sdr-visual-suite
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

2248 líneas
80KB

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