Wideband autonomous SDR analysis engine forked from sdr-visual-suite
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

2223 linhas
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 stats = refinementInfo.window_stats || null;
  768. if (stats && stats.count) {
  769. healthRefineWindows.textContent = `${fmtHz(stats.min_span_hz || 0)}–${fmtHz(stats.max_span_hz || 0)}`;
  770. } else {
  771. const windows = refinementInfo.windows || [];
  772. if (!Array.isArray(windows) || windows.length === 0) {
  773. healthRefineWindows.textContent = 'n/a';
  774. } else {
  775. const spans = windows.map(w => w.span_hz || 0).filter(v => v > 0);
  776. const minSpan = spans.length ? Math.min(...spans) : 0;
  777. const maxSpan = spans.length ? Math.max(...spans) : 0;
  778. healthRefineWindows.textContent = spans.length ? `${fmtHz(minSpan)}–${fmtHz(maxSpan)}` : 'n/a';
  779. }
  780. }
  781. }
  782. }
  783. function renderBandNavigator() {
  784. if (!latest) return;
  785. const ctx = navCanvas.getContext('2d');
  786. const w = navCanvas.width;
  787. const h = navCanvas.height;
  788. ctx.clearRect(0, 0, w, h);
  789. const display = getProcessedSpectrum();
  790. if (!display) return;
  791. const minDb = -120;
  792. const maxDb = 0;
  793. ctx.fillStyle = '#071018';
  794. ctx.fillRect(0, 0, w, h);
  795. ctx.strokeStyle = 'rgba(102, 169, 255, 0.25)';
  796. ctx.lineWidth = 1;
  797. ctx.beginPath();
  798. for (let x = 0; x < w; x++) {
  799. const idx = Math.min(display.length - 1, Math.floor((x / w) * display.length));
  800. const v = display[idx];
  801. const y = h - ((v - minDb) / (maxDb - minDb)) * (h - 10) - 5;
  802. if (x === 0) ctx.moveTo(x, y);
  803. else ctx.lineTo(x, y);
  804. }
  805. ctx.stroke();
  806. const span = latest.sample_rate / zoom;
  807. const fullStart = latest.center_hz - latest.sample_rate / 2;
  808. const viewStart = latest.center_hz - span / 2 + pan * span;
  809. const viewEnd = latest.center_hz + span / 2 + pan * span;
  810. const x1 = ((viewStart - fullStart) / latest.sample_rate) * w;
  811. const x2 = ((viewEnd - fullStart) / latest.sample_rate) * w;
  812. ctx.fillStyle = 'rgba(102, 240, 209, 0.10)';
  813. ctx.strokeStyle = 'rgba(102, 240, 209, 0.85)';
  814. ctx.lineWidth = 2;
  815. ctx.fillRect(x1, 4, Math.max(2, x2 - x1), h - 8);
  816. ctx.strokeRect(x1, 4, Math.max(2, x2 - x1), h - 8);
  817. }
  818. function drawSpectrumGrid(ctx, w, h, startHz, endHz) {
  819. ctx.strokeStyle = 'rgba(86, 109, 148, 0.18)';
  820. ctx.lineWidth = 1;
  821. for (let i = 1; i < 6; i++) {
  822. const y = (h / 6) * i;
  823. ctx.beginPath();
  824. ctx.moveTo(0, y);
  825. ctx.lineTo(w, y);
  826. ctx.stroke();
  827. }
  828. for (let i = 1; i < 8; i++) {
  829. const x = (w / 8) * i;
  830. ctx.beginPath();
  831. ctx.moveTo(x, 0);
  832. ctx.lineTo(x, h);
  833. ctx.stroke();
  834. const hz = startHz + (i / 8) * (endHz - startHz);
  835. ctx.fillStyle = 'rgba(173, 192, 220, 0.72)';
  836. ctx.font = `${Math.max(11, Math.floor(h / 26))}px Inter, sans-serif`;
  837. ctx.fillText((hz / 1e6).toFixed(3), x + 4, h - 8);
  838. }
  839. }
  840. function drawCfarEdgeOverlay(ctx, w, h, startHz, endHz) {
  841. if (!latest) return;
  842. const mode = currentConfig?.detector?.cfar_mode || 'OFF';
  843. if (mode === 'OFF') return;
  844. if (currentConfig?.detector?.cfar_wrap_around) return;
  845. const guardHz = currentConfig.detector.cfar_guard_hz ?? 500;
  846. const trainHz = currentConfig.detector.cfar_train_hz ?? 5000;
  847. const fftSize = latest.fft_size || latest.spectrum_db?.length;
  848. if (!fftSize || fftSize <= 0) return;
  849. const binW = (latest.sample_rate || 2048000) / fftSize;
  850. const bins = Math.ceil(guardHz / binW) + Math.ceil(trainHz / binW);
  851. if (bins <= 0) return;
  852. const binHz = latest.sample_rate / fftSize;
  853. const edgeHz = bins * binHz;
  854. const bandStart = latest.center_hz - latest.sample_rate / 2;
  855. const bandEnd = latest.center_hz + latest.sample_rate / 2;
  856. const leftEdgeEnd = bandStart + edgeHz;
  857. const rightEdgeStart = bandEnd - edgeHz;
  858. ctx.fillStyle = 'rgba(255, 204, 102, 0.08)';
  859. ctx.strokeStyle = 'rgba(255, 204, 102, 0.18)';
  860. ctx.lineWidth = 1;
  861. const leftStart = Math.max(startHz, bandStart);
  862. const leftEnd = Math.min(endHz, leftEdgeEnd);
  863. if (leftEnd > leftStart) {
  864. const x1 = ((leftStart - startHz) / (endHz - startHz)) * w;
  865. const x2 = ((leftEnd - startHz) / (endHz - startHz)) * w;
  866. ctx.fillRect(x1, 0, Math.max(2, x2 - x1), h);
  867. ctx.strokeRect(x1, 0, Math.max(2, x2 - x1), h);
  868. }
  869. const rightStart = Math.max(startHz, rightEdgeStart);
  870. const rightEnd = Math.min(endHz, bandEnd);
  871. if (rightEnd > rightStart) {
  872. const x1 = ((rightStart - startHz) / (endHz - startHz)) * w;
  873. const x2 = ((rightEnd - startHz) / (endHz - startHz)) * w;
  874. ctx.fillRect(x1, 0, Math.max(2, x2 - x1), h);
  875. ctx.strokeRect(x1, 0, Math.max(2, x2 - x1), h);
  876. }
  877. }
  878. function renderSpectrum() {
  879. if (!latest) return;
  880. const ctx = spectrumCanvas.getContext('2d');
  881. const w = spectrumCanvas.width;
  882. const h = spectrumCanvas.height;
  883. ctx.clearRect(0, 0, w, h);
  884. const display = getProcessedSpectrum();
  885. if (!display) return;
  886. const n = display.length;
  887. const span = latest.sample_rate / zoom;
  888. const startHz = latest.center_hz - span / 2 + pan * span;
  889. const endHz = latest.center_hz + span / 2 + pan * span;
  890. spanInput.value = (span / 1e6).toFixed(3);
  891. drawSpectrumGrid(ctx, w, h, startHz, endHz);
  892. drawCfarEdgeOverlay(ctx, w, h, startHz, endHz);
  893. const minDb = -120;
  894. const maxDb = 0;
  895. const fill = ctx.createLinearGradient(0, 0, 0, h);
  896. fill.addColorStop(0, 'rgba(102, 240, 209, 0.20)');
  897. fill.addColorStop(1, 'rgba(102, 240, 209, 0.02)');
  898. ctx.beginPath();
  899. for (let x = 0; x < w; x++) {
  900. const f1 = startHz + (x / w) * (endHz - startHz);
  901. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  902. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  903. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  904. const v = maxInBinRange(display, b0, b1);
  905. const y = h - ((v - minDb) / (maxDb - minDb)) * (h - 18) - 6;
  906. if (x === 0) ctx.moveTo(x, y);
  907. else ctx.lineTo(x, y);
  908. }
  909. ctx.lineTo(w, h);
  910. ctx.lineTo(0, h);
  911. ctx.closePath();
  912. ctx.fillStyle = fill;
  913. ctx.fill();
  914. ctx.strokeStyle = '#66f0d1';
  915. ctx.lineWidth = 2;
  916. ctx.beginPath();
  917. liveSignalRects = [];
  918. for (let x = 0; x < w; x++) {
  919. const f1 = startHz + (x / w) * (endHz - startHz);
  920. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  921. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  922. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  923. const v = maxInBinRange(display, b0, b1);
  924. const y = h - ((v - minDb) / (maxDb - minDb)) * (h - 18) - 6;
  925. if (x === 0) ctx.moveTo(x, y);
  926. else ctx.lineTo(x, y);
  927. }
  928. ctx.stroke();
  929. drawThresholdOverlay(ctx, w, h, minDb, maxDb);
  930. if (Array.isArray(latest.signals)) {
  931. latest.signals.forEach((s, index) => {
  932. const left = s.center_hz - s.bw_hz / 2;
  933. const right = s.center_hz + s.bw_hz / 2;
  934. if (right < startHz || left > endHz) return;
  935. const x1 = ((left - startHz) / (endHz - startHz)) * w;
  936. const x2 = ((right - startHz) / (endHz - startHz)) * w;
  937. const boxW = Math.max(2, x2 - x1);
  938. const mod = s.class?.mod_type || '';
  939. const mc = modColor(mod);
  940. const rdsName = s.class?.pll?.rds_station || '';
  941. // Signal box with modulation-based color
  942. ctx.fillStyle = modColorStr(mod, 0.10);
  943. ctx.strokeStyle = modColorStr(mod, 0.75);
  944. ctx.lineWidth = 1.5;
  945. ctx.fillRect(x1, 10, boxW, h - 28);
  946. ctx.strokeRect(x1, 10, boxW, h - 28);
  947. if (matchesListenTarget(s)) {
  948. ctx.strokeStyle = 'rgba(255, 92, 92, 0.95)';
  949. ctx.lineWidth = 2.5;
  950. ctx.strokeRect(x1 - 1, 9, boxW + 2, h - 26);
  951. }
  952. // Label badges with dark background for readability
  953. const labelX = Math.max(4, x1 + 4);
  954. const baseY = 14;
  955. const freqStr = `${(s.center_hz / 1e6).toFixed(4)} MHz`;
  956. // Badge background
  957. const badgeH = rdsName ? 42 : (mod ? 30 : 16);
  958. const freqW = ctx.measureText ? 0 : 0; // will measure below
  959. ctx.font = '11px Inter, sans-serif';
  960. const textW = Math.max(ctx.measureText(freqStr).width, mod ? ctx.measureText(mod).width : 0, rdsName ? ctx.measureText(rdsName).width : 0) + 8;
  961. ctx.fillStyle = 'rgba(7, 16, 24, 0.82)';
  962. ctx.fillRect(labelX - 3, baseY, textW, badgeH);
  963. // Line 1: Frequency (teal)
  964. ctx.fillStyle = 'rgba(102, 240, 209, 0.95)';
  965. ctx.font = '11px Inter, sans-serif';
  966. ctx.fillText(freqStr, labelX, baseY + 11);
  967. // Line 2: Mod type (modulation color)
  968. if (mod) {
  969. ctx.fillStyle = mc.label;
  970. ctx.font = 'bold 10px Inter, sans-serif';
  971. ctx.fillText(mod, labelX, baseY + 23);
  972. }
  973. // Line 3: RDS station name (white bold)
  974. if (rdsName) {
  975. ctx.fillStyle = 'rgba(255, 255, 255, 0.95)';
  976. ctx.font = 'bold 12px Inter, sans-serif';
  977. ctx.fillText(rdsName, labelX, baseY + 36);
  978. }
  979. const debugMatch = (latest?.debug?.scores || []).find((d) => Math.abs((d.center_hz || 0) - (s.center_hz || 0)) < Math.max(500, s.bw_hz || 0));
  980. if (debugMatch?.scores && (!s.class || !s.class.scores)) {
  981. s.debug_scores = debugMatch.scores;
  982. }
  983. liveSignalRects.push({
  984. x: x1,
  985. y: 10,
  986. w: boxW,
  987. h: h - 28,
  988. signal: s,
  989. });
  990. });
  991. }
  992. }
  993. function renderWaterfall() {
  994. if (!latest) return;
  995. const ctx = waterfallCanvas.getContext('2d');
  996. const w = waterfallCanvas.width;
  997. const h = waterfallCanvas.height;
  998. const prev = ctx.getImageData(0, 0, w, h - 1);
  999. ctx.putImageData(prev, 0, 1);
  1000. const display = getProcessedSpectrum();
  1001. if (!display) return;
  1002. const n = display.length;
  1003. const span = latest.sample_rate / zoom;
  1004. const startHz = latest.center_hz - span / 2 + pan * span;
  1005. const endHz = latest.center_hz + span / 2 + pan * span;
  1006. const minDb = -120;
  1007. const maxDb = 0;
  1008. const row = ctx.createImageData(w, 1);
  1009. for (let x = 0; x < w; x++) {
  1010. const f1 = startHz + (x / w) * (endHz - startHz);
  1011. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  1012. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  1013. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  1014. const v = maxInBinRange(display, b0, b1);
  1015. const norm = Math.max(0, Math.min(1, (v - minDb) / (maxDb - minDb)));
  1016. const [r, g, b] = colorMap(norm);
  1017. row.data[x * 4] = r;
  1018. row.data[x * 4 + 1] = g;
  1019. row.data[x * 4 + 2] = b;
  1020. row.data[x * 4 + 3] = 255;
  1021. }
  1022. ctx.putImageData(row, 0, 0);
  1023. drawCfarEdgeOverlay(ctx, w, h, startHz, endHz);
  1024. // Waterfall signal markers: thin vertical lines at signal center frequencies
  1025. if (Array.isArray(latest.signals)) {
  1026. latest.signals.forEach(s => {
  1027. if (!s.center_hz) return;
  1028. const xc = ((s.center_hz - startHz) / (endHz - startHz)) * w;
  1029. if (xc < 0 || xc > w) return;
  1030. const mod = s.class?.mod_type || '';
  1031. ctx.strokeStyle = modColorStr(mod, 0.35);
  1032. ctx.lineWidth = 1;
  1033. ctx.setLineDash([2, 3]);
  1034. ctx.beginPath();
  1035. ctx.moveTo(xc, 0);
  1036. ctx.lineTo(xc, h);
  1037. ctx.stroke();
  1038. ctx.setLineDash([]);
  1039. });
  1040. }
  1041. }
  1042. function renderOccupancy() {
  1043. const ctx = occupancyCanvas.getContext('2d');
  1044. const w = occupancyCanvas.width;
  1045. const h = occupancyCanvas.height;
  1046. ctx.clearRect(0, 0, w, h);
  1047. ctx.fillStyle = '#071018';
  1048. ctx.fillRect(0, 0, w, h);
  1049. if (!latest || events.length === 0) return;
  1050. const bins = new Array(Math.max(32, Math.min(160, Math.floor(w / 8)))).fill(0);
  1051. const bandStart = latest.center_hz - latest.sample_rate / 2;
  1052. const bandEnd = latest.center_hz + latest.sample_rate / 2;
  1053. const now = Date.now();
  1054. const windowStart = now - timelineWindowMs;
  1055. for (const ev of events) {
  1056. if (ev.end_ms < windowStart || ev.start_ms > now) continue;
  1057. const left = ev.center_hz - ev.bandwidth_hz / 2;
  1058. const right = ev.center_hz + ev.bandwidth_hz / 2;
  1059. const normL = Math.max(0, Math.min(1, (left - bandStart) / (bandEnd - bandStart)));
  1060. const normR = Math.max(0, Math.min(1, (right - bandStart) / (bandEnd - bandStart)));
  1061. let b0 = Math.floor(normL * bins.length);
  1062. let b1 = Math.floor(normR * bins.length);
  1063. if (b1 < b0) [b0, b1] = [b1, b0];
  1064. for (let i = Math.max(0, b0); i <= Math.min(bins.length - 1, b1); i++) {
  1065. bins[i] += Math.max(0.3, (ev.snr_db || 0) / 12 + 1);
  1066. }
  1067. }
  1068. const maxBin = Math.max(1, ...bins);
  1069. bins.forEach((v, i) => {
  1070. const norm = v / maxBin;
  1071. const [r, g, b] = colorMap(norm);
  1072. ctx.fillStyle = `rgb(${r}, ${g}, ${b})`;
  1073. const x = (i / bins.length) * w;
  1074. const bw = Math.ceil(w / bins.length) + 1;
  1075. ctx.fillRect(x, 0, bw, h);
  1076. });
  1077. }
  1078. function renderTimeline() {
  1079. const ctx = timelineCanvas.getContext('2d');
  1080. const w = timelineCanvas.width;
  1081. const h = timelineCanvas.height;
  1082. ctx.clearRect(0, 0, w, h);
  1083. ctx.fillStyle = '#071018';
  1084. ctx.fillRect(0, 0, w, h);
  1085. if (events.length === 0) {
  1086. timelineRangeEl.textContent = 'No events yet';
  1087. return;
  1088. }
  1089. const endMs = Date.now();
  1090. const startMs = endMs - timelineWindowMs;
  1091. timelineRangeEl.textContent = `${new Date(startMs).toLocaleTimeString()} - ${new Date(endMs).toLocaleTimeString()}`;
  1092. let minHz = Infinity;
  1093. let maxHz = -Infinity;
  1094. if (latest) {
  1095. minHz = latest.center_hz - latest.sample_rate / 2;
  1096. maxHz = latest.center_hz + latest.sample_rate / 2;
  1097. } else {
  1098. for (const ev of events) {
  1099. minHz = Math.min(minHz, ev.center_hz - ev.bandwidth_hz / 2);
  1100. maxHz = Math.max(maxHz, ev.center_hz + ev.bandwidth_hz / 2);
  1101. }
  1102. }
  1103. if (!isFinite(minHz) || !isFinite(maxHz) || minHz === maxHz) {
  1104. minHz = 0;
  1105. maxHz = 1;
  1106. }
  1107. ctx.strokeStyle = 'rgba(86, 109, 148, 0.18)';
  1108. ctx.lineWidth = 1;
  1109. for (let i = 1; i < 6; i++) {
  1110. const y = (h / 6) * i;
  1111. ctx.beginPath();
  1112. ctx.moveTo(0, y);
  1113. ctx.lineTo(w, y);
  1114. ctx.stroke();
  1115. }
  1116. for (let i = 1; i < 8; i++) {
  1117. const x = (w / 8) * i;
  1118. ctx.beginPath();
  1119. ctx.moveTo(x, 0);
  1120. ctx.lineTo(x, h);
  1121. ctx.stroke();
  1122. }
  1123. timelineRects = [];
  1124. for (const ev of events) {
  1125. if (ev.end_ms < startMs || ev.start_ms > endMs) continue;
  1126. const x1 = ((Math.max(ev.start_ms, startMs) - startMs) / (endMs - startMs)) * w;
  1127. const x2 = ((Math.min(ev.end_ms, endMs) - startMs) / (endMs - startMs)) * w;
  1128. const topHz = ev.center_hz + ev.bandwidth_hz / 2;
  1129. const bottomHz = ev.center_hz - ev.bandwidth_hz / 2;
  1130. const y1 = ((maxHz - topHz) / (maxHz - minHz)) * h;
  1131. const y2 = ((maxHz - bottomHz) / (maxHz - minHz)) * h;
  1132. const rect = { x: x1, y: y1, w: Math.max(2, x2 - x1), h: Math.max(3, y2 - y1), id: ev.id };
  1133. timelineRects.push(rect);
  1134. ctx.fillStyle = snrColor(ev.snr_db || 0).replace('rgb', 'rgba').replace(')', ', 0.85)');
  1135. ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
  1136. }
  1137. if (selectedEventId) {
  1138. const hit = timelineRects.find(r => r.id === selectedEventId);
  1139. if (hit) {
  1140. ctx.strokeStyle = '#ffffff';
  1141. ctx.lineWidth = 2;
  1142. ctx.strokeRect(hit.x - 1, hit.y - 1, hit.w + 2, hit.h + 2);
  1143. }
  1144. }
  1145. }
  1146. function renderDetailSpectrogram() {
  1147. const ev = eventsById.get(selectedEventId);
  1148. const ctx = detailSpectrogram.getContext('2d');
  1149. const w = detailSpectrogram.width;
  1150. const h = detailSpectrogram.height;
  1151. ctx.clearRect(0, 0, w, h);
  1152. ctx.fillStyle = '#071018';
  1153. ctx.fillRect(0, 0, w, h);
  1154. if (!latest || !ev) return;
  1155. const display = getProcessedSpectrum();
  1156. if (!display) return;
  1157. const n = display.length;
  1158. const localSpan = Math.min(latest.sample_rate, Math.max(ev.bandwidth_hz * 4, latest.sample_rate / 10));
  1159. const startHz = ev.center_hz - localSpan / 2;
  1160. const endHz = ev.center_hz + localSpan / 2;
  1161. const minDb = -120;
  1162. const maxDb = 0;
  1163. const row = ctx.createImageData(w, 1);
  1164. for (let x = 0; x < w; x++) {
  1165. const f1 = startHz + (x / w) * (endHz - startHz);
  1166. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  1167. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  1168. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  1169. const v = maxInBinRange(display, b0, b1);
  1170. const norm = Math.max(0, Math.min(1, (v - minDb) / (maxDb - minDb)));
  1171. const [r, g, b] = colorMap(norm);
  1172. row.data[x * 4] = r;
  1173. row.data[x * 4 + 1] = g;
  1174. row.data[x * 4 + 2] = b;
  1175. row.data[x * 4 + 3] = 255;
  1176. }
  1177. for (let y = 0; y < h; y++) ctx.putImageData(row, 0, y);
  1178. const centerX = w / 2;
  1179. ctx.strokeStyle = 'rgba(255,255,255,0.65)';
  1180. ctx.lineWidth = 1;
  1181. ctx.beginPath();
  1182. ctx.moveTo(centerX, 0);
  1183. ctx.lineTo(centerX, h);
  1184. ctx.stroke();
  1185. }
  1186. let _lastEventListKey = '';
  1187. function _createSignalItem(s) {
  1188. const btn = document.createElement('button');
  1189. btn.className = 'list-item signal-item';
  1190. btn.type = 'button';
  1191. btn.dataset.center = s.center_hz;
  1192. btn.dataset.bw = s.bw_hz || 0;
  1193. btn.dataset.class = s.class?.mod_type || '';
  1194. btn.dataset.id = s.id || 0;
  1195. const mod = s.class?.mod_type || '';
  1196. const mc = modColor(mod);
  1197. const rds = s.class?.pll?.rds_station || '';
  1198. 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>`;
  1199. btn.style.borderLeftColor = mc.label;
  1200. btn.style.borderLeftWidth = '3px';
  1201. btn.style.borderLeftStyle = 'solid';
  1202. if (matchesListenTarget(s)) btn.classList.add('listening');
  1203. return btn;
  1204. }
  1205. function _patchSignalItem(el, s) {
  1206. const freqEl = el.querySelector('[data-field="freq"]');
  1207. const snrEl = el.querySelector('[data-field="snr"]');
  1208. const bwEl = el.querySelector('[data-field="bw"]');
  1209. const modEl = el.querySelector('[data-field="mod"]');
  1210. const rdsEl = el.querySelector('[data-field="rds"]');
  1211. const mod = s.class?.mod_type || '';
  1212. const mc = modColor(mod);
  1213. const rds = s.class?.pll?.rds_station || '';
  1214. if (freqEl) freqEl.textContent = fmtMHz(s.center_hz, 6);
  1215. if (snrEl) { snrEl.textContent = `${(s.snr_db || 0).toFixed(1)} dB`; snrEl.style.color = snrColor(s.snr_db || 0); }
  1216. if (bwEl) bwEl.textContent = `BW ${fmtKHz(s.bw_hz || 0)}`;
  1217. if (modEl) { modEl.textContent = mod || 'carrier'; modEl.style.color = mc.label; }
  1218. if (rdsEl) { rdsEl.textContent = rds; } else if (rds && !rdsEl) {
  1219. const span = document.createElement('span');
  1220. span.className = 'item-meta';
  1221. span.dataset.field = 'rds';
  1222. span.style.color = '#fff';
  1223. span.style.fontWeight = '700';
  1224. span.textContent = rds;
  1225. el.querySelector('.item-bottom')?.appendChild(span);
  1226. }
  1227. el.dataset.center = s.center_hz;
  1228. el.dataset.bw = s.bw_hz || 0;
  1229. el.dataset.class = mod;
  1230. el.style.borderLeftColor = mc.label;
  1231. el.classList.toggle('listening', matchesListenTarget(s));
  1232. }
  1233. function renderLists() {
  1234. const signals = Array.isArray(latest?.signals) ? [...latest.signals] : [];
  1235. signals.sort((a, b) => (b.snr_db || 0) - (a.snr_db || 0));
  1236. signalCountBadge.textContent = `${signals.length} live`;
  1237. metricSignals.textContent = String(signals.length);
  1238. const displaySigs = signals.slice(0, 24);
  1239. const wantIds = new Set(displaySigs.map(s => String(s.id || 0)));
  1240. // Remove empty-state placeholder if signals exist
  1241. const emptyEl = signalList.querySelector('.empty-state');
  1242. if (emptyEl && displaySigs.length > 0) emptyEl.remove();
  1243. // Remove DOM items whose signal ID is no longer present
  1244. signalList.querySelectorAll('.signal-item').forEach(el => {
  1245. if (!wantIds.has(el.dataset.id)) el.remove();
  1246. });
  1247. if (displaySigs.length === 0) {
  1248. if (!signalList.querySelector('.empty-state')) {
  1249. signalList.innerHTML = '<div class="empty-state">No live signals yet.</div>';
  1250. }
  1251. } else {
  1252. // Build map of existing DOM items
  1253. const domById = new Map();
  1254. signalList.querySelectorAll('.signal-item').forEach(el => domById.set(el.dataset.id, el));
  1255. displaySigs.forEach(s => {
  1256. const id = String(s.id || 0);
  1257. const existing = domById.get(id);
  1258. if (existing) {
  1259. _patchSignalItem(existing, s);
  1260. } else {
  1261. const el = _createSignalItem(s);
  1262. // Auto-select if it matches the user's last selection
  1263. if (window._selectedSignal && Math.abs(s.center_hz - window._selectedSignal.freq) < 50000) {
  1264. el.classList.add('active');
  1265. }
  1266. signalList.appendChild(el);
  1267. }
  1268. });
  1269. }
  1270. const recent = [...events].sort((a, b) => b.end_ms - a.end_ms);
  1271. eventCountBadge.textContent = `${recent.length} stored`;
  1272. const evtKey = `${recent.length}:${selectedEventId}:${recent.slice(0, 5).map(e => e.id).join(',')}`;
  1273. if (evtKey !== _lastEventListKey) {
  1274. _lastEventListKey = evtKey;
  1275. if (recent.length === 0) {
  1276. eventList.innerHTML = '<div class="empty-state">No events yet.</div>';
  1277. } else {
  1278. eventList.innerHTML = recent.slice(0, 40).map((ev) => `
  1279. <button class="list-item event-item ${selectedEventId === ev.id ? 'active' : ''}" type="button" data-event-id="${ev.id}">
  1280. <div class="item-top">
  1281. <span class="item-title">${fmtMHz(ev.center_hz, 6)}</span>
  1282. <span class="item-badge" style="color:${snrColor(ev.snr_db || 0)}">${(ev.snr_db || 0).toFixed(1)} dB</span>
  1283. </div>
  1284. <div class="item-bottom">
  1285. <span class="item-meta">${fmtKHz(ev.bandwidth_hz || 0)} · ${fmtMs(ev.duration_ms || 0)}</span>
  1286. <span class="item-meta">${new Date(ev.end_ms).toLocaleTimeString()}</span>
  1287. </div>
  1288. </button>
  1289. `).join('');
  1290. }
  1291. }
  1292. if (recordingList && recordingCountBadge) {
  1293. recordingCountBadge.textContent = `${recordings.length}`;
  1294. if (recordings.length === 0) {
  1295. recordingList.innerHTML = '<div class="empty-state">No recordings yet.</div>';
  1296. } else {
  1297. recordingList.innerHTML = recordings.slice(0, 50).map((rec) => `
  1298. <button class="list-item recording-item" type="button" data-id="${rec.id}">
  1299. <div class="item-top">
  1300. <span class="item-title">${new Date(rec.start).toLocaleString()}</span>
  1301. <span class="item-badge">${fmtMHz(rec.center_hz || 0, 6)}</span>
  1302. </div>
  1303. <div class="item-bottom">
  1304. <span class="item-meta">${rec.id}</span>
  1305. <span class="item-meta">recording</span>
  1306. </div>
  1307. </button>
  1308. `).join('');
  1309. }
  1310. }
  1311. }
  1312. function normalizeEvent(ev) {
  1313. const startMs = new Date(ev.start).getTime();
  1314. const endMs = new Date(ev.end).getTime();
  1315. return {
  1316. ...ev,
  1317. start_ms: startMs,
  1318. end_ms: endMs,
  1319. duration_ms: Math.max(0, endMs - startMs),
  1320. };
  1321. }
  1322. function upsertEvents(list, replace = false) {
  1323. if (replace) {
  1324. events.length = 0;
  1325. eventsById.clear();
  1326. }
  1327. for (const raw of list) {
  1328. if (!raw || !raw.id || eventsById.has(raw.id)) continue;
  1329. const ev = normalizeEvent(raw);
  1330. eventsById.set(ev.id, ev);
  1331. events.push(ev);
  1332. }
  1333. events.sort((a, b) => a.end_ms - b.end_ms);
  1334. const maxEvents = 1500;
  1335. if (events.length > maxEvents) {
  1336. const drop = events.length - maxEvents;
  1337. for (let i = 0; i < drop; i++) eventsById.delete(events[i].id);
  1338. events.splice(0, drop);
  1339. }
  1340. if (events.length > 0) lastEventEndMs = events[events.length - 1].end_ms;
  1341. renderLists();
  1342. }
  1343. async function fetchEvents(initial) {
  1344. if (eventsFetchInFlight || timelineFrozen) return;
  1345. eventsFetchInFlight = true;
  1346. try {
  1347. let url = '/api/events?limit=1000';
  1348. if (!initial && lastEventEndMs > 0) url = `/api/events?since=${lastEventEndMs - 1}`;
  1349. const res = await fetch(url);
  1350. if (!res.ok) return;
  1351. const data = await res.json();
  1352. if (Array.isArray(data)) upsertEvents(data, initial);
  1353. } finally {
  1354. eventsFetchInFlight = false;
  1355. }
  1356. }
  1357. async function fetchRecordings() {
  1358. if (recordingsFetchInFlight || !recordingList) return;
  1359. recordingsFetchInFlight = true;
  1360. try {
  1361. const res = await fetch('/api/recordings');
  1362. if (!res.ok) return;
  1363. const data = await res.json();
  1364. if (Array.isArray(data)) {
  1365. recordings = data;
  1366. renderLists();
  1367. }
  1368. } finally {
  1369. recordingsFetchInFlight = false;
  1370. }
  1371. }
  1372. function openDrawer(ev) {
  1373. if (!ev) return;
  1374. selectedEventId = ev.id;
  1375. detailSubtitle.textContent = `Event ${ev.id}`;
  1376. detailCenterEl.textContent = fmtMHz(ev.center_hz, 6);
  1377. detailBwEl.textContent = fmtKHz(ev.bandwidth_hz || 0);
  1378. detailStartEl.textContent = new Date(ev.start_ms).toLocaleString();
  1379. detailEndEl.textContent = new Date(ev.end_ms).toLocaleString();
  1380. detailSnrEl.textContent = `${(ev.snr_db || 0).toFixed(1)} dB`;
  1381. detailDurEl.textContent = fmtMs(ev.duration_ms || 0);
  1382. detailClassEl.textContent = ev.class?.mod_type || '-';
  1383. if (classifierScoresEl) {
  1384. const scores = ev.class?.scores;
  1385. if (scores && typeof scores === 'object') {
  1386. const rows = Object.entries(scores)
  1387. .sort((a, b) => b[1] - a[1])
  1388. .slice(0, 6)
  1389. .map(([k, v]) => `${k}:${v.toFixed(2)}`)
  1390. .join(' · ');
  1391. classifierScoresEl.textContent = rows ? `Classifier scores: ${rows}` : 'Classifier scores: -';
  1392. renderScoreBars(scores);
  1393. } else {
  1394. const liveScores = (latest?.debug?.scores || []).find((s) => Math.abs((s.center_hz || 0) - (ev.center_hz || 0)) < Math.max(500, (ev.bandwidth_hz || 0)));
  1395. if (liveScores?.scores) {
  1396. const rows = Object.entries(liveScores.scores)
  1397. .sort((a, b) => b[1] - a[1])
  1398. .slice(0, 6)
  1399. .map(([k, v]) => `${k}:${Number(v).toFixed(2)}`)
  1400. .join(' · ');
  1401. classifierScoresEl.textContent = rows ? `Classifier scores: ${rows}` : 'Classifier scores: -';
  1402. renderScoreBars(liveScores.scores);
  1403. } else {
  1404. classifierScoresEl.textContent = 'Classifier scores: -';
  1405. renderScoreBars(null);
  1406. }
  1407. }
  1408. }
  1409. if (recordingMetaEl) {
  1410. recordingMetaEl.textContent = 'Recording: -';
  1411. }
  1412. if (recordingMetaLink) {
  1413. recordingMetaLink.href = '#';
  1414. recordingIQLink.href = '#';
  1415. recordingAudioLink.href = '#';
  1416. }
  1417. drawerEl.classList.add('open');
  1418. drawerEl.setAttribute('aria-hidden', 'false');
  1419. renderDetailSpectrogram();
  1420. renderLists();
  1421. }
  1422. function closeDrawer() {
  1423. drawerEl.classList.remove('open');
  1424. drawerEl.setAttribute('aria-hidden', 'true');
  1425. selectedEventId = null;
  1426. renderLists();
  1427. }
  1428. function fitView() {
  1429. zoom = 1;
  1430. pan = 0;
  1431. followLive = true;
  1432. }
  1433. function tuneToFrequency(centerHz) {
  1434. if (!Number.isFinite(centerHz)) return;
  1435. followLive = true;
  1436. centerInput.value = (centerHz / 1e6).toFixed(6);
  1437. queueConfigUpdate({ center_hz: centerHz });
  1438. }
  1439. function connect() {
  1440. clearTimeout(wsReconnectTimer);
  1441. const proto = location.protocol === 'https:' ? 'wss' : 'ws';
  1442. // Remote optimization: detect non-localhost and opt into binary + decimation
  1443. const hn = location.hostname;
  1444. const isLocal = ['localhost', '127.0.0.1', '::1'].includes(hn)
  1445. || hn.startsWith('192.168.')
  1446. || hn.startsWith('10.')
  1447. || /^172\.(1[6-9]|2\d|3[01])\./.test(hn)
  1448. || hn.endsWith('.local')
  1449. || hn.endsWith('.lan');
  1450. const params = new URLSearchParams(location.search);
  1451. const wantBinary = params.get('binary') === '1' || !isLocal;
  1452. const bins = parseInt(params.get('bins') || (isLocal ? '0' : '2048'), 10);
  1453. const fps = parseInt(params.get('fps') || (isLocal ? '0' : '10'), 10);
  1454. let wsUrl = `${proto}://${location.host}/ws`;
  1455. if (wantBinary || bins > 0 || fps > 0) {
  1456. const qp = [];
  1457. if (wantBinary) qp.push('binary=1');
  1458. if (bins > 0) qp.push(`bins=${bins}`);
  1459. if (fps > 0) qp.push(`fps=${fps}`);
  1460. wsUrl += '?' + qp.join('&');
  1461. }
  1462. const ws = new WebSocket(wsUrl);
  1463. ws.binaryType = 'arraybuffer';
  1464. setWsBadge('Connecting', 'neutral');
  1465. ws.onopen = () => setWsBadge('Live', 'ok');
  1466. ws.onmessage = (ev) => {
  1467. if (ev.data instanceof ArrayBuffer) {
  1468. try {
  1469. const decoded = decodeBinaryFrame(ev.data);
  1470. if (decoded) latest = decoded;
  1471. } catch (e) {
  1472. console.warn('binary frame decode error:', e);
  1473. return;
  1474. }
  1475. } else {
  1476. latest = JSON.parse(ev.data);
  1477. }
  1478. markSpectrumDirty();
  1479. if (followLive) pan = 0;
  1480. updateHeroMetrics();
  1481. renderLists();
  1482. };
  1483. ws.onclose = () => {
  1484. setWsBadge('Retrying', 'bad');
  1485. wsReconnectTimer = setTimeout(connect, 1000);
  1486. };
  1487. ws.onerror = () => ws.close();
  1488. }
  1489. // Decode binary spectrum frame v4 (hybrid: binary spectrum + JSON signals)
  1490. function decodeBinaryFrame(buf) {
  1491. const view = new DataView(buf);
  1492. if (buf.byteLength < 32) return null;
  1493. // Header: 32 bytes
  1494. const magic0 = view.getUint8(0);
  1495. const magic1 = view.getUint8(1);
  1496. if (magic0 !== 0x53 || magic1 !== 0x50) return null; // not "SP"
  1497. const version = view.getUint16(2, true);
  1498. const ts = Number(view.getBigInt64(4, true));
  1499. const centerHz = view.getFloat64(12, true);
  1500. const binCount = view.getUint32(20, true);
  1501. const sampleRateHz = view.getUint32(24, true);
  1502. const jsonOffset = view.getUint32(28, true);
  1503. if (buf.byteLength < 32 + binCount * 2) return null;
  1504. // Spectrum: binCount × int16 at offset 32
  1505. const spectrum = new Float64Array(binCount);
  1506. let off = 32;
  1507. for (let i = 0; i < binCount; i++) {
  1508. spectrum[i] = view.getInt16(off, true) / 100;
  1509. off += 2;
  1510. }
  1511. // JSON signals + debug after the spectrum data
  1512. let signals = [];
  1513. let debug = null;
  1514. if (jsonOffset > 0 && jsonOffset < buf.byteLength) {
  1515. try {
  1516. const jsonBytes = new Uint8Array(buf, jsonOffset);
  1517. const jsonStr = new TextDecoder().decode(jsonBytes);
  1518. const parsed = JSON.parse(jsonStr);
  1519. signals = parsed.signals || [];
  1520. debug = parsed.debug || null;
  1521. } catch (e) {
  1522. // JSON parse failed — continue with empty signals
  1523. }
  1524. }
  1525. return {
  1526. ts: ts,
  1527. center_hz: centerHz,
  1528. sample_rate: sampleRateHz,
  1529. fft_size: binCount,
  1530. spectrum_db: spectrum,
  1531. signals: signals,
  1532. debug: debug
  1533. };
  1534. }
  1535. function renderLoop() {
  1536. renderFrames += 1;
  1537. const now = performance.now();
  1538. if (now - lastFpsTs >= 1000) {
  1539. renderFps = (renderFrames * 1000) / (now - lastFpsTs);
  1540. renderFrames = 0;
  1541. lastFpsTs = now;
  1542. }
  1543. if (latest) {
  1544. renderBandNavigator();
  1545. renderSpectrum();
  1546. renderWaterfall();
  1547. renderOccupancy();
  1548. renderTimeline();
  1549. if (drawerEl.classList.contains('open')) renderDetailSpectrogram();
  1550. }
  1551. updateHeroMetrics();
  1552. requestAnimationFrame(renderLoop);
  1553. }
  1554. function handleSpectrumClick(ev) {
  1555. const rect = spectrumCanvas.getBoundingClientRect();
  1556. const x = (ev.clientX - rect.left) * (spectrumCanvas.width / rect.width);
  1557. const y = (ev.clientY - rect.top) * (spectrumCanvas.height / rect.height);
  1558. for (let i = liveSignalRects.length - 1; i >= 0; i--) {
  1559. const r = liveSignalRects[i];
  1560. if (x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h) {
  1561. const sig = r.signal;
  1562. const freq = sig.center_hz;
  1563. const bw = sig.bw_hz || 12000;
  1564. const mode = sig.class?.mod_type || '';
  1565. startLiveListen(freq, bw, mode);
  1566. window._selectedSignal = { freq, bw, mode };
  1567. // Update selected signal in list
  1568. signalList.querySelectorAll('.signal-item').forEach(el => {
  1569. const elFreq = parseFloat(el.dataset.center || '0');
  1570. el.classList.toggle('active', Math.abs(elFreq - freq) < Math.max(500, bw * 0.5));
  1571. });
  1572. return;
  1573. }
  1574. }
  1575. if (!latest) return;
  1576. const span = latest.sample_rate / zoom;
  1577. const startHz = latest.center_hz - span / 2 + pan * span;
  1578. const clickedHz = startHz + (x / spectrumCanvas.width) * span;
  1579. tuneToFrequency(clickedHz);
  1580. }
  1581. function handleNavPosition(ev) {
  1582. if (!latest) return;
  1583. const rect = navCanvas.getBoundingClientRect();
  1584. const x = Math.max(0, Math.min(rect.width, ev.clientX - rect.left));
  1585. const norm = x / rect.width;
  1586. const fullStart = latest.center_hz - latest.sample_rate / 2;
  1587. const newViewCenter = fullStart + norm * latest.sample_rate;
  1588. const span = latest.sample_rate / zoom;
  1589. const desiredPan = (newViewCenter - latest.center_hz) / span;
  1590. pan = Math.max(-0.5, Math.min(0.5, desiredPan));
  1591. followLive = false;
  1592. }
  1593. function exportSelectedEvent() {
  1594. const ev = eventsById.get(selectedEventId);
  1595. if (!ev) return;
  1596. const blob = new Blob([JSON.stringify(ev, null, 2)], { type: 'application/json' });
  1597. const a = document.createElement('a');
  1598. a.href = URL.createObjectURL(blob);
  1599. a.download = `event-${ev.id}.json`;
  1600. a.click();
  1601. URL.revokeObjectURL(a.href);
  1602. }
  1603. spectrumCanvas.addEventListener('wheel', (ev) => {
  1604. ev.preventDefault();
  1605. const direction = Math.sign(ev.deltaY);
  1606. zoom = Math.max(0.25, Math.min(24, zoom * (direction > 0 ? 1.12 : 0.89)));
  1607. followLive = false;
  1608. });
  1609. spectrumCanvas.addEventListener('mousedown', (ev) => {
  1610. isDraggingSpectrum = true;
  1611. dragStartX = ev.clientX;
  1612. dragStartPan = pan;
  1613. });
  1614. window.addEventListener('mouseup', () => {
  1615. isDraggingSpectrum = false;
  1616. navDrag = false;
  1617. });
  1618. spectrumCanvas.addEventListener('mouseleave', hideSignalPopover);
  1619. window.addEventListener('mousemove', (ev) => {
  1620. const rect = spectrumCanvas.getBoundingClientRect();
  1621. const x = (ev.clientX - rect.left) * (spectrumCanvas.width / rect.width);
  1622. const y = (ev.clientY - rect.top) * (spectrumCanvas.height / rect.height);
  1623. let hoverHit = null;
  1624. for (let i = liveSignalRects.length - 1; i >= 0; i--) {
  1625. const r = liveSignalRects[i];
  1626. if (x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h) {
  1627. hoverHit = r;
  1628. break;
  1629. }
  1630. }
  1631. if (hoverHit) {
  1632. hoveredSignal = hoverHit.signal;
  1633. renderSignalPopover(hoverHit, hoverHit.signal);
  1634. } else {
  1635. hideSignalPopover();
  1636. }
  1637. if (isDraggingSpectrum) {
  1638. const dx = ev.clientX - dragStartX;
  1639. pan = Math.max(-0.5, Math.min(0.5, dragStartPan - dx / spectrumCanvas.clientWidth));
  1640. followLive = false;
  1641. }
  1642. if (navDrag) handleNavPosition(ev);
  1643. });
  1644. spectrumCanvas.addEventListener('dblclick', fitView);
  1645. spectrumCanvas.addEventListener('click', handleSpectrumClick);
  1646. navCanvas.addEventListener('mousedown', (ev) => {
  1647. navDrag = true;
  1648. handleNavPosition(ev);
  1649. });
  1650. navCanvas.addEventListener('click', handleNavPosition);
  1651. centerInput.addEventListener('change', () => {
  1652. const mhz = parseFloat(centerInput.value);
  1653. if (Number.isFinite(mhz)) tuneToFrequency(fromMHz(mhz));
  1654. });
  1655. spanInput.addEventListener('change', () => {
  1656. const mhz = parseFloat(spanInput.value);
  1657. if (!Number.isFinite(mhz) || mhz <= 0) return;
  1658. const baseRate = currentConfig?.sample_rate || latest?.sample_rate;
  1659. if (!baseRate) return;
  1660. zoom = Math.max(0.25, Math.min(24, baseRate / fromMHz(mhz)));
  1661. followLive = false;
  1662. });
  1663. sampleRateSelect.addEventListener('change', () => {
  1664. const mhz = parseFloat(sampleRateSelect.value);
  1665. if (Number.isFinite(mhz)) queueConfigUpdate({ sample_rate: Math.round(fromMHz(mhz)) });
  1666. });
  1667. bwSelect.addEventListener('change', () => {
  1668. const bw = parseInt(bwSelect.value, 10);
  1669. if (Number.isFinite(bw)) queueConfigUpdate({ tuner_bw_khz: bw });
  1670. });
  1671. fftSelect.addEventListener('change', () => {
  1672. const size = parseInt(fftSelect.value, 10);
  1673. if (Number.isFinite(size)) queueConfigUpdate({ fft_size: size });
  1674. });
  1675. gainRange.addEventListener('input', () => {
  1676. gainInput.value = gainRange.value;
  1677. const uiVal = parseFloat(gainRange.value);
  1678. if (Number.isFinite(uiVal)) queueConfigUpdate({ gain_db: Math.max(0, Math.min(GAIN_MAX, GAIN_MAX - uiVal)) });
  1679. });
  1680. gainInput.addEventListener('change', () => {
  1681. const uiVal = parseFloat(gainInput.value);
  1682. if (Number.isFinite(uiVal)) {
  1683. gainRange.value = uiVal;
  1684. queueConfigUpdate({ gain_db: Math.max(0, Math.min(GAIN_MAX, GAIN_MAX - uiVal)) });
  1685. }
  1686. });
  1687. thresholdRange.addEventListener('input', () => {
  1688. thresholdInput.value = thresholdRange.value;
  1689. queueConfigUpdate({ detector: { threshold_db: parseFloat(thresholdRange.value) } });
  1690. });
  1691. thresholdInput.addEventListener('change', () => {
  1692. const v = parseFloat(thresholdInput.value);
  1693. if (Number.isFinite(v)) {
  1694. thresholdRange.value = v;
  1695. queueConfigUpdate({ detector: { threshold_db: v } });
  1696. }
  1697. });
  1698. if (cfarModeSelect) cfarModeSelect.addEventListener('change', () => {
  1699. queueConfigUpdate({ detector: { cfar_mode: cfarModeSelect.value } });
  1700. const rankRow = cfarRankInput?.closest('.field');
  1701. if (rankRow) rankRow.style.display = (cfarModeSelect.value === 'OS') ? '' : 'none';
  1702. });
  1703. if (cfarWrapToggle) cfarWrapToggle.addEventListener('change', () => {
  1704. queueConfigUpdate({ detector: { cfar_wrap_around: cfarWrapToggle.checked } });
  1705. });
  1706. if (cfarGuardHzInput) cfarGuardHzInput.addEventListener('change', () => {
  1707. const v = parseFloat(cfarGuardHzInput.value);
  1708. if (Number.isFinite(v) && v >= 0) queueConfigUpdate({ detector: { cfar_guard_hz: v } });
  1709. });
  1710. if (cfarTrainHzInput) cfarTrainHzInput.addEventListener('change', () => {
  1711. const v = parseFloat(cfarTrainHzInput.value);
  1712. if (Number.isFinite(v) && v > 0) queueConfigUpdate({ detector: { cfar_train_hz: v } });
  1713. });
  1714. if (cfarRankInput) cfarRankInput.addEventListener('change', () => {
  1715. const v = parseInt(cfarRankInput.value, 10);
  1716. if (Number.isFinite(v)) queueConfigUpdate({ detector: { cfar_rank: v } });
  1717. });
  1718. if (cfarScaleInput) cfarScaleInput.addEventListener('change', () => {
  1719. const v = parseFloat(cfarScaleInput.value);
  1720. if (Number.isFinite(v)) queueConfigUpdate({ detector: { cfar_scale_db: v } });
  1721. });
  1722. if (minDurationInput) minDurationInput.addEventListener('change', () => {
  1723. const v = parseInt(minDurationInput.value, 10);
  1724. if (Number.isFinite(v)) queueConfigUpdate({ detector: { min_duration_ms: v } });
  1725. });
  1726. if (holdInput) holdInput.addEventListener('change', () => {
  1727. const v = parseInt(holdInput.value, 10);
  1728. if (Number.isFinite(v)) queueConfigUpdate({ detector: { hold_ms: v } });
  1729. });
  1730. if (emaAlphaInput) emaAlphaInput.addEventListener('change', () => {
  1731. const v = parseFloat(emaAlphaInput.value);
  1732. if (Number.isFinite(v)) queueConfigUpdate({ detector: { ema_alpha: v } });
  1733. });
  1734. if (hysteresisInput) hysteresisInput.addEventListener('change', () => {
  1735. const v = parseFloat(hysteresisInput.value);
  1736. if (Number.isFinite(v)) queueConfigUpdate({ detector: { hysteresis_db: v } });
  1737. });
  1738. if (stableFramesInput) stableFramesInput.addEventListener('change', () => {
  1739. const v = parseInt(stableFramesInput.value, 10);
  1740. if (Number.isFinite(v)) queueConfigUpdate({ detector: { min_stable_frames: v } });
  1741. });
  1742. if (gapToleranceInput) gapToleranceInput.addEventListener('change', () => {
  1743. const v = parseInt(gapToleranceInput.value, 10);
  1744. if (Number.isFinite(v)) queueConfigUpdate({ detector: { gap_tolerance_ms: v } });
  1745. });
  1746. if (classifierModeSelect) classifierModeSelect.addEventListener('change', () => {
  1747. queueConfigUpdate({ classifier_mode: classifierModeSelect.value });
  1748. });
  1749. if (edgeMarginInput) edgeMarginInput.addEventListener('change', () => {
  1750. const v = parseFloat(edgeMarginInput.value);
  1751. if (Number.isFinite(v) && v >= 0) queueConfigUpdate({ detector: { edge_margin_db: v } });
  1752. });
  1753. if (mergeGapInput) mergeGapInput.addEventListener('change', () => {
  1754. const v = parseFloat(mergeGapInput.value);
  1755. if (Number.isFinite(v)) queueConfigUpdate({ detector: { merge_gap_hz: v } });
  1756. });
  1757. if (classHistoryInput) classHistoryInput.addEventListener('change', () => {
  1758. const v = parseInt(classHistoryInput.value, 10);
  1759. if (Number.isFinite(v) && v >= 1) queueConfigUpdate({ detector: { class_history_size: v } });
  1760. });
  1761. if (classSwitchInput) classSwitchInput.addEventListener('change', () => {
  1762. const v = parseFloat(classSwitchInput.value);
  1763. if (Number.isFinite(v) && v >= 0.1 && v <= 1.0) queueConfigUpdate({ detector: { class_switch_ratio: v } });
  1764. });
  1765. agcToggle.addEventListener('change', () => queueSettingsUpdate({ agc: agcToggle.checked }));
  1766. dcToggle.addEventListener('change', () => queueSettingsUpdate({ dc_block: dcToggle.checked }));
  1767. iqToggle.addEventListener('change', () => queueSettingsUpdate({ iq_balance: iqToggle.checked }));
  1768. gpuToggle.addEventListener('change', () => queueConfigUpdate({ use_gpu_fft: gpuToggle.checked }));
  1769. if (recEnableToggle) recEnableToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { enabled: recEnableToggle.checked } }));
  1770. if (recIQToggle) recIQToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { record_iq: recIQToggle.checked } }));
  1771. if (recAudioToggle) recAudioToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { record_audio: recAudioToggle.checked } }));
  1772. if (recDemodToggle) recDemodToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { auto_demod: recDemodToggle.checked } }));
  1773. if (recDecodeToggle) recDecodeToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { auto_decode: recDecodeToggle.checked } }));
  1774. if (recMinSNR) recMinSNR.addEventListener('change', () => queueConfigUpdate({ recorder: { min_snr_db: parseFloat(recMinSNR.value) } }));
  1775. if (recMaxDisk) recMaxDisk.addEventListener('change', () => queueConfigUpdate({ recorder: { max_disk_mb: parseInt(recMaxDisk.value || '0', 10) } }));
  1776. if (recClassFilter) recClassFilter.addEventListener('change', () => {
  1777. const list = (recClassFilter.value || '')
  1778. .split(',')
  1779. .map(s => s.trim())
  1780. .filter(Boolean);
  1781. queueConfigUpdate({ recorder: { class_filter: list } });
  1782. });
  1783. if (refineAutoSpan) refineAutoSpan.addEventListener('change', () => {
  1784. queueConfigUpdate({ refinement: { auto_span: refineAutoSpan.value === 'true' } });
  1785. });
  1786. if (refineMinSpan) refineMinSpan.addEventListener('change', () => {
  1787. const v = parseFloat(refineMinSpan.value);
  1788. if (Number.isFinite(v)) queueConfigUpdate({ refinement: { min_span_hz: v } });
  1789. });
  1790. if (refineMaxSpan) refineMaxSpan.addEventListener('change', () => {
  1791. const v = parseFloat(refineMaxSpan.value);
  1792. if (Number.isFinite(v)) queueConfigUpdate({ refinement: { max_span_hz: v } });
  1793. });
  1794. avgSelect.addEventListener('change', () => {
  1795. avgAlpha = parseFloat(avgSelect.value) || 0;
  1796. resetProcessingCaches();
  1797. });
  1798. maxHoldToggle.addEventListener('change', () => {
  1799. maxHold = maxHoldToggle.checked;
  1800. maxSpectrum = null;
  1801. markSpectrumDirty();
  1802. });
  1803. if (debugOverlayToggle) debugOverlayToggle.addEventListener('change', () => {
  1804. showDebugOverlay = debugOverlayToggle.checked;
  1805. localStorage.setItem('spectre.debugOverlay', showDebugOverlay ? '1' : '0');
  1806. markSpectrumDirty();
  1807. updateHeroMetrics();
  1808. });
  1809. resetMaxBtn.addEventListener('click', () => {
  1810. maxSpectrum = null;
  1811. markSpectrumDirty();
  1812. });
  1813. followBtn.addEventListener('click', () => { followLive = true; pan = 0; });
  1814. fitBtn.addEventListener('click', fitView);
  1815. timelineFollowBtn.addEventListener('click', () => { timelineFrozen = false; });
  1816. timelineFreezeBtn.addEventListener('click', () => {
  1817. timelineFrozen = !timelineFrozen;
  1818. timelineFreezeBtn.textContent = timelineFrozen ? 'Frozen' : 'Freeze';
  1819. });
  1820. presetButtons.forEach((btn) => {
  1821. btn.addEventListener('click', () => {
  1822. const mhz = parseFloat(btn.dataset.center);
  1823. if (Number.isFinite(mhz)) tuneToFrequency(fromMHz(mhz));
  1824. });
  1825. });
  1826. railTabs.forEach((tab) => {
  1827. tab.addEventListener('click', () => {
  1828. railTabs.forEach(t => t.classList.toggle('active', t === tab));
  1829. tabPanels.forEach(panel => panel.classList.toggle('active', panel.dataset.panel === tab.dataset.tab));
  1830. });
  1831. });
  1832. modeButtons.forEach((btn) => {
  1833. btn.addEventListener('click', () => {
  1834. modeButtons.forEach(b => b.classList.toggle('active', b === btn));
  1835. document.body.classList.remove('mode-live', 'mode-hunt', 'mode-review', 'mode-lab');
  1836. document.body.classList.add(`mode-${btn.dataset.mode}`);
  1837. });
  1838. });
  1839. document.body.classList.add('mode-live');
  1840. drawerCloseBtn.addEventListener('click', closeDrawer);
  1841. exportEventBtn.addEventListener('click', exportSelectedEvent);
  1842. if (liveListenEventBtn) {
  1843. liveListenEventBtn.addEventListener('click', () => {
  1844. const ev = eventsById.get(selectedEventId);
  1845. if (!ev) return;
  1846. // Toggle off if already listening
  1847. if (liveListenWS && liveListenWS.playing) {
  1848. stopLiveListen();
  1849. return;
  1850. }
  1851. const freq = ev.center_hz;
  1852. const bw = ev.bandwidth_hz || 12000;
  1853. const mode = ev.class?.mod_type || 'NFM';
  1854. startLiveListen(freq, bw, mode);
  1855. });
  1856. }
  1857. if (decodeEventBtn) {
  1858. decodeEventBtn.addEventListener('click', async () => {
  1859. const ev = eventsById.get(selectedEventId);
  1860. if (!ev) return;
  1861. if (!recordingMetaEl) return;
  1862. const rec = recordings.find(r => r.event_id === ev.id) || recordings.find(r => r.center_hz === ev.center_hz);
  1863. if (!rec) {
  1864. decodeResultEl.textContent = 'Decode: no recording';
  1865. return;
  1866. }
  1867. const mode = decodeModeSelect?.value || ev.class?.mod_type || 'FT8';
  1868. const res = await fetch(`/api/recordings/${rec.id}/decode?mode=${mode}`);
  1869. if (!res.ok) {
  1870. decodeResultEl.textContent = 'Decode: failed';
  1871. return;
  1872. }
  1873. const data = await res.json();
  1874. decodeResultEl.textContent = `Decode: ${String(data.stdout || '').slice(0, 80)}`;
  1875. });
  1876. }
  1877. jumpToEventBtn.addEventListener('click', () => {
  1878. const ev = eventsById.get(selectedEventId);
  1879. if (!ev) return;
  1880. tuneToFrequency(ev.center_hz);
  1881. });
  1882. timelineCanvas.addEventListener('click', (ev) => {
  1883. const rect = timelineCanvas.getBoundingClientRect();
  1884. const x = (ev.clientX - rect.left) * (timelineCanvas.width / rect.width);
  1885. const y = (ev.clientY - rect.top) * (timelineCanvas.height / rect.height);
  1886. for (let i = timelineRects.length - 1; i >= 0; i--) {
  1887. const r = timelineRects[i];
  1888. if (x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h) {
  1889. openDrawer(eventsById.get(r.id));
  1890. return;
  1891. }
  1892. }
  1893. });
  1894. signalList.addEventListener('click', (ev) => {
  1895. const target = ev.target.closest('.signal-item');
  1896. if (!target) return;
  1897. // Select this signal for live listening — don't retune the SDR
  1898. const allItems = signalList.querySelectorAll('.signal-item');
  1899. allItems.forEach(el => el.classList.remove('active'));
  1900. target.classList.add('active');
  1901. // Store selected signal data for Live Listen button
  1902. window._selectedSignal = {
  1903. freq: parseFloat(target.dataset.center),
  1904. bw: parseFloat(target.dataset.bw || '12000'),
  1905. mode: target.dataset.class || ''
  1906. };
  1907. });
  1908. if (liveListenBtn) {
  1909. liveListenBtn.addEventListener('click', async () => {
  1910. // Toggle: if already listening, stop
  1911. if (liveListenWS && liveListenWS.playing) {
  1912. stopLiveListen();
  1913. return;
  1914. }
  1915. // Use selected signal if available, otherwise first in list
  1916. let freq, bw, mode;
  1917. if (window._selectedSignal) {
  1918. freq = window._selectedSignal.freq;
  1919. bw = window._selectedSignal.bw;
  1920. mode = window._selectedSignal.mode;
  1921. } else {
  1922. const first = signalList.querySelector('.signal-item');
  1923. if (!first) return;
  1924. freq = parseFloat(first.dataset.center);
  1925. bw = parseFloat(first.dataset.bw || '12000');
  1926. mode = first.dataset.class || '';
  1927. }
  1928. if (!Number.isFinite(freq)) return;
  1929. startLiveListen(freq, bw, mode);
  1930. });
  1931. }
  1932. eventList.addEventListener('click', (ev) => {
  1933. const target = ev.target.closest('.event-item');
  1934. if (!target) return;
  1935. const id = target.dataset.eventId;
  1936. openDrawer(eventsById.get(id));
  1937. });
  1938. if (recordingList) {
  1939. recordingList.addEventListener('click', async (ev) => {
  1940. const target = ev.target.closest('.recording-item');
  1941. if (!target) return;
  1942. const id = target.dataset.id;
  1943. const audio = new Audio(`/api/recordings/${id}/audio`);
  1944. audio.play();
  1945. if (recordingMetaEl) recordingMetaEl.textContent = `Recording: ${id}`;
  1946. if (recordingMetaLink) {
  1947. recordingMetaLink.href = `/api/recordings/${id}`;
  1948. recordingIQLink.href = `/api/recordings/${id}/iq`;
  1949. recordingAudioLink.href = `/api/recordings/${id}/audio`;
  1950. }
  1951. try {
  1952. const res = await fetch(`/api/recordings/${id}`);
  1953. if (!res.ok) return;
  1954. const meta = await res.json();
  1955. if (decodeResultEl) {
  1956. const rds = meta.rds_ps ? `RDS: ${meta.rds_ps}` : '';
  1957. decodeResultEl.textContent = `Decode: ${rds}`;
  1958. }
  1959. if (classifierScoresEl) {
  1960. const scores = meta.classification?.scores;
  1961. if (scores && typeof scores === 'object') {
  1962. const rows = Object.entries(scores)
  1963. .sort((a, b) => b[1] - a[1])
  1964. .slice(0, 6)
  1965. .map(([k, v]) => `${k}:${v.toFixed(2)}`)
  1966. .join(' · ');
  1967. classifierScoresEl.textContent = rows ? `Classifier scores: ${rows}` : 'Classifier scores: -';
  1968. } else {
  1969. classifierScoresEl.textContent = 'Classifier scores: -';
  1970. }
  1971. }
  1972. } catch {}
  1973. });
  1974. }
  1975. if (debugOverlayToggle) debugOverlayToggle.checked = showDebugOverlay;
  1976. window.addEventListener('keydown', (ev) => {
  1977. if (ev.target && ['INPUT', 'SELECT', 'TEXTAREA'].includes(ev.target.tagName)) return;
  1978. if (ev.key === ' ') {
  1979. ev.preventDefault();
  1980. followLive = true;
  1981. pan = 0;
  1982. } else if (ev.key.toLowerCase() === 'f') {
  1983. fitView();
  1984. } else if (ev.key.toLowerCase() === 'm') {
  1985. maxHold = !maxHold;
  1986. maxHoldToggle.checked = maxHold;
  1987. if (!maxHold) maxSpectrum = null;
  1988. markSpectrumDirty();
  1989. } else if (ev.key.toLowerCase() === 'g') {
  1990. gpuToggle.checked = !gpuToggle.checked;
  1991. queueConfigUpdate({ use_gpu_fft: gpuToggle.checked });
  1992. } else if (ev.key === '[') {
  1993. zoom = Math.max(0.25, zoom * 0.88);
  1994. } else if (ev.key === ']') {
  1995. zoom = Math.min(24, zoom * 1.12);
  1996. } else if (ev.key === 'ArrowLeft') {
  1997. pan = Math.max(-0.5, pan - 0.04);
  1998. followLive = false;
  1999. } else if (ev.key === 'ArrowRight') {
  2000. pan = Math.min(0.5, pan + 0.04);
  2001. followLive = false;
  2002. }
  2003. });
  2004. loadConfig();
  2005. loadStats();
  2006. loadGPU();
  2007. loadRefinement();
  2008. fetchEvents(true);
  2009. fetchRecordings();
  2010. loadDecoders();
  2011. connect();
  2012. requestAnimationFrame(renderLoop);
  2013. setInterval(loadStats, 1000);
  2014. setInterval(loadGPU, 1000);
  2015. setInterval(loadRefinement, 1500);
  2016. setInterval(() => fetchEvents(false), 2000);
  2017. setInterval(fetchRecordings, 5000);
  2018. setInterval(loadSignals, 1500);
  2019. setInterval(loadDecoders, 10000);