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.

2113 líneas
75KB

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