Wideband autonomous SDR analysis engine forked from sdr-visual-suite
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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