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

2723 líneas
98KB

  1. const qs = (id) => document.getElementById(id);
  2. const navCanvas = qs('navCanvas');
  3. const spectrumCanvas = qs('spectrum');
  4. const waterfallCanvas = qs('waterfall');
  5. const occupancyCanvas = qs('occupancy');
  6. const timelineCanvas = qs('timeline');
  7. const detailSpectrogram = qs('detailSpectrogram');
  8. const signalPopover = qs('signalPopover');
  9. const wsBadge = qs('wsBadge');
  10. const metaLine = qs('metaLine');
  11. const heroSubtitle = qs('heroSubtitle');
  12. const configStatusEl = qs('configStatus');
  13. const timelineRangeEl = qs('timelineRange');
  14. const metricCenter = qs('metricCenter');
  15. const metricSpan = qs('metricSpan');
  16. const metricRes = qs('metricRes');
  17. const metricSignals = qs('metricSignals');
  18. const metricGpu = qs('metricGpu');
  19. const metricSource = qs('metricSource');
  20. const centerInput = qs('centerInput');
  21. const spanInput = qs('spanInput');
  22. const sampleRateSelect = qs('sampleRateSelect');
  23. const bwSelect = qs('bwSelect');
  24. const fftSelect = qs('fftSelect');
  25. const gainRange = qs('gainRange');
  26. const gainInput = qs('gainInput');
  27. const thresholdRange = qs('thresholdRange');
  28. const thresholdInput = qs('thresholdInput');
  29. const cfarModeSelect = qs('cfarModeSelect');
  30. const cfarWrapToggle = qs('cfarWrapToggle');
  31. const cfarGuardHzInput = qs('cfarGuardHzInput');
  32. const cfarTrainHzInput = qs('cfarTrainHzInput');
  33. const cfarRankInput = qs('cfarRankInput');
  34. const classifierModeSelect = qs('classifierModeSelect');
  35. const edgeMarginInput = qs('edgeMarginInput');
  36. const mergeGapInput = qs('mergeGapInput');
  37. const classHistoryInput = qs('classHistoryInput');
  38. const classSwitchInput = qs('classSwitchInput');
  39. const cfarScaleInput = qs('cfarScaleInput');
  40. const minDurationInput = qs('minDurationInput');
  41. const holdInput = qs('holdInput');
  42. const emaAlphaInput = qs('emaAlphaInput');
  43. const hysteresisInput = qs('hysteresisInput');
  44. const stableFramesInput = qs('stableFramesInput');
  45. const gapToleranceInput = qs('gapToleranceInput');
  46. const agcToggle = qs('agcToggle');
  47. const dcToggle = qs('dcToggle');
  48. const iqToggle = qs('iqToggle');
  49. const avgSelect = qs('avgSelect');
  50. const maxHoldToggle = qs('maxHoldToggle');
  51. const gpuToggle = qs('gpuToggle');
  52. const recEnableToggle = qs('recEnableToggle');
  53. const recIQToggle = qs('recIQToggle');
  54. const recAudioToggle = qs('recAudioToggle');
  55. const recDemodToggle = qs('recDemodToggle');
  56. const recDecodeToggle = qs('recDecodeToggle');
  57. const recMinSNR = qs('recMinSNR');
  58. const recMaxDisk = qs('recMaxDisk');
  59. const recClassFilter = qs('recClassFilter');
  60. const refineAutoSpan = qs('refineAutoSpan');
  61. const refineMinSpan = qs('refineMinSpan');
  62. const refineMaxSpan = qs('refineMaxSpan');
  63. const resMaxRefine = qs('resMaxRefine');
  64. const resMaxRecord = qs('resMaxRecord');
  65. const resMaxDecode = qs('resMaxDecode');
  66. const resDecisionHold = qs('resDecisionHold');
  67. const signalList = qs('signalList');
  68. const signalDecisionSummary = qs('signalDecisionSummary');
  69. const signalQueueSummary = qs('signalQueueSummary');
  70. const eventList = qs('eventList');
  71. const recordingList = qs('recordingList');
  72. const signalCountBadge = qs('signalCountBadge');
  73. const eventCountBadge = qs('eventCountBadge');
  74. const recordingCountBadge = qs('recordingCountBadge');
  75. const signalSummaryLine = qs('signalSummaryLine');
  76. const healthBuffer = qs('healthBuffer');
  77. const healthDropped = qs('healthDropped');
  78. const healthResets = qs('healthResets');
  79. const healthAge = qs('healthAge');
  80. const healthGpu = qs('healthGpu');
  81. const healthFps = qs('healthFps');
  82. const healthRefinePlan = qs('healthRefinePlan');
  83. const healthRefineWindows = qs('healthRefineWindows');
  84. const healthWs = qs('healthWs');
  85. const healthApi = qs('healthApi');
  86. const healthConfig = qs('healthConfig');
  87. const healthRefine = qs('healthRefine');
  88. const healthTelemetry = qs('healthTelemetry');
  89. const healthSource = qs('healthSource');
  90. const refineDetails = qs('refineDetails');
  91. const telemetryEventList = qs('telemetryEventList');
  92. const policySummaryList = qs('policySummaryList');
  93. const policyRecommendationList = qs('policyRecommendationList');
  94. const drawerEl = qs('eventDrawer');
  95. const drawerCloseBtn = qs('drawerClose');
  96. const detailSubtitle = qs('detailSubtitle');
  97. const detailCenterEl = qs('detailCenter');
  98. const detailBwEl = qs('detailBw');
  99. const detailStartEl = qs('detailStart');
  100. const detailEndEl = qs('detailEnd');
  101. const detailSnrEl = qs('detailSnr');
  102. const detailDurEl = qs('detailDur');
  103. const detailClassEl = qs('detailClass');
  104. const jumpToEventBtn = qs('jumpToEventBtn');
  105. const exportEventBtn = qs('exportEventBtn');
  106. const liveListenEventBtn = qs('liveListenEventBtn');
  107. const decodeEventBtn = qs('decodeEventBtn');
  108. const decodeModeSelect = qs('decodeMode');
  109. const recordingMetaEl = qs('recordingMeta');
  110. const decodeResultEl = qs('decodeResult');
  111. const classifierScoresEl = qs('classifierScores');
  112. const classifierScoreBarsEl = qs('classifierScoreBars');
  113. const recordingMetaLink = qs('recordingMetaLink');
  114. const recordingIQLink = qs('recordingIQLink');
  115. const recordingAudioLink = qs('recordingAudioLink');
  116. const followBtn = qs('followBtn');
  117. const fitBtn = qs('fitBtn');
  118. const resetMaxBtn = qs('resetMaxBtn');
  119. const debugOverlayToggle = qs('debugOverlayToggle');
  120. const timelineFollowBtn = qs('timelineFollowBtn');
  121. const timelineFreezeBtn = qs('timelineFreezeBtn');
  122. const modeButtons = Array.from(document.querySelectorAll('.mode-btn'));
  123. const railTabs = Array.from(document.querySelectorAll('.rail-tab'));
  124. const tabPanels = Array.from(document.querySelectorAll('.tab-panel'));
  125. const presetButtons = Array.from(document.querySelectorAll('.preset-btn'));
  126. const liveListenBtn = qs('liveListenBtn');
  127. const listenSecondsInput = qs('listenSeconds');
  128. const listenModeSelect = qs('listenMode');
  129. const listenMetaDemod = qs('listenMetaDemod');
  130. const listenMetaPlayback = qs('listenMetaPlayback');
  131. const listenMetaStereo = qs('listenMetaStereo');
  132. const listenMetaStatus = qs('listenMetaStatus');
  133. const listenMetaAudio = qs('listenMetaAudio');
  134. let latest = null;
  135. let currentConfig = null;
  136. let liveAudio = null;
  137. let liveListenWS = null; // WebSocket-based live listen
  138. let liveListenTarget = null; // { freq, bw, mode }
  139. let liveListenInfo = null;
  140. let stats = { buffer_samples: 0, dropped: 0, resets: 0, last_sample_ago_ms: -1 };
  141. let refinementInfo = {};
  142. let decisionIndex = new Map();
  143. let telemetryLive = null;
  144. let policyInfo = null;
  145. let policyRecommendations = null;
  146. let wsState = 'init';
  147. let wsLastMessageTs = 0;
  148. let apiState = { ok: false, latencyMs: null, lastOkTs: 0, lastError: '' };
  149. const apiClient = window.SpectreApi?.createClient
  150. ? window.SpectreApi.createClient({ timeoutMs: 4500 })
  151. : null;
  152. const operatorPanel = window.OperatorPanel?.create
  153. ? window.OperatorPanel.create({
  154. healthWs,
  155. healthApi,
  156. healthConfig,
  157. healthRefine,
  158. healthTelemetry,
  159. healthSource,
  160. refineDetails,
  161. telemetryEvents: telemetryEventList
  162. })
  163. : null;
  164. // ---------------------------------------------------------------------------
  165. // LiveListenWS — WebSocket-based gapless audio streaming via /ws/audio
  166. // ---------------------------------------------------------------------------
  167. // v4: Jank-resistant scheduled playback.
  168. //
  169. // Problem: Main-thread Canvas rendering blocks for 150-250ms, starving
  170. // ScriptProcessorNode callbacks and causing audio underruns.
  171. // AudioWorklet would fix this but requires Secure Context (HTTPS/localhost).
  172. //
  173. // Solution: Use BufferSource scheduling (like v1) but with a much larger
  174. // jitter budget. We pre-schedule audio 400ms into the future so that even
  175. // a 300ms main-thread hang doesn't cause a gap. The AudioContext's internal
  176. // scheduling is sample-accurate and runs on a system thread — once a
  177. // BufferSource is scheduled, it plays regardless of main-thread state.
  178. //
  179. // Key differences from v1:
  180. // - 400ms target latency (was 100ms) — survives observed 250ms hangs
  181. // - Soft resync: on underrun, schedule next chunk with a short crossfade
  182. // gap instead of hard jump
  183. // - Overrun cap at 800ms (was 500ms)
  184. // - Chunk coalescing: merge small chunks to reduce scheduling overhead
  185. // ---------------------------------------------------------------------------
  186. class LiveListenWS {
  187. constructor(freq, bw, mode) {
  188. this.freq = freq;
  189. this.bw = bw;
  190. this.mode = mode;
  191. this.ws = null;
  192. this.audioCtx = null;
  193. this.sampleRate = 48000;
  194. this.channels = 1;
  195. this.playing = false;
  196. this.nextTime = 0;
  197. this.started = false;
  198. this._onStop = null;
  199. // Chunk coalescing buffer
  200. this._pendingSamples = [];
  201. this._pendingLen = 0;
  202. this._flushTimer = 0;
  203. // Fade state for soft resync
  204. this._lastEndSample = null; // last sample value per channel for crossfade
  205. }
  206. start() {
  207. const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
  208. const url = `${proto}//${location.host}/ws/audio?freq=${this.freq}&bw=${this.bw}&mode=${this.mode || ''}`;
  209. this.ws = new WebSocket(url);
  210. this.ws.binaryType = 'arraybuffer';
  211. this.playing = true;
  212. this.ws.onmessage = (ev) => {
  213. if (typeof ev.data === 'string') {
  214. try {
  215. const info = JSON.parse(ev.data);
  216. handleLiveListenAudioInfo(info);
  217. const hasRate = Number.isFinite(info.sample_rate) && info.sample_rate > 0;
  218. const hasCh = Number.isFinite(info.channels) && info.channels > 0;
  219. if (hasRate || hasCh) {
  220. const newRate = hasRate ? info.sample_rate : this.sampleRate;
  221. const newCh = hasCh ? info.channels : this.channels;
  222. if (newRate !== this.sampleRate || newCh !== this.channels) {
  223. this.sampleRate = newRate;
  224. this.channels = newCh;
  225. this._teardownAudio();
  226. }
  227. this._initAudio();
  228. }
  229. } catch (e) { /* ignore */ }
  230. return;
  231. }
  232. if (!this.audioCtx || !this.playing) return;
  233. this._onPCM(ev.data);
  234. };
  235. this.ws.onclose = () => {
  236. this.playing = false;
  237. if (this._onStop) this._onStop();
  238. };
  239. this.ws.onerror = () => {
  240. this.playing = false;
  241. if (this._onStop) this._onStop();
  242. };
  243. setTimeout(() => {
  244. if (!this.audioCtx && this.playing) this._initAudio();
  245. }, 500);
  246. }
  247. stop() {
  248. this.playing = false;
  249. if (this.ws) { this.ws.close(); this.ws = null; }
  250. this._teardownAudio();
  251. }
  252. onStop(fn) { this._onStop = fn; }
  253. _teardownAudio() {
  254. if (this._flushTimer) { clearTimeout(this._flushTimer); this._flushTimer = 0; }
  255. if (this.audioCtx) { this.audioCtx.close().catch(() => {}); this.audioCtx = null; }
  256. this.nextTime = 0;
  257. this.started = false;
  258. this._pendingSamples = [];
  259. this._pendingLen = 0;
  260. this._lastEndSample = null;
  261. }
  262. _initAudio() {
  263. if (this.audioCtx) return;
  264. this.audioCtx = new (window.AudioContext || window.webkitAudioContext)({
  265. sampleRate: this.sampleRate
  266. });
  267. this.audioCtx.resume().catch(() => {});
  268. this.nextTime = 0;
  269. this.started = false;
  270. this._lastEndSample = null;
  271. }
  272. _onPCM(buf) {
  273. // Coalesce small chunks: accumulate until we have >= 40ms or 50ms passes.
  274. // This reduces BufferSource scheduling overhead from ~12/sec to ~6/sec
  275. // and produces larger, more stable buffers.
  276. this._pendingSamples.push(new Int16Array(buf));
  277. this._pendingLen += buf.byteLength / 2; // Int16 = 2 bytes
  278. const minFrames = Math.ceil(this.sampleRate * 0.04); // 40ms worth
  279. const haveFrames = Math.floor(this._pendingLen / this.channels);
  280. if (haveFrames >= minFrames) {
  281. this._flushPending();
  282. } else if (!this._flushTimer) {
  283. // Flush after 50ms even if we don't have enough (prevents stale data)
  284. this._flushTimer = setTimeout(() => {
  285. this._flushTimer = 0;
  286. if (this._pendingLen > 0) this._flushPending();
  287. }, 50);
  288. }
  289. }
  290. _flushPending() {
  291. if (this._flushTimer) { clearTimeout(this._flushTimer); this._flushTimer = 0; }
  292. if (this._pendingSamples.length === 0) return;
  293. // Merge all pending into one Int16Array
  294. const total = this._pendingLen;
  295. const merged = new Int16Array(total);
  296. let off = 0;
  297. for (const chunk of this._pendingSamples) {
  298. merged.set(chunk, off);
  299. off += chunk.length;
  300. }
  301. this._pendingSamples = [];
  302. this._pendingLen = 0;
  303. this._scheduleChunk(merged);
  304. }
  305. _scheduleChunk(samples) {
  306. const ctx = this.audioCtx;
  307. if (!ctx) return;
  308. if (ctx.state === 'suspended') ctx.resume().catch(() => {});
  309. const nFrames = Math.floor(samples.length / this.channels);
  310. if (nFrames === 0) return;
  311. const audioBuffer = ctx.createBuffer(this.channels, nFrames, this.sampleRate);
  312. // Decode interleaved s16le → per-channel float32
  313. for (let ch = 0; ch < this.channels; ch++) {
  314. const data = audioBuffer.getChannelData(ch);
  315. for (let i = 0; i < nFrames; i++) {
  316. data[i] = samples[i * this.channels + ch] / 32768;
  317. }
  318. }
  319. const now = ctx.currentTime;
  320. // Target latency: 400ms. This means we schedule audio to play 400ms
  321. // from now. Even if the main thread hangs for 300ms, the already-
  322. // scheduled BufferSources continue playing on the system audio thread.
  323. const targetLatency = 0.4;
  324. // Max buffered: 900ms. Drop chunks if we're too far ahead.
  325. const maxBuffered = 0.9;
  326. if (!this.started || this.nextTime < now) {
  327. // First chunk or underrun.
  328. // Apply fade-in to avoid click at resync point.
  329. const fadeIn = Math.min(64, nFrames);
  330. for (let ch = 0; ch < this.channels; ch++) {
  331. const data = audioBuffer.getChannelData(ch);
  332. for (let i = 0; i < fadeIn; i++) {
  333. data[i] *= i / fadeIn;
  334. }
  335. }
  336. this.nextTime = now + targetLatency;
  337. this.started = true;
  338. }
  339. if (this.nextTime > now + maxBuffered) {
  340. // Too much buffered — drop to cap latency
  341. return;
  342. }
  343. const source = ctx.createBufferSource();
  344. source.buffer = audioBuffer;
  345. source.connect(ctx.destination);
  346. source.start(this.nextTime);
  347. this.nextTime += audioBuffer.duration;
  348. }
  349. }
  350. const liveListenDefaults = {
  351. status: 'Idle',
  352. demod: '-',
  353. playback_mode: '-',
  354. stereo_state: '-',
  355. sample_rate: null,
  356. channels: null
  357. };
  358. function formatListenMetaValue(value, fallback = '-') {
  359. if (value === undefined || value === null || value === '') return fallback;
  360. return String(value);
  361. }
  362. function isListeningSignal(signal) {
  363. return !!(signal && liveListenTarget && matchesListenTarget(signal));
  364. }
  365. function getSignalPrimaryMode(signal) {
  366. if (isListeningSignal(signal) && liveListenInfo?.playback_mode && liveListenInfo.playback_mode !== '-') {
  367. return liveListenInfo.playback_mode;
  368. }
  369. if (signal?.playback_mode) return signal.playback_mode;
  370. if (signal?.demod) return signal.demod;
  371. if (signal?.class?.mod_type) return signal.class.mod_type;
  372. return 'carrier';
  373. }
  374. function getSignalRuntimeSummary(signal) {
  375. const bits = [];
  376. if (isListeningSignal(signal)) {
  377. if (liveListenInfo?.stereo_state && liveListenInfo.stereo_state !== '-') bits.push(liveListenInfo.stereo_state);
  378. if (liveListenInfo?.demod && liveListenInfo.demod !== getSignalPrimaryMode(signal)) bits.push(liveListenInfo.demod);
  379. if (liveListenInfo?.status && !['Idle', '-', 'Live'].includes(liveListenInfo.status)) bits.push(liveListenInfo.status);
  380. if (bits.length) return bits.join(' · ');
  381. }
  382. if (signal?.stereo_state) bits.push(signal.stereo_state);
  383. if (signal?.demod && signal.demod !== getSignalPrimaryMode(signal)) bits.push(signal.demod);
  384. return bits.join(' · ');
  385. }
  386. function getSignalAudioSummary(signal) {
  387. if (!isListeningSignal(signal)) return '';
  388. const rate = Number.isFinite(liveListenInfo?.sample_rate) && liveListenInfo.sample_rate > 0 ? fmtHz(liveListenInfo.sample_rate) : '';
  389. const ch = Number.isFinite(liveListenInfo?.channels) && liveListenInfo.channels > 0 ? `${liveListenInfo.channels} ch` : '';
  390. return [rate, ch].filter(Boolean).join(' · ');
  391. }
  392. function renderLiveListenMeta(info) {
  393. if (!listenMetaDemod) return;
  394. const status = formatListenMetaValue(info?.status, 'Idle');
  395. const demod = formatListenMetaValue(info?.demod);
  396. const playback = formatListenMetaValue(info?.playback_mode);
  397. const stereo = formatListenMetaValue(info?.stereo_state);
  398. const sampleRate = Number.isFinite(info?.sample_rate) && info.sample_rate > 0
  399. ? fmtHz(info.sample_rate)
  400. : '-';
  401. const channels = Number.isFinite(info?.channels) && info.channels > 0
  402. ? `${info.channels} ch`
  403. : '-';
  404. if (listenMetaStatus) listenMetaStatus.textContent = status;
  405. listenMetaPlayback.textContent = playback;
  406. listenMetaStereo.textContent = stereo;
  407. listenMetaDemod.textContent = `Demod ${demod}`;
  408. if (listenMetaAudio) listenMetaAudio.textContent = `Audio ${sampleRate}${channels !== '-' ? ` · ${channels}` : ''}`;
  409. }
  410. function resetLiveListenMeta() {
  411. liveListenInfo = { ...liveListenDefaults };
  412. renderLiveListenMeta(liveListenInfo);
  413. }
  414. function updateLiveListenMeta(partial) {
  415. liveListenInfo = { ...(liveListenInfo || liveListenDefaults), ...partial };
  416. renderLiveListenMeta(liveListenInfo);
  417. }
  418. function handleLiveListenAudioInfo(info) {
  419. if (!info || typeof info !== 'object') return;
  420. const partial = { status: 'Live' };
  421. if (info.demod) partial.demod = info.demod;
  422. if (info.playback_mode) partial.playback_mode = info.playback_mode;
  423. if (info.stereo_state) partial.stereo_state = info.stereo_state;
  424. if (Number.isFinite(info.sample_rate)) partial.sample_rate = info.sample_rate;
  425. if (Number.isFinite(info.channels)) partial.channels = info.channels;
  426. if (Object.keys(partial).length > 0) {
  427. updateLiveListenMeta(partial);
  428. }
  429. }
  430. function resolveListenMode(detectedMode) {
  431. const manual = listenModeSelect?.value || '';
  432. if (manual) return manual;
  433. return detectedMode || 'NFM';
  434. }
  435. function syncListeningVisuals() {
  436. signalList?.querySelectorAll('.signal-item').forEach(el => {
  437. const center = parseFloat(el.dataset.center || '0');
  438. const bw = parseFloat(el.dataset.bw || '0');
  439. const fakeSignal = { center_hz: center, bw_hz: bw };
  440. el.classList.toggle('listening', matchesListenTarget(fakeSignal));
  441. });
  442. }
  443. function setLiveListenUI(active) {
  444. if (liveListenBtn) {
  445. liveListenBtn.textContent = active ? '■ Stop' : 'Live Listen';
  446. liveListenBtn.classList.toggle('active', active);
  447. }
  448. if (liveListenEventBtn) {
  449. liveListenEventBtn.textContent = active ? '■ Stop' : 'Listen';
  450. liveListenEventBtn.classList.toggle('active', active);
  451. }
  452. }
  453. function stopLiveListen() {
  454. if (liveListenWS) {
  455. liveListenWS.onStop(() => {});
  456. liveListenWS.stop();
  457. liveListenWS = null;
  458. }
  459. liveListenTarget = null;
  460. setLiveListenUI(false);
  461. resetLiveListenMeta();
  462. syncListeningVisuals();
  463. }
  464. function startLiveListen(freq, bw, detectedMode) {
  465. if (!Number.isFinite(freq)) return;
  466. const mode = resolveListenMode(detectedMode);
  467. const width = Number.isFinite(bw) && bw > 0 ? bw : 12000;
  468. // Stop any old HTTP audio
  469. if (liveAudio) { liveAudio.pause(); liveAudio = null; }
  470. // Switch on the fly if already listening
  471. if (liveListenWS) {
  472. liveListenWS.onStop(() => {});
  473. liveListenWS.stop();
  474. liveListenWS = null;
  475. }
  476. liveListenTarget = { freq, bw: width, mode };
  477. liveListenWS = new LiveListenWS(freq, width, mode);
  478. liveListenWS.onStop(() => {
  479. liveListenWS = null;
  480. liveListenTarget = null;
  481. setLiveListenUI(false);
  482. resetLiveListenMeta();
  483. });
  484. liveListenWS.start();
  485. setLiveListenUI(true);
  486. syncListeningVisuals();
  487. const startingInfo = {
  488. status: 'Connecting',
  489. demod: mode || '-',
  490. playback_mode: mode || '-',
  491. stereo_state: mode === 'WFM_STEREO' ? 'searching' : 'mono',
  492. sample_rate: 48000,
  493. channels: mode === 'WFM_STEREO' ? 2 : 1
  494. };
  495. updateLiveListenMeta(startingInfo);
  496. }
  497. function matchesListenTarget(signal) {
  498. if (!liveListenTarget || !signal) return false;
  499. const bw = signal.bw_hz || liveListenTarget.bw || 0;
  500. const tol = Math.max(500, bw * 0.5);
  501. return Math.abs((signal.center_hz || 0) - liveListenTarget.freq) <= tol;
  502. }
  503. let gpuInfo = { available: false, active: false, error: '' };
  504. let zoom = 1;
  505. let pan = 0;
  506. let followLive = true;
  507. let maxHold = false;
  508. let avgAlpha = 0;
  509. let avgSpectrum = null;
  510. let maxSpectrum = null;
  511. let lastFFTSize = null;
  512. let processedSpectrum = null;
  513. let processedSpectrumSource = null;
  514. let processingDirty = true;
  515. let pendingConfigUpdate = null;
  516. let pendingSettingsUpdate = null;
  517. let configTimer = null;
  518. let settingsTimer = null;
  519. let isSyncingConfig = false;
  520. let isDraggingSpectrum = false;
  521. let dragStartX = 0;
  522. let dragStartPan = 0;
  523. let navDrag = false;
  524. let timelineFrozen = false;
  525. let renderFrames = 0;
  526. let renderFps = 0;
  527. let lastFpsTs = performance.now();
  528. let wsReconnectTimer = null;
  529. let eventsFetchInFlight = false;
  530. const events = [];
  531. const eventsById = new Map();
  532. let lastEventEndMs = 0;
  533. let selectedEventId = null;
  534. let timelineRects = [];
  535. let liveSignalRects = [];
  536. let recordings = [];
  537. let recordingsFetchInFlight = false;
  538. let showDebugOverlay = localStorage.getItem('spectre.debugOverlay') !== '0';
  539. let hoveredSignal = null;
  540. let popoverHideTimer = null;
  541. const GAIN_MAX = 60;
  542. const timelineWindowMs = 5 * 60 * 1000;
  543. function setConfigStatus(text) {
  544. configStatusEl.textContent = text;
  545. }
  546. function setWsBadge(text, kind = 'neutral') {
  547. wsState = kind === 'ok' ? 'live' : (kind === 'bad' ? 'retrying' : 'connecting');
  548. wsBadge.textContent = text;
  549. wsBadge.style.borderColor = kind === 'ok'
  550. ? 'rgba(124, 251, 131, 0.35)'
  551. : kind === 'bad'
  552. ? 'rgba(255, 107, 129, 0.35)'
  553. : 'rgba(112, 150, 207, 0.18)';
  554. }
  555. function updateApiState(result) {
  556. if (!result) return;
  557. const latency = result.meta?.duration_ms;
  558. if (Number.isFinite(latency)) apiState.latencyMs = latency;
  559. if (result.ok) {
  560. apiState.ok = true;
  561. apiState.lastOkTs = Date.now();
  562. apiState.lastError = '';
  563. } else {
  564. apiState.ok = false;
  565. apiState.lastError = result.error || (result.status ? `HTTP ${result.status}` : 'request failed');
  566. }
  567. }
  568. function fmtAgeShort(ms) {
  569. if (!Number.isFinite(ms) || ms < 0) return '-';
  570. if (ms < 1000) return `${Math.round(ms)} ms`;
  571. if (ms < 60000) return `${(ms / 1000).toFixed(1)} s`;
  572. return `${Math.round(ms / 60000)} min`;
  573. }
  574. function updateOperatorStatus() {
  575. if (operatorPanel) {
  576. operatorPanel.updateStatus({
  577. wsState,
  578. wsLastMessageTs,
  579. apiState,
  580. configStatusText: configStatusEl?.textContent || '-',
  581. refinementInfo,
  582. telemetryLive,
  583. sourceAgeMs: stats?.last_sample_ago_ms
  584. });
  585. return;
  586. }
  587. if (healthWs) {
  588. const age = wsLastMessageTs > 0 ? fmtAgeShort(Date.now() - wsLastMessageTs) : '-';
  589. healthWs.textContent = `${wsState} | last ${age}`;
  590. }
  591. if (healthApi) {
  592. const latency = Number.isFinite(apiState.latencyMs) ? `${apiState.latencyMs} ms` : 'n/a';
  593. healthApi.textContent = apiState.ok ? `ok | ${latency}` : `degraded | ${apiState.lastError || 'n/a'}`;
  594. }
  595. if (healthConfig) {
  596. healthConfig.textContent = configStatusEl?.textContent || '-';
  597. }
  598. if (healthRefine) {
  599. const plan = refinementInfo.plan || {};
  600. const queue = refinementInfo.arbitration?.queue || {};
  601. healthRefine.textContent = `${plan.selected?.length || 0}/${plan.budget || 0} | q ${queue.record_queued || 0}/${queue.decode_queued || 0}`;
  602. }
  603. if (healthTelemetry) {
  604. if (!telemetryLive) {
  605. healthTelemetry.textContent = 'unavailable';
  606. } else {
  607. const enabled = telemetryLive.enabled === false ? 'off' : 'on';
  608. const collector = telemetryLive.collector || {};
  609. const recent = Array.isArray(telemetryLive.recent_events) ? telemetryLive.recent_events.length : 0;
  610. const heavy = collector.heavy_enabled ? 'heavy' : 'light';
  611. healthTelemetry.textContent = `${enabled} | ${heavy} | events ${recent}`;
  612. }
  613. }
  614. }
  615. function toMHz(hz) { return hz / 1e6; }
  616. function fromMHz(mhz) { return mhz * 1e6; }
  617. function fmtMHz(hz, digits = 3) { return `${(hz / 1e6).toFixed(digits)} MHz`; }
  618. function fmtKHz(hz, digits = 2) { return `${(hz / 1e3).toFixed(digits)} kHz`; }
  619. function fmtHz(hz) {
  620. if (hz >= 1e6) return `${(hz / 1e6).toFixed(3)} MHz`;
  621. if (hz >= 1e3) return `${(hz / 1e3).toFixed(2)} kHz`;
  622. return `${hz.toFixed(0)} Hz`;
  623. }
  624. function fmtMs(ms) {
  625. if (ms < 1000) return `${Math.max(0, Math.round(ms))} ms`;
  626. return `${(ms / 1000).toFixed(2)} s`;
  627. }
  628. function scoreEntries(scores, limit = 6) {
  629. if (!scores || typeof scores !== 'object') return [];
  630. return Object.entries(scores)
  631. .filter(([, v]) => Number.isFinite(Number(v)))
  632. .sort((a, b) => Number(b[1]) - Number(a[1]))
  633. .slice(0, limit);
  634. }
  635. function renderScoreBars(scores) {
  636. if (!classifierScoreBarsEl) return;
  637. const entries = scoreEntries(scores);
  638. if (!entries.length) {
  639. classifierScoreBarsEl.innerHTML = '';
  640. return;
  641. }
  642. const maxVal = Math.max(...entries.map(([, v]) => Number(v)), 1e-6);
  643. classifierScoreBarsEl.innerHTML = entries.map(([label, value]) => {
  644. const width = Math.max(4, (Number(value) / maxVal) * 100);
  645. 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>`;
  646. }).join('');
  647. }
  648. function hideSignalPopover() {
  649. hoveredSignal = null;
  650. if (!signalPopover) return;
  651. signalPopover.classList.remove('open');
  652. signalPopover.setAttribute('aria-hidden', 'true');
  653. }
  654. function renderSignalPopover(rect, signal) {
  655. if (!signalPopover || !signal) return;
  656. const entries = scoreEntries(signal.class?.scores || signal.debug_scores || {}, 4);
  657. const maxVal = Math.max(...entries.map(([, v]) => Number(v)), 1e-6);
  658. const rows = entries.map(([label, value]) => {
  659. const width = Math.max(4, (Number(value) / maxVal) * 100);
  660. 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>`;
  661. }).join('');
  662. const primaryMode = getSignalPrimaryMode(signal);
  663. const runtimeInfo = getSignalRuntimeSummary(signal);
  664. signalPopover.innerHTML = `<div class="signal-popover__title">${primaryMode}${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${runtimeInfo ? ` · ${runtimeInfo}` : ''}${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>`;
  665. const popW = 220;
  666. const top = rect.y + 8;
  667. const maxLeft = Math.max(8, spectrumCanvas.width - popW - 8);
  668. signalPopover.style.left = `${Math.max(8, Math.min(maxLeft, left))}px`;
  669. signalPopover.style.top = `${Math.max(8, top)}px`;
  670. signalPopover.classList.add('open');
  671. signalPopover.setAttribute('aria-hidden', 'false');
  672. }
  673. function colorMap(v) {
  674. const x = Math.max(0, Math.min(1, v));
  675. const r = Math.floor(255 * Math.pow(x, 0.55));
  676. const g = Math.floor(255 * Math.pow(x, 1.08));
  677. const b = Math.floor(220 * Math.pow(1 - x, 1.15));
  678. return [r, g, b];
  679. }
  680. function snrColor(snr) {
  681. const norm = Math.max(0, Math.min(1, (snr + 5) / 35));
  682. const [r, g, b] = colorMap(norm);
  683. return `rgb(${r}, ${g}, ${b})`;
  684. }
  685. // Modulation-type color map for signal boxes and badges
  686. function modColor(modType) {
  687. switch (modType) {
  688. case 'WFM': return { r: 72, g: 210, b: 120, label: '#48d278' }; // green
  689. case 'WFM_STEREO': return { r: 72, g: 230, b: 160, label: '#48e6a0' }; // bright green
  690. case 'NFM': return { r: 255, g: 170, b: 60, label: '#ffaa3c' }; // orange
  691. case 'AM': return { r: 90, g: 160, b: 255, label: '#5aa0ff' }; // blue
  692. case 'USB': case 'LSB':
  693. return { r: 160, g: 120, b: 255, label: '#a078ff' }; // purple
  694. case 'CW': return { r: 255, g: 100, b: 100, label: '#ff6464' }; // red
  695. case 'FT8': case 'WSPR': case 'FSK': case 'PSK':
  696. return { r: 255, g: 220, b: 80, label: '#ffdc50' }; // yellow
  697. default: return { r: 160, g: 190, b: 220, label: '#a0bedc' }; // grey-blue
  698. }
  699. }
  700. function modColorStr(modType, alpha) {
  701. const c = modColor(modType);
  702. return `rgba(${c.r}, ${c.g}, ${c.b}, ${alpha})`;
  703. }
  704. function binForFreq(freq, centerHz, sampleRate, n) {
  705. return Math.floor((freq - (centerHz - sampleRate / 2)) / (sampleRate / n));
  706. }
  707. function maxInBinRange(spectrum, b0, b1) {
  708. const n = spectrum.length;
  709. let start = Math.max(0, Math.min(n - 1, b0));
  710. let end = Math.max(0, Math.min(n - 1, b1));
  711. if (end < start) [start, end] = [end, start];
  712. let max = -1e9;
  713. for (let i = start; i <= end; i++) {
  714. if (spectrum[i] > max) max = spectrum[i];
  715. }
  716. return max;
  717. }
  718. function sampleOverlayAtX(overlay, x, width, centerHz, sampleRate) {
  719. if (!Array.isArray(overlay) || overlay.length === 0 || width <= 0) return null;
  720. const n = overlay.length;
  721. const span = sampleRate / zoom;
  722. const startHz = centerHz - span / 2 + pan * span;
  723. const endHz = centerHz + span / 2 + pan * span;
  724. const f1 = startHz + (x / width) * (endHz - startHz);
  725. const f2 = startHz + ((x + 1) / width) * (endHz - startHz);
  726. const b0 = binForFreq(f1, centerHz, sampleRate, n);
  727. const b1 = binForFreq(f2, centerHz, sampleRate, n);
  728. return maxInBinRange(overlay, b0, b1);
  729. }
  730. function drawThresholdOverlay(ctx, w, h, minDb, maxDb) {
  731. if (!showDebugOverlay) return;
  732. const thresholds = latest?.debug?.thresholds;
  733. if (!Array.isArray(thresholds) || thresholds.length === 0) return;
  734. ctx.save();
  735. ctx.strokeStyle = 'rgba(255, 196, 92, 0.9)';
  736. ctx.lineWidth = 1.25;
  737. if (ctx.setLineDash) ctx.setLineDash([6, 4]);
  738. ctx.beginPath();
  739. for (let x = 0; x < w; x++) {
  740. const v = sampleOverlayAtX(thresholds, x, w, latest.center_hz, latest.sample_rate);
  741. if (v == null || Number.isNaN(v)) continue;
  742. const y = h - ((v - minDb) / (maxDb - minDb)) * (h - 18) - 6;
  743. if (x === 0) ctx.moveTo(x, y);
  744. else ctx.lineTo(x, y);
  745. }
  746. ctx.stroke();
  747. if (ctx.setLineDash) ctx.setLineDash([]);
  748. ctx.fillStyle = 'rgba(255, 196, 92, 0.95)';
  749. ctx.font = '11px Inter, sans-serif';
  750. ctx.fillText('CFAR', 8, 14);
  751. ctx.restore();
  752. }
  753. function markSpectrumDirty() {
  754. processingDirty = true;
  755. }
  756. function processSpectrum(spectrum) {
  757. if (!spectrum) return spectrum;
  758. let base = spectrum;
  759. if (avgAlpha > 0) {
  760. if (!avgSpectrum || avgSpectrum.length !== spectrum.length) {
  761. avgSpectrum = spectrum.slice();
  762. } else {
  763. for (let i = 0; i < spectrum.length; i++) {
  764. avgSpectrum[i] = avgAlpha * spectrum[i] + (1 - avgAlpha) * avgSpectrum[i];
  765. }
  766. }
  767. base = avgSpectrum;
  768. }
  769. if (maxHold) {
  770. if (!maxSpectrum || maxSpectrum.length !== base.length) {
  771. maxSpectrum = base.slice();
  772. } else {
  773. for (let i = 0; i < base.length; i++) {
  774. if (base[i] > maxSpectrum[i]) maxSpectrum[i] = base[i];
  775. }
  776. }
  777. base = maxSpectrum;
  778. }
  779. return base;
  780. }
  781. function resetProcessingCaches() {
  782. avgSpectrum = null;
  783. maxSpectrum = null;
  784. processedSpectrum = null;
  785. processedSpectrumSource = null;
  786. processingDirty = true;
  787. }
  788. function getProcessedSpectrum() {
  789. if (!latest?.spectrum_db) return null;
  790. if (!processingDirty && processedSpectrumSource === latest.spectrum_db) return processedSpectrum;
  791. processedSpectrum = processSpectrum(latest.spectrum_db);
  792. processedSpectrumSource = latest.spectrum_db;
  793. processingDirty = false;
  794. return processedSpectrum;
  795. }
  796. function resizeCanvas(canvas) {
  797. if (!canvas) return;
  798. const rect = canvas.getBoundingClientRect();
  799. const dpr = window.devicePixelRatio || 1;
  800. const width = Math.max(1, Math.floor(rect.width * dpr));
  801. const height = Math.max(1, Math.floor(rect.height * dpr));
  802. if (canvas.width !== width || canvas.height !== height) {
  803. canvas.width = width;
  804. canvas.height = height;
  805. }
  806. }
  807. function resizeAll() {
  808. [navCanvas, spectrumCanvas, waterfallCanvas, occupancyCanvas, timelineCanvas, detailSpectrogram].forEach(resizeCanvas);
  809. }
  810. window.addEventListener('resize', resizeAll);
  811. resizeAll();
  812. function setSelectValueOrNearest(selectEl, numericValue) {
  813. if (!selectEl) return;
  814. const options = Array.from(selectEl.options || []);
  815. const exact = options.find(o => Number.parseFloat(o.value) === numericValue);
  816. if (exact) {
  817. selectEl.value = exact.value;
  818. return;
  819. }
  820. let best = options[0];
  821. let bestDist = Infinity;
  822. for (const opt of options) {
  823. const dist = Math.abs(Number.parseFloat(opt.value) - numericValue);
  824. if (dist < bestDist) {
  825. best = opt;
  826. bestDist = dist;
  827. }
  828. }
  829. if (best) selectEl.value = best.value;
  830. }
  831. function applyConfigToUI(cfg) {
  832. if (!cfg) return;
  833. isSyncingConfig = true;
  834. centerInput.value = toMHz(cfg.center_hz).toFixed(6);
  835. setSelectValueOrNearest(sampleRateSelect, cfg.sample_rate / 1e6);
  836. setSelectValueOrNearest(bwSelect, cfg.tuner_bw_khz || 1536);
  837. setSelectValueOrNearest(fftSelect, cfg.fft_size);
  838. if (lastFFTSize !== cfg.fft_size) {
  839. resetProcessingCaches();
  840. lastFFTSize = cfg.fft_size;
  841. }
  842. const uiGain = Math.max(0, Math.min(GAIN_MAX, GAIN_MAX - cfg.gain_db));
  843. gainRange.value = uiGain;
  844. gainInput.value = uiGain;
  845. thresholdRange.value = cfg.detector.threshold_db;
  846. thresholdInput.value = cfg.detector.threshold_db;
  847. if (cfarModeSelect) cfarModeSelect.value = cfg.detector.cfar_mode || 'OFF';
  848. if (cfarWrapToggle) cfarWrapToggle.checked = cfg.detector.cfar_wrap_around !== false;
  849. if (cfarGuardHzInput) cfarGuardHzInput.value = cfg.detector.cfar_guard_hz ?? 500;
  850. if (cfarTrainHzInput) cfarTrainHzInput.value = cfg.detector.cfar_train_hz ?? 5000;
  851. if (cfarRankInput) cfarRankInput.value = cfg.detector.cfar_rank ?? 24;
  852. if (cfarScaleInput) cfarScaleInput.value = cfg.detector.cfar_scale_db ?? 6;
  853. const rankRow = cfarRankInput?.closest('.field');
  854. if (rankRow) rankRow.style.display = (cfg.detector.cfar_mode === 'OS') ? '' : 'none';
  855. if (minDurationInput) minDurationInput.value = cfg.detector.min_duration_ms;
  856. if (holdInput) holdInput.value = cfg.detector.hold_ms;
  857. if (emaAlphaInput) emaAlphaInput.value = cfg.detector.ema_alpha ?? 0.2;
  858. if (hysteresisInput) hysteresisInput.value = cfg.detector.hysteresis_db ?? 3;
  859. if (stableFramesInput) stableFramesInput.value = cfg.detector.min_stable_frames ?? 3;
  860. if (gapToleranceInput) gapToleranceInput.value = cfg.detector.gap_tolerance_ms ?? cfg.detector.hold_ms;
  861. if (classifierModeSelect) classifierModeSelect.value = cfg.classifier_mode || 'combined';
  862. if (edgeMarginInput) edgeMarginInput.value = cfg.detector.edge_margin_db ?? 3.0;
  863. if (mergeGapInput) mergeGapInput.value = cfg.detector.merge_gap_hz ?? 5000;
  864. if (classHistoryInput) classHistoryInput.value = cfg.detector.class_history_size ?? 10;
  865. if (classSwitchInput) classSwitchInput.value = cfg.detector.class_switch_ratio ?? 0.6;
  866. agcToggle.checked = !!cfg.agc;
  867. dcToggle.checked = !!cfg.dc_block;
  868. iqToggle.checked = !!cfg.iq_balance;
  869. gpuToggle.checked = !!cfg.use_gpu_fft;
  870. maxHoldToggle.checked = maxHold;
  871. if (cfg.recorder) {
  872. if (recEnableToggle) recEnableToggle.checked = !!cfg.recorder.enabled;
  873. if (recIQToggle) recIQToggle.checked = !!cfg.recorder.record_iq;
  874. if (recAudioToggle) recAudioToggle.checked = !!cfg.recorder.record_audio;
  875. if (recDemodToggle) recDemodToggle.checked = !!cfg.recorder.auto_demod;
  876. if (recDecodeToggle) recDecodeToggle.checked = !!cfg.recorder.auto_decode;
  877. if (recMinSNR) recMinSNR.value = cfg.recorder.min_snr_db ?? 10;
  878. if (recMaxDisk) recMaxDisk.value = cfg.recorder.max_disk_mb ?? 0;
  879. if (recClassFilter) recClassFilter.value = (cfg.recorder.class_filter || []).join(', ');
  880. }
  881. if (refineAutoSpan) refineAutoSpan.value = String(cfg.refinement?.auto_span ?? true);
  882. if (refineMinSpan) refineMinSpan.value = cfg.refinement?.min_span_hz ?? 0;
  883. if (refineMaxSpan) refineMaxSpan.value = cfg.refinement?.max_span_hz ?? 0;
  884. if (resMaxRefine) resMaxRefine.value = cfg.resources?.max_refinement_jobs ?? 0;
  885. if (resMaxRecord) resMaxRecord.value = cfg.resources?.max_recording_streams ?? 0;
  886. if (resMaxDecode) resMaxDecode.value = cfg.resources?.max_decode_jobs ?? 0;
  887. spanInput.value = (cfg.sample_rate / zoom / 1e6).toFixed(3);
  888. isSyncingConfig = false;
  889. }
  890. async function loadConfig() {
  891. if (!apiClient) return;
  892. const res = await apiClient.getConfig();
  893. updateApiState(res);
  894. if (res.ok && res.data) {
  895. currentConfig = res.data;
  896. applyConfigToUI(currentConfig);
  897. setConfigStatus('Config synced');
  898. } else {
  899. setConfigStatus('Config offline');
  900. }
  901. updateOperatorStatus();
  902. }
  903. async function loadSignals() {
  904. if (!apiClient) return;
  905. const res = await apiClient.getSignals();
  906. updateApiState(res);
  907. if (!res.ok || !Array.isArray(res.data)) return;
  908. latest = latest || {};
  909. latest.signals = res.data;
  910. renderLists();
  911. }
  912. async function loadDecoders() {
  913. if (!decodeModeSelect || !apiClient) return;
  914. const res = await apiClient.getDecoders();
  915. updateApiState(res);
  916. if (!res.ok || !Array.isArray(res.data)) return;
  917. const current = decodeModeSelect.value;
  918. decodeModeSelect.innerHTML = '';
  919. res.data.forEach((mode) => {
  920. const opt = document.createElement('option');
  921. opt.value = mode;
  922. opt.textContent = mode;
  923. decodeModeSelect.appendChild(opt);
  924. });
  925. if (current) decodeModeSelect.value = current;
  926. }
  927. async function loadStats() {
  928. if (!apiClient) return;
  929. const res = await apiClient.getStats();
  930. updateApiState(res);
  931. if (res.ok && res.data) stats = res.data;
  932. updateOperatorStatus();
  933. }
  934. async function loadGPU() {
  935. if (!apiClient) return;
  936. const res = await apiClient.getGPU();
  937. updateApiState(res);
  938. if (res.ok && res.data) gpuInfo = res.data;
  939. updateOperatorStatus();
  940. }
  941. async function loadRefinement() {
  942. if (!apiClient) return;
  943. const res = await apiClient.getRefinement();
  944. updateApiState(res);
  945. if (!res.ok || !res.data) return;
  946. refinementInfo = res.data;
  947. decisionIndex = new Map();
  948. const items = Array.isArray(refinementInfo.arbitration?.decision_items) ? refinementInfo.arbitration.decision_items : [];
  949. items.forEach(item => {
  950. if (item && item.id != null) decisionIndex.set(String(item.id), item);
  951. });
  952. updateSignalDecisionSummary(window._selectedSignal?.id);
  953. updateSignalQueueSummary();
  954. updateOperatorStatus();
  955. }
  956. async function loadTelemetryLive() {
  957. if (!apiClient) return;
  958. const res = await apiClient.getTelemetryLive();
  959. updateApiState(res);
  960. if (!res.ok) {
  961. telemetryLive = null;
  962. updateOperatorStatus();
  963. return;
  964. }
  965. telemetryLive = res.data;
  966. updateOperatorStatus();
  967. }
  968. function renderKvList(root, rows, emptyText) {
  969. if (!root) return;
  970. if (!rows || !rows.length) {
  971. root.innerHTML = `<div class="ops-line ops-line--muted">${emptyText}</div>`;
  972. return;
  973. }
  974. root.innerHTML = rows.map(({ key, value }) => `<div class="kv-row"><div class="kv-key">${key}</div><div class="kv-val">${value}</div></div>`).join('');
  975. }
  976. function renderPolicyLists() {
  977. if (policySummaryList) {
  978. if (!policyInfo) {
  979. renderKvList(policySummaryList, [], 'Policy unavailable.');
  980. } else {
  981. renderKvList(policySummaryList, [
  982. { key: 'Profile', value: policyInfo.profile || 'n/a' },
  983. { key: 'Mode', value: policyInfo.mode || 'n/a' },
  984. { key: 'Intent', value: policyInfo.intent || 'n/a' },
  985. { key: 'Surveillance', value: policyInfo.surveillance_strategy || 'n/a' },
  986. { key: 'Refinement', value: policyInfo.refinement_strategy || 'n/a' }
  987. ], 'Policy unavailable.');
  988. }
  989. }
  990. if (policyRecommendationList) {
  991. if (!policyRecommendations) {
  992. renderKvList(policyRecommendationList, [], 'Recommendations unavailable.');
  993. } else {
  994. renderKvList(policyRecommendationList, [
  995. { key: 'Monitor span', value: Number.isFinite(policyRecommendations.monitor_span_hz) ? fmtHz(policyRecommendations.monitor_span_hz) : 'n/a' },
  996. { key: 'Refine jobs', value: policyRecommendations.refinement_jobs ?? 'n/a' },
  997. { key: 'Detail FFT', value: policyRecommendations.refinement_detail_fft ?? 'n/a' },
  998. { key: 'Auto span', value: policyRecommendations.refinement_auto_span ?? 'n/a' },
  999. { key: 'Auto record', value: Array.isArray(policyRecommendations.auto_record_classes) && policyRecommendations.auto_record_classes.length ? policyRecommendations.auto_record_classes.join(', ') : 'n/a' },
  1000. { key: 'Auto decode', value: Array.isArray(policyRecommendations.auto_decode_classes) && policyRecommendations.auto_decode_classes.length ? policyRecommendations.auto_decode_classes.join(', ') : 'n/a' }
  1001. ], 'Recommendations unavailable.');
  1002. }
  1003. }
  1004. }
  1005. async function loadPolicy() {
  1006. if (!apiClient) return;
  1007. const [policyRes, recRes] = await Promise.all([
  1008. apiClient.getPolicy(),
  1009. apiClient.getRecommendations()
  1010. ]);
  1011. updateApiState(policyRes.ok ? policyRes : recRes);
  1012. policyInfo = policyRes.ok ? policyRes.data : null;
  1013. policyRecommendations = recRes.ok ? recRes.data : null;
  1014. renderPolicyLists();
  1015. }
  1016. function formatLevelSummary(level) {
  1017. if (!level) return 'n/a';
  1018. const name = level.name || 'level';
  1019. const fft = level.fft_size ? `${level.fft_size} bins` : 'bins n/a';
  1020. const span = level.span_hz ? fmtHz(level.span_hz) : 'span n/a';
  1021. const binHz = level.bin_hz || ((level.sample_rate && level.fft_size) ? (level.sample_rate / level.fft_size) : 0);
  1022. const binText = binHz ? `${binHz.toFixed(1)} Hz/bin` : 'bin n/a';
  1023. const decim = level.decimation && level.decimation > 1 ? `decim ${level.decimation}` : '';
  1024. const source = level.source ? `src ${level.source}` : '';
  1025. return [name, fft, span, binText, decim, source].filter(Boolean).join(' · ');
  1026. }
  1027. function queueConfigUpdate(partial) {
  1028. if (isSyncingConfig) return;
  1029. pendingConfigUpdate = { ...(pendingConfigUpdate || {}), ...partial };
  1030. setConfigStatus('Applying…');
  1031. clearTimeout(configTimer);
  1032. configTimer = setTimeout(sendConfigUpdate, 180);
  1033. }
  1034. function queueSettingsUpdate(partial) {
  1035. if (isSyncingConfig) return;
  1036. pendingSettingsUpdate = { ...(pendingSettingsUpdate || {}), ...partial };
  1037. setConfigStatus('Applying…');
  1038. clearTimeout(settingsTimer);
  1039. settingsTimer = setTimeout(sendSettingsUpdate, 120);
  1040. }
  1041. async function sendConfigUpdate() {
  1042. if (!pendingConfigUpdate) return;
  1043. const payload = pendingConfigUpdate;
  1044. pendingConfigUpdate = null;
  1045. if (!apiClient) return;
  1046. const res = await apiClient.postConfig(payload);
  1047. updateApiState(res);
  1048. if (res.ok && res.data) {
  1049. currentConfig = res.data;
  1050. applyConfigToUI(currentConfig);
  1051. setConfigStatus('Config applied');
  1052. } else {
  1053. setConfigStatus('Config apply failed');
  1054. }
  1055. }
  1056. async function sendSettingsUpdate() {
  1057. if (!pendingSettingsUpdate) return;
  1058. const payload = pendingSettingsUpdate;
  1059. pendingSettingsUpdate = null;
  1060. if (!apiClient) return;
  1061. const res = await apiClient.postSettings(payload);
  1062. updateApiState(res);
  1063. if (res.ok && res.data) {
  1064. currentConfig = res.data;
  1065. applyConfigToUI(currentConfig);
  1066. setConfigStatus('Settings applied');
  1067. } else {
  1068. setConfigStatus('Settings apply failed');
  1069. }
  1070. }
  1071. function updateHeroMetrics() {
  1072. if (!latest) return;
  1073. const span = latest.sample_rate / zoom;
  1074. const binHz = latest.sample_rate / Math.max(1, latest.spectrum_db?.length || latest.fft_size || 1);
  1075. metricCenter.textContent = fmtMHz(latest.center_hz, 6);
  1076. metricSpan.textContent = fmtHz(span);
  1077. metricRes.textContent = `${binHz.toFixed(1)} Hz/bin`;
  1078. metricSignals.textContent = String(latest.signals?.length || 0);
  1079. metricGpu.textContent = gpuInfo.active ? 'ON' : (gpuInfo.available ? 'OFF' : 'N/A');
  1080. metricSource.textContent = stats.last_sample_ago_ms >= 0 ? `${stats.last_sample_ago_ms} ms` : 'n/a';
  1081. const gpuText = gpuInfo.active ? 'GPU active' : (gpuInfo.available ? 'GPU ready' : 'GPU n/a');
  1082. const debug = latest.debug || {};
  1083. const thresholdInfo = Array.isArray(debug.thresholds) && debug.thresholds.length
  1084. ? `CFAR ${showDebugOverlay ? 'on' : 'hidden'} · noise ${(Number.isFinite(debug.noise_floor) ? debug.noise_floor.toFixed(1) : 'n/a')} dB`
  1085. : `CFAR off · noise ${(Number.isFinite(debug.noise_floor) ? debug.noise_floor.toFixed(1) : 'n/a')} dB`;
  1086. const plan = debug.refinement_plan || null;
  1087. const windowSummary = debug.window_summary || null;
  1088. const windows = (windowSummary && windowSummary.refinement) || debug.refinement_windows || null;
  1089. const refineInfo = plan && showDebugOverlay
  1090. ? `refine ${plan.selected?.length || 0}/${plan.budget || 0} drop ${plan.dropped_by_snr || 0}/${plan.dropped_by_budget || 0}`
  1091. : '';
  1092. const windowInfo = windows && showDebugOverlay
  1093. ? `win ${windows.count || 0} span ${fmtHz(windows.min_span_hz || 0)}–${fmtHz(windows.max_span_hz || 0)}`
  1094. : '';
  1095. const extras = [refineInfo, windowInfo].filter(Boolean).join(' · ');
  1096. metaLine.textContent = `${fmtMHz(latest.center_hz, 3)} · ${fmtHz(span)} span · ${thresholdInfo}${extras ? ' · ' + extras : ''} · ${gpuText}`;
  1097. heroSubtitle.textContent = `${latest.signals?.length || 0} live signals · ${events.length} recent events tracked`;
  1098. healthBuffer.textContent = String(stats.buffer_samples ?? '-');
  1099. healthDropped.textContent = String(stats.dropped ?? '-');
  1100. healthResets.textContent = String(stats.resets ?? '-');
  1101. healthAge.textContent = stats.last_sample_ago_ms >= 0 ? `${stats.last_sample_ago_ms} ms` : 'n/a';
  1102. healthGpu.textContent = gpuInfo.error ? `${gpuInfo.active ? 'ON' : 'OFF'} · ${gpuInfo.error}` : (gpuInfo.active ? 'ON' : (gpuInfo.available ? 'Ready' : 'N/A'));
  1103. healthFps.textContent = `${renderFps.toFixed(0)} fps`;
  1104. if (healthRefinePlan) {
  1105. const plan = refinementInfo.plan || {};
  1106. const decisionSummary = refinementInfo.arbitration?.decision_summary || {};
  1107. const recOn = decisionSummary.record_enabled ?? 0;
  1108. const decOn = decisionSummary.decode_enabled ?? 0;
  1109. const reasonCounts = decisionSummary.reasons || {};
  1110. const topReason = Object.entries(reasonCounts).sort((a, b) => b[1] - a[1])[0];
  1111. const reasonText = topReason ? `· ${topReason[0]}` : '';
  1112. const queueStats = refinementInfo.arbitration?.queue || {};
  1113. const queueText = (queueStats.record_queued || queueStats.decode_queued)
  1114. ? `· q ${queueStats.record_queued || 0}/${queueStats.decode_queued || 0}`
  1115. : '';
  1116. healthRefinePlan.textContent = `${plan.selected?.length || 0}/${plan.budget || 0} · drop ${plan.dropped_by_snr || 0}/${plan.dropped_by_budget || 0} · rec ${recOn} dec ${decOn} ${queueText} ${reasonText}`;
  1117. }
  1118. if (healthRefineWindows) {
  1119. const stats = refinementInfo.window_summary?.refinement || refinementInfo.window_stats || null;
  1120. if (stats && stats.count) {
  1121. const levelSet = refinementInfo.surveillance_level_set || {};
  1122. const primary = levelSet.primary || refinementInfo.surveillance_level;
  1123. const presentation = levelSet.presentation || refinementInfo.display_level || null;
  1124. const primaryText = primary ? ` · primary ${formatLevelSummary(primary)}` : '';
  1125. const presentationText = presentation ? ` · display ${formatLevelSummary(presentation)}` : '';
  1126. healthRefineWindows.textContent = `${fmtHz(stats.min_span_hz || 0)}–${fmtHz(stats.max_span_hz || 0)}${primaryText}${presentationText}`;
  1127. } else {
  1128. const windows = refinementInfo.windows || [];
  1129. if (!Array.isArray(windows) || windows.length === 0) {
  1130. healthRefineWindows.textContent = 'n/a';
  1131. } else {
  1132. const spans = windows.map(w => w.span_hz || 0).filter(v => v > 0);
  1133. const minSpan = spans.length ? Math.min(...spans) : 0;
  1134. const maxSpan = spans.length ? Math.max(...spans) : 0;
  1135. healthRefineWindows.textContent = spans.length ? `${fmtHz(minSpan)}–${fmtHz(maxSpan)}` : 'n/a';
  1136. }
  1137. }
  1138. }
  1139. }
  1140. function renderBandNavigator() {
  1141. if (!latest) return;
  1142. const ctx = navCanvas.getContext('2d');
  1143. const w = navCanvas.width;
  1144. const h = navCanvas.height;
  1145. ctx.clearRect(0, 0, w, h);
  1146. const display = getProcessedSpectrum();
  1147. if (!display) return;
  1148. const minDb = -120;
  1149. const maxDb = 0;
  1150. ctx.fillStyle = '#071018';
  1151. ctx.fillRect(0, 0, w, h);
  1152. ctx.strokeStyle = 'rgba(102, 169, 255, 0.25)';
  1153. ctx.lineWidth = 1;
  1154. ctx.beginPath();
  1155. for (let x = 0; x < w; x++) {
  1156. const idx = Math.min(display.length - 1, Math.floor((x / w) * display.length));
  1157. const v = display[idx];
  1158. const y = h - ((v - minDb) / (maxDb - minDb)) * (h - 10) - 5;
  1159. if (x === 0) ctx.moveTo(x, y);
  1160. else ctx.lineTo(x, y);
  1161. }
  1162. ctx.stroke();
  1163. const span = latest.sample_rate / zoom;
  1164. const fullStart = latest.center_hz - latest.sample_rate / 2;
  1165. const viewStart = latest.center_hz - span / 2 + pan * span;
  1166. const viewEnd = latest.center_hz + span / 2 + pan * span;
  1167. const x1 = ((viewStart - fullStart) / latest.sample_rate) * w;
  1168. const x2 = ((viewEnd - fullStart) / latest.sample_rate) * w;
  1169. ctx.fillStyle = 'rgba(102, 240, 209, 0.10)';
  1170. ctx.strokeStyle = 'rgba(102, 240, 209, 0.85)';
  1171. ctx.lineWidth = 2;
  1172. ctx.fillRect(x1, 4, Math.max(2, x2 - x1), h - 8);
  1173. ctx.strokeRect(x1, 4, Math.max(2, x2 - x1), h - 8);
  1174. }
  1175. function drawSpectrumGrid(ctx, w, h, startHz, endHz) {
  1176. ctx.strokeStyle = 'rgba(86, 109, 148, 0.18)';
  1177. ctx.lineWidth = 1;
  1178. for (let i = 1; i < 6; i++) {
  1179. const y = (h / 6) * i;
  1180. ctx.beginPath();
  1181. ctx.moveTo(0, y);
  1182. ctx.lineTo(w, y);
  1183. ctx.stroke();
  1184. }
  1185. for (let i = 1; i < 8; i++) {
  1186. const x = (w / 8) * i;
  1187. ctx.beginPath();
  1188. ctx.moveTo(x, 0);
  1189. ctx.lineTo(x, h);
  1190. ctx.stroke();
  1191. const hz = startHz + (i / 8) * (endHz - startHz);
  1192. ctx.fillStyle = 'rgba(173, 192, 220, 0.72)';
  1193. ctx.font = `${Math.max(11, Math.floor(h / 26))}px Inter, sans-serif`;
  1194. ctx.fillText((hz / 1e6).toFixed(3), x + 4, h - 8);
  1195. }
  1196. }
  1197. function drawCfarEdgeOverlay(ctx, w, h, startHz, endHz) {
  1198. if (!latest) return;
  1199. const mode = currentConfig?.detector?.cfar_mode || 'OFF';
  1200. if (mode === 'OFF') return;
  1201. if (currentConfig?.detector?.cfar_wrap_around) return;
  1202. const guardHz = currentConfig.detector.cfar_guard_hz ?? 500;
  1203. const trainHz = currentConfig.detector.cfar_train_hz ?? 5000;
  1204. const fftSize = latest.fft_size || latest.spectrum_db?.length;
  1205. if (!fftSize || fftSize <= 0) return;
  1206. const binW = (latest.sample_rate || 2048000) / fftSize;
  1207. const bins = Math.ceil(guardHz / binW) + Math.ceil(trainHz / binW);
  1208. if (bins <= 0) return;
  1209. const binHz = latest.sample_rate / fftSize;
  1210. const edgeHz = bins * binHz;
  1211. const bandStart = latest.center_hz - latest.sample_rate / 2;
  1212. const bandEnd = latest.center_hz + latest.sample_rate / 2;
  1213. const leftEdgeEnd = bandStart + edgeHz;
  1214. const rightEdgeStart = bandEnd - edgeHz;
  1215. ctx.fillStyle = 'rgba(255, 204, 102, 0.08)';
  1216. ctx.strokeStyle = 'rgba(255, 204, 102, 0.18)';
  1217. ctx.lineWidth = 1;
  1218. const leftStart = Math.max(startHz, bandStart);
  1219. const leftEnd = Math.min(endHz, leftEdgeEnd);
  1220. if (leftEnd > leftStart) {
  1221. const x1 = ((leftStart - startHz) / (endHz - startHz)) * w;
  1222. const x2 = ((leftEnd - startHz) / (endHz - startHz)) * w;
  1223. ctx.fillRect(x1, 0, Math.max(2, x2 - x1), h);
  1224. ctx.strokeRect(x1, 0, Math.max(2, x2 - x1), h);
  1225. }
  1226. const rightStart = Math.max(startHz, rightEdgeStart);
  1227. const rightEnd = Math.min(endHz, bandEnd);
  1228. if (rightEnd > rightStart) {
  1229. const x1 = ((rightStart - startHz) / (endHz - startHz)) * w;
  1230. const x2 = ((rightEnd - startHz) / (endHz - startHz)) * w;
  1231. ctx.fillRect(x1, 0, Math.max(2, x2 - x1), h);
  1232. ctx.strokeRect(x1, 0, Math.max(2, x2 - x1), h);
  1233. }
  1234. }
  1235. function renderSpectrum() {
  1236. if (!latest) return;
  1237. const ctx = spectrumCanvas.getContext('2d');
  1238. const w = spectrumCanvas.width;
  1239. const h = spectrumCanvas.height;
  1240. ctx.clearRect(0, 0, w, h);
  1241. const display = getProcessedSpectrum();
  1242. if (!display) return;
  1243. const n = display.length;
  1244. const span = latest.sample_rate / zoom;
  1245. const startHz = latest.center_hz - span / 2 + pan * span;
  1246. const endHz = latest.center_hz + span / 2 + pan * span;
  1247. spanInput.value = (span / 1e6).toFixed(3);
  1248. drawSpectrumGrid(ctx, w, h, startHz, endHz);
  1249. drawCfarEdgeOverlay(ctx, w, h, startHz, endHz);
  1250. const minDb = -120;
  1251. const maxDb = 0;
  1252. const fill = ctx.createLinearGradient(0, 0, 0, h);
  1253. fill.addColorStop(0, 'rgba(102, 240, 209, 0.20)');
  1254. fill.addColorStop(1, 'rgba(102, 240, 209, 0.02)');
  1255. ctx.beginPath();
  1256. for (let x = 0; x < w; x++) {
  1257. const f1 = startHz + (x / w) * (endHz - startHz);
  1258. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  1259. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  1260. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  1261. const v = maxInBinRange(display, b0, b1);
  1262. const y = h - ((v - minDb) / (maxDb - minDb)) * (h - 18) - 6;
  1263. if (x === 0) ctx.moveTo(x, y);
  1264. else ctx.lineTo(x, y);
  1265. }
  1266. ctx.lineTo(w, h);
  1267. ctx.lineTo(0, h);
  1268. ctx.closePath();
  1269. ctx.fillStyle = fill;
  1270. ctx.fill();
  1271. ctx.strokeStyle = '#66f0d1';
  1272. ctx.lineWidth = 2;
  1273. ctx.beginPath();
  1274. liveSignalRects = [];
  1275. for (let x = 0; x < w; x++) {
  1276. const f1 = startHz + (x / w) * (endHz - startHz);
  1277. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  1278. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  1279. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  1280. const v = maxInBinRange(display, b0, b1);
  1281. const y = h - ((v - minDb) / (maxDb - minDb)) * (h - 18) - 6;
  1282. if (x === 0) ctx.moveTo(x, y);
  1283. else ctx.lineTo(x, y);
  1284. }
  1285. ctx.stroke();
  1286. drawThresholdOverlay(ctx, w, h, minDb, maxDb);
  1287. if (Array.isArray(latest.signals)) {
  1288. latest.signals.forEach((s, index) => {
  1289. const left = s.center_hz - s.bw_hz / 2;
  1290. const right = s.center_hz + s.bw_hz / 2;
  1291. if (right < startHz || left > endHz) return;
  1292. const x1 = ((left - startHz) / (endHz - startHz)) * w;
  1293. const x2 = ((right - startHz) / (endHz - startHz)) * w;
  1294. const boxW = Math.max(2, x2 - x1);
  1295. const primaryMode = getSignalPrimaryMode(s);
  1296. const mc = modColor(primaryMode);
  1297. const rdsName = s.class?.pll?.rds_station || '';
  1298. const runtimeInfo = getSignalRuntimeSummary(s);
  1299. // Signal box with modulation-based color
  1300. ctx.fillStyle = modColorStr(primaryMode, 0.10);
  1301. ctx.strokeStyle = modColorStr(primaryMode, 0.75);
  1302. ctx.lineWidth = 1.5;
  1303. ctx.fillRect(x1, 10, boxW, h - 28);
  1304. ctx.strokeRect(x1, 10, boxW, h - 28);
  1305. if (matchesListenTarget(s)) {
  1306. ctx.strokeStyle = 'rgba(255, 92, 92, 0.95)';
  1307. ctx.lineWidth = 2.5;
  1308. ctx.strokeRect(x1 - 1, 9, boxW + 2, h - 26);
  1309. }
  1310. // Label badges with dark background for readability
  1311. const labelX = Math.max(4, x1 + 4);
  1312. const baseY = 14;
  1313. const freqStr = `${(s.center_hz / 1e6).toFixed(4)} MHz`;
  1314. // Badge background
  1315. const badgeH = rdsName ? 42 : ((primaryMode || runtimeInfo) ? 30 : 16);
  1316. const freqW = ctx.measureText ? 0 : 0; // will measure below
  1317. ctx.font = '11px Inter, sans-serif';
  1318. const line2 = runtimeInfo || primaryMode;
  1319. const textW = Math.max(ctx.measureText(freqStr).width, line2 ? ctx.measureText(line2).width : 0, rdsName ? ctx.measureText(rdsName).width : 0) + 8;
  1320. ctx.fillStyle = 'rgba(7, 16, 24, 0.82)';
  1321. ctx.fillRect(labelX - 3, baseY, textW, badgeH);
  1322. // Line 1: Frequency (teal)
  1323. ctx.fillStyle = 'rgba(102, 240, 209, 0.95)';
  1324. ctx.font = '11px Inter, sans-serif';
  1325. ctx.fillText(freqStr, labelX, baseY + 11);
  1326. // Line 2: runtime info first, then primary mode
  1327. if (runtimeInfo || primaryMode) {
  1328. ctx.fillStyle = mc.label;
  1329. ctx.font = 'bold 10px Inter, sans-serif';
  1330. ctx.fillText(runtimeInfo || primaryMode, labelX, baseY + 23);
  1331. }
  1332. // Line 3: RDS station name (white bold)
  1333. if (rdsName) {
  1334. ctx.fillStyle = 'rgba(255, 255, 255, 0.95)';
  1335. ctx.font = 'bold 12px Inter, sans-serif';
  1336. ctx.fillText(rdsName, labelX, baseY + 36);
  1337. }
  1338. const debugMatch = (latest?.debug?.scores || []).find((d) => Math.abs((d.center_hz || 0) - (s.center_hz || 0)) < Math.max(500, s.bw_hz || 0));
  1339. if (debugMatch?.scores && (!s.class || !s.class.scores)) {
  1340. s.debug_scores = debugMatch.scores;
  1341. }
  1342. liveSignalRects.push({
  1343. x: x1,
  1344. y: 10,
  1345. w: boxW,
  1346. h: h - 28,
  1347. signal: s,
  1348. });
  1349. });
  1350. }
  1351. }
  1352. function renderWaterfall() {
  1353. if (!latest) return;
  1354. const ctx = waterfallCanvas.getContext('2d');
  1355. const w = waterfallCanvas.width;
  1356. const h = waterfallCanvas.height;
  1357. const prev = ctx.getImageData(0, 0, w, h - 1);
  1358. ctx.putImageData(prev, 0, 1);
  1359. const display = getProcessedSpectrum();
  1360. if (!display) return;
  1361. const n = display.length;
  1362. const span = latest.sample_rate / zoom;
  1363. const startHz = latest.center_hz - span / 2 + pan * span;
  1364. const endHz = latest.center_hz + span / 2 + pan * span;
  1365. const minDb = -120;
  1366. const maxDb = 0;
  1367. const row = ctx.createImageData(w, 1);
  1368. for (let x = 0; x < w; x++) {
  1369. const f1 = startHz + (x / w) * (endHz - startHz);
  1370. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  1371. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  1372. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  1373. const v = maxInBinRange(display, b0, b1);
  1374. const norm = Math.max(0, Math.min(1, (v - minDb) / (maxDb - minDb)));
  1375. const [r, g, b] = colorMap(norm);
  1376. row.data[x * 4] = r;
  1377. row.data[x * 4 + 1] = g;
  1378. row.data[x * 4 + 2] = b;
  1379. row.data[x * 4 + 3] = 255;
  1380. }
  1381. ctx.putImageData(row, 0, 0);
  1382. drawCfarEdgeOverlay(ctx, w, h, startHz, endHz);
  1383. // Waterfall signal markers: thin vertical lines at signal center frequencies
  1384. if (Array.isArray(latest.signals)) {
  1385. latest.signals.forEach(s => {
  1386. if (!s.center_hz) return;
  1387. const xc = ((s.center_hz - startHz) / (endHz - startHz)) * w;
  1388. if (xc < 0 || xc > w) return;
  1389. const mod = s.class?.mod_type || '';
  1390. ctx.strokeStyle = modColorStr(mod, 0.35);
  1391. ctx.lineWidth = 1;
  1392. ctx.setLineDash([2, 3]);
  1393. ctx.beginPath();
  1394. ctx.moveTo(xc, 0);
  1395. ctx.lineTo(xc, h);
  1396. ctx.stroke();
  1397. ctx.setLineDash([]);
  1398. });
  1399. }
  1400. }
  1401. function renderOccupancy() {
  1402. const ctx = occupancyCanvas.getContext('2d');
  1403. const w = occupancyCanvas.width;
  1404. const h = occupancyCanvas.height;
  1405. ctx.clearRect(0, 0, w, h);
  1406. ctx.fillStyle = '#071018';
  1407. ctx.fillRect(0, 0, w, h);
  1408. if (!latest || events.length === 0) return;
  1409. const bins = new Array(Math.max(32, Math.min(160, Math.floor(w / 8)))).fill(0);
  1410. const bandStart = latest.center_hz - latest.sample_rate / 2;
  1411. const bandEnd = latest.center_hz + latest.sample_rate / 2;
  1412. const now = Date.now();
  1413. const windowStart = now - timelineWindowMs;
  1414. for (const ev of events) {
  1415. if (ev.end_ms < windowStart || ev.start_ms > now) continue;
  1416. const left = ev.center_hz - ev.bandwidth_hz / 2;
  1417. const right = ev.center_hz + ev.bandwidth_hz / 2;
  1418. const normL = Math.max(0, Math.min(1, (left - bandStart) / (bandEnd - bandStart)));
  1419. const normR = Math.max(0, Math.min(1, (right - bandStart) / (bandEnd - bandStart)));
  1420. let b0 = Math.floor(normL * bins.length);
  1421. let b1 = Math.floor(normR * bins.length);
  1422. if (b1 < b0) [b0, b1] = [b1, b0];
  1423. for (let i = Math.max(0, b0); i <= Math.min(bins.length - 1, b1); i++) {
  1424. bins[i] += Math.max(0.3, (ev.snr_db || 0) / 12 + 1);
  1425. }
  1426. }
  1427. const maxBin = Math.max(1, ...bins);
  1428. bins.forEach((v, i) => {
  1429. const norm = v / maxBin;
  1430. const [r, g, b] = colorMap(norm);
  1431. ctx.fillStyle = `rgb(${r}, ${g}, ${b})`;
  1432. const x = (i / bins.length) * w;
  1433. const bw = Math.ceil(w / bins.length) + 1;
  1434. ctx.fillRect(x, 0, bw, h);
  1435. });
  1436. }
  1437. function renderTimeline() {
  1438. const ctx = timelineCanvas.getContext('2d');
  1439. const w = timelineCanvas.width;
  1440. const h = timelineCanvas.height;
  1441. ctx.clearRect(0, 0, w, h);
  1442. ctx.fillStyle = '#071018';
  1443. ctx.fillRect(0, 0, w, h);
  1444. if (events.length === 0) {
  1445. timelineRangeEl.textContent = 'No events yet';
  1446. return;
  1447. }
  1448. const endMs = Date.now();
  1449. const startMs = endMs - timelineWindowMs;
  1450. timelineRangeEl.textContent = `${new Date(startMs).toLocaleTimeString()} - ${new Date(endMs).toLocaleTimeString()}`;
  1451. let minHz = Infinity;
  1452. let maxHz = -Infinity;
  1453. if (latest) {
  1454. minHz = latest.center_hz - latest.sample_rate / 2;
  1455. maxHz = latest.center_hz + latest.sample_rate / 2;
  1456. } else {
  1457. for (const ev of events) {
  1458. minHz = Math.min(minHz, ev.center_hz - ev.bandwidth_hz / 2);
  1459. maxHz = Math.max(maxHz, ev.center_hz + ev.bandwidth_hz / 2);
  1460. }
  1461. }
  1462. if (!isFinite(minHz) || !isFinite(maxHz) || minHz === maxHz) {
  1463. minHz = 0;
  1464. maxHz = 1;
  1465. }
  1466. ctx.strokeStyle = 'rgba(86, 109, 148, 0.18)';
  1467. ctx.lineWidth = 1;
  1468. for (let i = 1; i < 6; i++) {
  1469. const y = (h / 6) * i;
  1470. ctx.beginPath();
  1471. ctx.moveTo(0, y);
  1472. ctx.lineTo(w, y);
  1473. ctx.stroke();
  1474. }
  1475. for (let i = 1; i < 8; i++) {
  1476. const x = (w / 8) * i;
  1477. ctx.beginPath();
  1478. ctx.moveTo(x, 0);
  1479. ctx.lineTo(x, h);
  1480. ctx.stroke();
  1481. }
  1482. timelineRects = [];
  1483. for (const ev of events) {
  1484. if (ev.end_ms < startMs || ev.start_ms > endMs) continue;
  1485. const x1 = ((Math.max(ev.start_ms, startMs) - startMs) / (endMs - startMs)) * w;
  1486. const x2 = ((Math.min(ev.end_ms, endMs) - startMs) / (endMs - startMs)) * w;
  1487. const topHz = ev.center_hz + ev.bandwidth_hz / 2;
  1488. const bottomHz = ev.center_hz - ev.bandwidth_hz / 2;
  1489. const y1 = ((maxHz - topHz) / (maxHz - minHz)) * h;
  1490. const y2 = ((maxHz - bottomHz) / (maxHz - minHz)) * h;
  1491. const rect = { x: x1, y: y1, w: Math.max(2, x2 - x1), h: Math.max(3, y2 - y1), id: ev.id };
  1492. timelineRects.push(rect);
  1493. ctx.fillStyle = snrColor(ev.snr_db || 0).replace('rgb', 'rgba').replace(')', ', 0.85)');
  1494. ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
  1495. }
  1496. if (selectedEventId) {
  1497. const hit = timelineRects.find(r => r.id === selectedEventId);
  1498. if (hit) {
  1499. ctx.strokeStyle = '#ffffff';
  1500. ctx.lineWidth = 2;
  1501. ctx.strokeRect(hit.x - 1, hit.y - 1, hit.w + 2, hit.h + 2);
  1502. }
  1503. }
  1504. }
  1505. function renderDetailSpectrogram() {
  1506. const ev = eventsById.get(selectedEventId);
  1507. const ctx = detailSpectrogram.getContext('2d');
  1508. const w = detailSpectrogram.width;
  1509. const h = detailSpectrogram.height;
  1510. ctx.clearRect(0, 0, w, h);
  1511. ctx.fillStyle = '#071018';
  1512. ctx.fillRect(0, 0, w, h);
  1513. if (!latest || !ev) return;
  1514. const display = getProcessedSpectrum();
  1515. if (!display) return;
  1516. const n = display.length;
  1517. const localSpan = Math.min(latest.sample_rate, Math.max(ev.bandwidth_hz * 4, latest.sample_rate / 10));
  1518. const startHz = ev.center_hz - localSpan / 2;
  1519. const endHz = ev.center_hz + localSpan / 2;
  1520. const minDb = -120;
  1521. const maxDb = 0;
  1522. const row = ctx.createImageData(w, 1);
  1523. for (let x = 0; x < w; x++) {
  1524. const f1 = startHz + (x / w) * (endHz - startHz);
  1525. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  1526. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  1527. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  1528. const v = maxInBinRange(display, b0, b1);
  1529. const norm = Math.max(0, Math.min(1, (v - minDb) / (maxDb - minDb)));
  1530. const [r, g, b] = colorMap(norm);
  1531. row.data[x * 4] = r;
  1532. row.data[x * 4 + 1] = g;
  1533. row.data[x * 4 + 2] = b;
  1534. row.data[x * 4 + 3] = 255;
  1535. }
  1536. for (let y = 0; y < h; y++) ctx.putImageData(row, 0, y);
  1537. const centerX = w / 2;
  1538. ctx.strokeStyle = 'rgba(255,255,255,0.65)';
  1539. ctx.lineWidth = 1;
  1540. ctx.beginPath();
  1541. ctx.moveTo(centerX, 0);
  1542. ctx.lineTo(centerX, h);
  1543. ctx.stroke();
  1544. }
  1545. let _lastEventListKey = '';
  1546. function updateSignalDecisionSummary(id) {
  1547. if (!signalDecisionSummary) return;
  1548. if (!id) {
  1549. signalDecisionSummary.textContent = 'Decision: -';
  1550. return;
  1551. }
  1552. const dec = decisionIndex.get(String(id));
  1553. if (!dec) {
  1554. signalDecisionSummary.textContent = 'Decision: -';
  1555. return;
  1556. }
  1557. const flags = `${dec.record ? 'REC' : ''}${dec.decode ? (dec.record ? '+DEC' : 'DEC') : ''}` || 'none';
  1558. const reason = dec.reason ? ` · ${dec.reason}` : '';
  1559. signalDecisionSummary.textContent = `Decision: ${flags}${reason}`;
  1560. }
  1561. function setSelectedSignal(sel) {
  1562. window._selectedSignal = sel || null;
  1563. signalList.querySelectorAll('.signal-item').forEach((el) => {
  1564. const active = !!sel && ((sel.key && el.dataset.key === sel.key) || (!sel.key && sel.id && el.dataset.id === String(sel.id)));
  1565. el.classList.toggle('active', active);
  1566. });
  1567. updateSignalDecisionSummary(window._selectedSignal?.id);
  1568. updateSignalQueueSummary();
  1569. }
  1570. function getSignalDomKey(s) {
  1571. if (s?.id != null && s.id !== '') return `id:${s.id}`;
  1572. const center = Math.round(Number(s?.center_hz || 0));
  1573. const bw = Math.round(Number(s?.bw_hz || 0));
  1574. const mode = getSignalPrimaryMode(s) || s?.class?.mod_type || 'UNK';
  1575. const rds = s?.class?.pll?.rds_station || '';
  1576. return `sig:${center}:${bw}:${mode}:${rds}`;
  1577. }
  1578. function _createSignalItem(s) {
  1579. const btn = document.createElement('button');
  1580. btn.className = 'list-item signal-item';
  1581. btn.type = 'button';
  1582. btn.dataset.center = s.center_hz;
  1583. btn.dataset.bw = s.bw_hz || 0;
  1584. btn.dataset.class = s.class?.mod_type || '';
  1585. btn.dataset.id = s.id ?? '';
  1586. btn.dataset.key = getSignalDomKey(s);
  1587. const primaryMode = getSignalPrimaryMode(s);
  1588. const runtimeInfo = getSignalRuntimeSummary(s);
  1589. const mc = modColor(primaryMode);
  1590. const rds = s.class?.pll?.rds_station || '';
  1591. const dec = decisionIndex.get(String(s.id || 0));
  1592. const decText = dec?.reason ? `${dec.reason}` : '';
  1593. const decFlags = dec ? `${dec.record ? 'REC' : ''}${dec.decode ? (dec.record ? '+DEC' : 'DEC') : ''}` : '';
  1594. const metaBits = [];
  1595. if (decFlags) metaBits.push(decFlags);
  1596. if (decText) metaBits.push(decText);
  1597. if (runtimeInfo) metaBits.push(runtimeInfo);
  1598. btn.title = metaBits.join(' · ');
  1599. 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 item-meta--runtime" data-field="mode" style="color:${mc.label}">${primaryMode}</span>${rds ? `<span class="item-meta item-meta--rds" data-field="rds">${rds}</span>` : ''}</div>`;
  1600. btn.style.borderLeftColor = mc.label;
  1601. btn.style.borderLeftWidth = '3px';
  1602. btn.style.borderLeftStyle = 'solid';
  1603. if (matchesListenTarget(s)) btn.classList.add('listening');
  1604. return btn;
  1605. }
  1606. function _patchSignalItem(el, s) {
  1607. const freqEl = el.querySelector('[data-field="freq"]');
  1608. const snrEl = el.querySelector('[data-field="snr"]');
  1609. const modeEl = el.querySelector('[data-field="mode"]');
  1610. const mod = s.class?.mod_type || '';
  1611. const primaryMode = getSignalPrimaryMode(s);
  1612. const runtimeInfo = getSignalRuntimeSummary(s);
  1613. const mc = modColor(primaryMode);
  1614. const rds = s.class?.pll?.rds_station || '';
  1615. const rdsEl = el.querySelector('[data-field="rds"]');
  1616. const dec = decisionIndex.get(String(s.id || 0));
  1617. const decText = dec?.reason ? `${dec.reason}` : '';
  1618. const decFlags = dec ? `${dec.record ? 'REC' : ''}${dec.decode ? (dec.record ? '+DEC' : 'DEC') : ''}` : '';
  1619. const metaBits = [];
  1620. if (decFlags) metaBits.push(decFlags);
  1621. if (decText) metaBits.push(decText);
  1622. if (runtimeInfo) metaBits.push(runtimeInfo);
  1623. el.title = metaBits.join(' · ');
  1624. if (freqEl) freqEl.textContent = fmtMHz(s.center_hz, 6);
  1625. if (snrEl) { snrEl.textContent = `${(s.snr_db || 0).toFixed(1)} dB`; snrEl.style.color = snrColor(s.snr_db || 0); }
  1626. if (modeEl) { modeEl.textContent = primaryMode; modeEl.style.color = mc.label; }
  1627. if (rdsEl) {
  1628. rdsEl.textContent = rds;
  1629. rdsEl.style.display = rds ? '' : 'none';
  1630. } else if (rds) {
  1631. const span = document.createElement('span');
  1632. span.className = 'item-meta item-meta--rds';
  1633. span.dataset.field = 'rds';
  1634. span.textContent = rds;
  1635. el.querySelector('.item-bottom')?.appendChild(span);
  1636. }
  1637. el.dataset.center = s.center_hz;
  1638. el.dataset.bw = s.bw_hz || 0;
  1639. el.dataset.class = mod;
  1640. el.dataset.id = s.id ?? '';
  1641. el.dataset.key = getSignalDomKey(s);
  1642. el.style.borderLeftColor = mc.label;
  1643. el.classList.toggle('listening', matchesListenTarget(s));
  1644. }
  1645. function renderLists() {
  1646. const signals = Array.isArray(latest?.signals) ? [...latest.signals] : [];
  1647. signals.sort((a, b) => (b.snr_db || 0) - (a.snr_db || 0));
  1648. signalCountBadge.textContent = `${signals.length} live`;
  1649. metricSignals.textContent = String(signals.length);
  1650. const displaySigs = signals.slice(0, 24);
  1651. const strongest = displaySigs[0] || null;
  1652. const selectedSignal = window._selectedSignal || null;
  1653. if (signalSummaryLine) {
  1654. const strongestText = strongest
  1655. ? `${fmtMHz(strongest.center_hz, 4)} · ${(strongest.snr_db || 0).toFixed(1)} dB`
  1656. : '-';
  1657. const selectedText = selectedSignal && Number.isFinite(selectedSignal.freq)
  1658. ? `${fmtMHz(selectedSignal.freq, 4)}${selectedSignal.mode ? ` · ${selectedSignal.mode}` : ''}`
  1659. : '-';
  1660. signalSummaryLine.textContent = `Visible: ${displaySigs.length} · Strongest: ${strongestText} · Selected: ${selectedText}`;
  1661. }
  1662. if (displaySigs.length === 0) {
  1663. signalList.innerHTML = '<div class="empty-state">No live signals yet.</div>';
  1664. } else {
  1665. const existing = new Map();
  1666. signalList.querySelectorAll('.signal-item').forEach((el) => existing.set(el.dataset.key, el));
  1667. const frag = document.createDocumentFragment();
  1668. displaySigs.forEach((s) => {
  1669. const key = getSignalDomKey(s);
  1670. let el = existing.get(key);
  1671. if (el) {
  1672. _patchSignalItem(el, s);
  1673. } else {
  1674. el = _createSignalItem(s);
  1675. }
  1676. if (window._selectedSignal) {
  1677. const selectedKey = window._selectedSignal.key;
  1678. const selectedId = window._selectedSignal.id;
  1679. const sameKey = selectedKey && key === selectedKey;
  1680. const sameId = !selectedKey && selectedId && s.id != null && String(s.id) === String(selectedId);
  1681. const nearFreq = !selectedKey && !selectedId && Number.isFinite(window._selectedSignal.freq) && Math.abs(s.center_hz - window._selectedSignal.freq) < 2500;
  1682. el.classList.toggle('active', !!(sameKey || sameId || nearFreq));
  1683. } else {
  1684. el.classList.remove('active');
  1685. }
  1686. frag.appendChild(el);
  1687. existing.delete(key);
  1688. });
  1689. signalList.innerHTML = '';
  1690. signalList.appendChild(frag);
  1691. }
  1692. const recent = [...events].sort((a, b) => b.end_ms - a.end_ms);
  1693. eventCountBadge.textContent = `${recent.length} stored`;
  1694. const evtKey = `${recent.length}:${selectedEventId}:${recent.slice(0, 5).map(e => e.id).join(',')}`;
  1695. if (evtKey !== _lastEventListKey) {
  1696. _lastEventListKey = evtKey;
  1697. if (recent.length === 0) {
  1698. eventList.innerHTML = '<div class="empty-state">No events yet.</div>';
  1699. } else {
  1700. eventList.innerHTML = recent.slice(0, 40).map((ev) => `
  1701. <button class="list-item event-item ${selectedEventId === ev.id ? 'active' : ''}" type="button" data-event-id="${ev.id}">
  1702. <div class="item-top">
  1703. <span class="item-title">${fmtMHz(ev.center_hz, 6)}</span>
  1704. <span class="item-badge" style="color:${snrColor(ev.snr_db || 0)}">${(ev.snr_db || 0).toFixed(1)} dB</span>
  1705. </div>
  1706. <div class="item-bottom">
  1707. <span class="item-meta">${fmtKHz(ev.bandwidth_hz || 0)} · ${fmtMs(ev.duration_ms || 0)}</span>
  1708. <span class="item-meta">${new Date(ev.end_ms).toLocaleTimeString()}</span>
  1709. </div>
  1710. </button>
  1711. `).join('');
  1712. }
  1713. }
  1714. if (recordingList && recordingCountBadge) {
  1715. recordingCountBadge.textContent = `${recordings.length}`;
  1716. if (recordings.length === 0) {
  1717. recordingList.innerHTML = '<div class="empty-state">No recordings yet.</div>';
  1718. } else {
  1719. recordingList.innerHTML = recordings.slice(0, 50).map((rec) => `
  1720. <button class="list-item recording-item" type="button" data-id="${rec.id}">
  1721. <div class="item-top">
  1722. <span class="item-title">${new Date(rec.start).toLocaleString()}</span>
  1723. <span class="item-badge">${fmtMHz(rec.center_hz || 0, 6)}</span>
  1724. </div>
  1725. <div class="item-bottom">
  1726. <span class="item-meta">${rec.id}</span>
  1727. <span class="item-meta">recording</span>
  1728. </div>
  1729. </button>
  1730. `).join('');
  1731. }
  1732. }
  1733. updateSignalDecisionSummary(window._selectedSignal?.id);
  1734. }
  1735. function normalizeEvent(ev) {
  1736. const startMs = new Date(ev.start).getTime();
  1737. const endMs = new Date(ev.end).getTime();
  1738. return {
  1739. ...ev,
  1740. start_ms: startMs,
  1741. end_ms: endMs,
  1742. duration_ms: Math.max(0, endMs - startMs),
  1743. };
  1744. }
  1745. function upsertEvents(list, replace = false) {
  1746. if (replace) {
  1747. events.length = 0;
  1748. eventsById.clear();
  1749. }
  1750. for (const raw of list) {
  1751. if (!raw || !raw.id || eventsById.has(raw.id)) continue;
  1752. const ev = normalizeEvent(raw);
  1753. eventsById.set(ev.id, ev);
  1754. events.push(ev);
  1755. }
  1756. events.sort((a, b) => a.end_ms - b.end_ms);
  1757. const maxEvents = 1500;
  1758. if (events.length > maxEvents) {
  1759. const drop = events.length - maxEvents;
  1760. for (let i = 0; i < drop; i++) eventsById.delete(events[i].id);
  1761. events.splice(0, drop);
  1762. }
  1763. if (events.length > 0) lastEventEndMs = events[events.length - 1].end_ms;
  1764. renderLists();
  1765. }
  1766. async function fetchEvents(initial) {
  1767. if (eventsFetchInFlight || timelineFrozen || !apiClient) return;
  1768. eventsFetchInFlight = true;
  1769. try {
  1770. const query = initial
  1771. ? { limit: 1000 }
  1772. : (lastEventEndMs > 0 ? { since: lastEventEndMs - 1 } : { limit: 200 });
  1773. const res = await apiClient.getEvents(query);
  1774. updateApiState(res);
  1775. if (res.ok && Array.isArray(res.data)) upsertEvents(res.data, initial);
  1776. } finally {
  1777. eventsFetchInFlight = false;
  1778. }
  1779. }
  1780. async function fetchRecordings() {
  1781. if (recordingsFetchInFlight || !recordingList || !apiClient) return;
  1782. recordingsFetchInFlight = true;
  1783. try {
  1784. const res = await apiClient.getRecordings();
  1785. updateApiState(res);
  1786. if (res.ok && Array.isArray(res.data)) {
  1787. recordings = res.data;
  1788. renderLists();
  1789. }
  1790. } finally {
  1791. recordingsFetchInFlight = false;
  1792. }
  1793. }
  1794. function openDrawer(ev) {
  1795. if (!ev) return;
  1796. selectedEventId = ev.id;
  1797. detailSubtitle.textContent = `Event ${ev.id}`;
  1798. detailCenterEl.textContent = fmtMHz(ev.center_hz, 6);
  1799. detailBwEl.textContent = fmtKHz(ev.bandwidth_hz || 0);
  1800. detailStartEl.textContent = new Date(ev.start_ms).toLocaleString();
  1801. detailEndEl.textContent = new Date(ev.end_ms).toLocaleString();
  1802. detailSnrEl.textContent = `${(ev.snr_db || 0).toFixed(1)} dB`;
  1803. detailDurEl.textContent = fmtMs(ev.duration_ms || 0);
  1804. detailClassEl.textContent = ev.class?.mod_type || '-';
  1805. if (classifierScoresEl) {
  1806. const scores = ev.class?.scores;
  1807. if (scores && typeof scores === 'object') {
  1808. const rows = Object.entries(scores)
  1809. .sort((a, b) => b[1] - a[1])
  1810. .slice(0, 6)
  1811. .map(([k, v]) => `${k}:${v.toFixed(2)}`)
  1812. .join(' · ');
  1813. classifierScoresEl.textContent = rows ? `Classifier scores: ${rows}` : 'Classifier scores: -';
  1814. renderScoreBars(scores);
  1815. } else {
  1816. const liveScores = (latest?.debug?.scores || []).find((s) => Math.abs((s.center_hz || 0) - (ev.center_hz || 0)) < Math.max(500, (ev.bandwidth_hz || 0)));
  1817. if (liveScores?.scores) {
  1818. const rows = Object.entries(liveScores.scores)
  1819. .sort((a, b) => b[1] - a[1])
  1820. .slice(0, 6)
  1821. .map(([k, v]) => `${k}:${Number(v).toFixed(2)}`)
  1822. .join(' · ');
  1823. classifierScoresEl.textContent = rows ? `Classifier scores: ${rows}` : 'Classifier scores: -';
  1824. renderScoreBars(liveScores.scores);
  1825. } else {
  1826. classifierScoresEl.textContent = 'Classifier scores: -';
  1827. renderScoreBars(null);
  1828. }
  1829. }
  1830. }
  1831. if (recordingMetaEl) {
  1832. recordingMetaEl.textContent = 'Recording: -';
  1833. }
  1834. if (recordingMetaLink) {
  1835. recordingMetaLink.href = '#';
  1836. recordingIQLink.href = '#';
  1837. recordingAudioLink.href = '#';
  1838. }
  1839. drawerEl.classList.add('open');
  1840. drawerEl.setAttribute('aria-hidden', 'false');
  1841. renderDetailSpectrogram();
  1842. renderLists();
  1843. }
  1844. function closeDrawer() {
  1845. drawerEl.classList.remove('open');
  1846. drawerEl.setAttribute('aria-hidden', 'true');
  1847. selectedEventId = null;
  1848. renderLists();
  1849. }
  1850. function fitView() {
  1851. zoom = 1;
  1852. pan = 0;
  1853. followLive = true;
  1854. }
  1855. function tuneToFrequency(centerHz) {
  1856. if (!Number.isFinite(centerHz)) return;
  1857. followLive = true;
  1858. centerInput.value = (centerHz / 1e6).toFixed(6);
  1859. queueConfigUpdate({ center_hz: centerHz });
  1860. }
  1861. function connect() {
  1862. clearTimeout(wsReconnectTimer);
  1863. const proto = location.protocol === 'https:' ? 'wss' : 'ws';
  1864. // Remote optimization: detect non-localhost and opt into binary + decimation
  1865. const hn = location.hostname;
  1866. const isLocal = ['localhost', '127.0.0.1', '::1'].includes(hn)
  1867. || hn.startsWith('192.168.')
  1868. || hn.startsWith('10.')
  1869. || /^172\.(1[6-9]|2\d|3[01])\./.test(hn)
  1870. || hn.endsWith('.local')
  1871. || hn.endsWith('.lan');
  1872. const params = new URLSearchParams(location.search);
  1873. const wantBinary = params.get('binary') === '1' || !isLocal;
  1874. const bins = parseInt(params.get('bins') || (isLocal ? '0' : '2048'), 10);
  1875. const fps = parseInt(params.get('fps') || (isLocal ? '0' : '10'), 10);
  1876. let wsUrl = `${proto}://${location.host}/ws`;
  1877. if (wantBinary || bins > 0 || fps > 0) {
  1878. const qp = [];
  1879. if (wantBinary) qp.push('binary=1');
  1880. if (bins > 0) qp.push(`bins=${bins}`);
  1881. if (fps > 0) qp.push(`fps=${fps}`);
  1882. wsUrl += '?' + qp.join('&');
  1883. }
  1884. const ws = new WebSocket(wsUrl);
  1885. ws.binaryType = 'arraybuffer';
  1886. setWsBadge('Connecting', 'neutral');
  1887. ws.onopen = () => {
  1888. setWsBadge('Live', 'ok');
  1889. wsLastMessageTs = Date.now();
  1890. updateOperatorStatus();
  1891. };
  1892. ws.onmessage = (ev) => {
  1893. if (ev.data instanceof ArrayBuffer) {
  1894. try {
  1895. const decoded = decodeBinaryFrame(ev.data);
  1896. if (decoded) latest = decoded;
  1897. } catch (e) {
  1898. console.warn('binary frame decode error:', e);
  1899. return;
  1900. }
  1901. } else {
  1902. latest = JSON.parse(ev.data);
  1903. }
  1904. wsLastMessageTs = Date.now();
  1905. updateOperatorStatus();
  1906. markSpectrumDirty();
  1907. if (followLive) pan = 0;
  1908. updateHeroMetrics();
  1909. renderLists();
  1910. };
  1911. ws.onclose = () => {
  1912. setWsBadge('Retrying', 'bad');
  1913. updateOperatorStatus();
  1914. wsReconnectTimer = setTimeout(connect, 1000);
  1915. };
  1916. ws.onerror = () => ws.close();
  1917. }
  1918. // Decode binary spectrum frame v4 (hybrid: binary spectrum + JSON signals)
  1919. function decodeBinaryFrame(buf) {
  1920. const view = new DataView(buf);
  1921. if (buf.byteLength < 32) return null;
  1922. // Header: 32 bytes
  1923. const magic0 = view.getUint8(0);
  1924. const magic1 = view.getUint8(1);
  1925. if (magic0 !== 0x53 || magic1 !== 0x50) return null; // not "SP"
  1926. const version = view.getUint16(2, true);
  1927. const ts = Number(view.getBigInt64(4, true));
  1928. const centerHz = view.getFloat64(12, true);
  1929. const binCount = view.getUint32(20, true);
  1930. const sampleRateHz = view.getUint32(24, true);
  1931. const jsonOffset = view.getUint32(28, true);
  1932. if (buf.byteLength < 32 + binCount * 2) return null;
  1933. // Spectrum: binCount × int16 at offset 32
  1934. const spectrum = new Float64Array(binCount);
  1935. let off = 32;
  1936. for (let i = 0; i < binCount; i++) {
  1937. spectrum[i] = view.getInt16(off, true) / 100;
  1938. off += 2;
  1939. }
  1940. // JSON signals + debug after the spectrum data
  1941. let signals = [];
  1942. let debug = null;
  1943. if (jsonOffset > 0 && jsonOffset < buf.byteLength) {
  1944. try {
  1945. const jsonBytes = new Uint8Array(buf, jsonOffset);
  1946. const jsonStr = new TextDecoder().decode(jsonBytes);
  1947. const parsed = JSON.parse(jsonStr);
  1948. signals = parsed.signals || [];
  1949. debug = parsed.debug || null;
  1950. } catch (e) {
  1951. // JSON parse failed — continue with empty signals
  1952. }
  1953. }
  1954. return {
  1955. ts: ts,
  1956. center_hz: centerHz,
  1957. sample_rate: sampleRateHz,
  1958. fft_size: binCount,
  1959. spectrum_db: spectrum,
  1960. signals: signals,
  1961. debug: debug
  1962. };
  1963. }
  1964. function renderLoop() {
  1965. renderFrames += 1;
  1966. const now = performance.now();
  1967. if (now - lastFpsTs >= 1000) {
  1968. renderFps = (renderFrames * 1000) / (now - lastFpsTs);
  1969. renderFrames = 0;
  1970. lastFpsTs = now;
  1971. }
  1972. if (latest) {
  1973. renderBandNavigator();
  1974. renderSpectrum();
  1975. renderWaterfall();
  1976. renderOccupancy();
  1977. renderTimeline();
  1978. if (drawerEl.classList.contains('open')) renderDetailSpectrogram();
  1979. }
  1980. updateHeroMetrics();
  1981. requestAnimationFrame(renderLoop);
  1982. }
  1983. function handleSpectrumClick(ev) {
  1984. const rect = spectrumCanvas.getBoundingClientRect();
  1985. const x = (ev.clientX - rect.left) * (spectrumCanvas.width / rect.width);
  1986. const y = (ev.clientY - rect.top) * (spectrumCanvas.height / rect.height);
  1987. for (let i = liveSignalRects.length - 1; i >= 0; i--) {
  1988. const r = liveSignalRects[i];
  1989. if (x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h) {
  1990. const sig = r.signal;
  1991. const freq = sig.center_hz;
  1992. const bw = sig.bw_hz || 12000;
  1993. const mode = sig.class?.mod_type || '';
  1994. startLiveListen(freq, bw, mode);
  1995. setSelectedSignal({
  1996. key: getSignalDomKey(sig),
  1997. id: sig.id ?? null,
  1998. freq,
  1999. bw,
  2000. mode
  2001. });
  2002. return;
  2003. }
  2004. }
  2005. if (!latest) return;
  2006. const span = latest.sample_rate / zoom;
  2007. const startHz = latest.center_hz - span / 2 + pan * span;
  2008. const clickedHz = startHz + (x / spectrumCanvas.width) * span;
  2009. tuneToFrequency(clickedHz);
  2010. }
  2011. function handleNavPosition(ev) {
  2012. if (!latest) return;
  2013. const rect = navCanvas.getBoundingClientRect();
  2014. const x = Math.max(0, Math.min(rect.width, ev.clientX - rect.left));
  2015. const norm = x / rect.width;
  2016. const fullStart = latest.center_hz - latest.sample_rate / 2;
  2017. const newViewCenter = fullStart + norm * latest.sample_rate;
  2018. const span = latest.sample_rate / zoom;
  2019. const desiredPan = (newViewCenter - latest.center_hz) / span;
  2020. pan = Math.max(-0.5, Math.min(0.5, desiredPan));
  2021. followLive = false;
  2022. }
  2023. function exportSelectedEvent() {
  2024. const ev = eventsById.get(selectedEventId);
  2025. if (!ev) return;
  2026. const blob = new Blob([JSON.stringify(ev, null, 2)], { type: 'application/json' });
  2027. const a = document.createElement('a');
  2028. a.href = URL.createObjectURL(blob);
  2029. a.download = `event-${ev.id}.json`;
  2030. a.click();
  2031. URL.revokeObjectURL(a.href);
  2032. }
  2033. spectrumCanvas.addEventListener('wheel', (ev) => {
  2034. ev.preventDefault();
  2035. const direction = Math.sign(ev.deltaY);
  2036. zoom = Math.max(0.25, Math.min(24, zoom * (direction > 0 ? 1.12 : 0.89)));
  2037. followLive = false;
  2038. });
  2039. spectrumCanvas.addEventListener('mousedown', (ev) => {
  2040. isDraggingSpectrum = true;
  2041. dragStartX = ev.clientX;
  2042. dragStartPan = pan;
  2043. });
  2044. window.addEventListener('mouseup', () => {
  2045. isDraggingSpectrum = false;
  2046. navDrag = false;
  2047. });
  2048. spectrumCanvas.addEventListener('mouseleave', hideSignalPopover);
  2049. window.addEventListener('mousemove', (ev) => {
  2050. const rect = spectrumCanvas.getBoundingClientRect();
  2051. const x = (ev.clientX - rect.left) * (spectrumCanvas.width / rect.width);
  2052. const y = (ev.clientY - rect.top) * (spectrumCanvas.height / rect.height);
  2053. let hoverHit = null;
  2054. for (let i = liveSignalRects.length - 1; i >= 0; i--) {
  2055. const r = liveSignalRects[i];
  2056. if (x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h) {
  2057. hoverHit = r;
  2058. break;
  2059. }
  2060. }
  2061. if (hoverHit) {
  2062. hoveredSignal = hoverHit.signal;
  2063. renderSignalPopover(hoverHit, hoverHit.signal);
  2064. } else {
  2065. hideSignalPopover();
  2066. }
  2067. if (isDraggingSpectrum) {
  2068. const dx = ev.clientX - dragStartX;
  2069. pan = Math.max(-0.5, Math.min(0.5, dragStartPan - dx / spectrumCanvas.clientWidth));
  2070. followLive = false;
  2071. }
  2072. if (navDrag) handleNavPosition(ev);
  2073. });
  2074. spectrumCanvas.addEventListener('dblclick', fitView);
  2075. spectrumCanvas.addEventListener('click', handleSpectrumClick);
  2076. navCanvas.addEventListener('mousedown', (ev) => {
  2077. navDrag = true;
  2078. handleNavPosition(ev);
  2079. });
  2080. navCanvas.addEventListener('click', handleNavPosition);
  2081. centerInput.addEventListener('change', () => {
  2082. const mhz = parseFloat(centerInput.value);
  2083. if (Number.isFinite(mhz)) tuneToFrequency(fromMHz(mhz));
  2084. });
  2085. spanInput.addEventListener('change', () => {
  2086. const mhz = parseFloat(spanInput.value);
  2087. if (!Number.isFinite(mhz) || mhz <= 0) return;
  2088. const baseRate = currentConfig?.sample_rate || latest?.sample_rate;
  2089. if (!baseRate) return;
  2090. zoom = Math.max(0.25, Math.min(24, baseRate / fromMHz(mhz)));
  2091. followLive = false;
  2092. });
  2093. sampleRateSelect.addEventListener('change', () => {
  2094. const mhz = parseFloat(sampleRateSelect.value);
  2095. if (Number.isFinite(mhz)) queueConfigUpdate({ sample_rate: Math.round(fromMHz(mhz)) });
  2096. });
  2097. bwSelect.addEventListener('change', () => {
  2098. const bw = parseInt(bwSelect.value, 10);
  2099. if (Number.isFinite(bw)) queueConfigUpdate({ tuner_bw_khz: bw });
  2100. });
  2101. fftSelect.addEventListener('change', () => {
  2102. const size = parseInt(fftSelect.value, 10);
  2103. if (Number.isFinite(size)) queueConfigUpdate({ fft_size: size });
  2104. });
  2105. gainRange.addEventListener('input', () => {
  2106. gainInput.value = gainRange.value;
  2107. const uiVal = parseFloat(gainRange.value);
  2108. if (Number.isFinite(uiVal)) queueConfigUpdate({ gain_db: Math.max(0, Math.min(GAIN_MAX, GAIN_MAX - uiVal)) });
  2109. });
  2110. gainInput.addEventListener('change', () => {
  2111. const uiVal = parseFloat(gainInput.value);
  2112. if (Number.isFinite(uiVal)) {
  2113. gainRange.value = uiVal;
  2114. queueConfigUpdate({ gain_db: Math.max(0, Math.min(GAIN_MAX, GAIN_MAX - uiVal)) });
  2115. }
  2116. });
  2117. thresholdRange.addEventListener('input', () => {
  2118. thresholdInput.value = thresholdRange.value;
  2119. queueConfigUpdate({ detector: { threshold_db: parseFloat(thresholdRange.value) } });
  2120. });
  2121. thresholdInput.addEventListener('change', () => {
  2122. const v = parseFloat(thresholdInput.value);
  2123. if (Number.isFinite(v)) {
  2124. thresholdRange.value = v;
  2125. queueConfigUpdate({ detector: { threshold_db: v } });
  2126. }
  2127. });
  2128. if (cfarModeSelect) cfarModeSelect.addEventListener('change', () => {
  2129. queueConfigUpdate({ detector: { cfar_mode: cfarModeSelect.value } });
  2130. const rankRow = cfarRankInput?.closest('.field');
  2131. if (rankRow) rankRow.style.display = (cfarModeSelect.value === 'OS') ? '' : 'none';
  2132. });
  2133. if (cfarWrapToggle) cfarWrapToggle.addEventListener('change', () => {
  2134. queueConfigUpdate({ detector: { cfar_wrap_around: cfarWrapToggle.checked } });
  2135. });
  2136. if (cfarGuardHzInput) cfarGuardHzInput.addEventListener('change', () => {
  2137. const v = parseFloat(cfarGuardHzInput.value);
  2138. if (Number.isFinite(v) && v >= 0) queueConfigUpdate({ detector: { cfar_guard_hz: v } });
  2139. });
  2140. if (cfarTrainHzInput) cfarTrainHzInput.addEventListener('change', () => {
  2141. const v = parseFloat(cfarTrainHzInput.value);
  2142. if (Number.isFinite(v) && v > 0) queueConfigUpdate({ detector: { cfar_train_hz: v } });
  2143. });
  2144. if (cfarRankInput) cfarRankInput.addEventListener('change', () => {
  2145. const v = parseInt(cfarRankInput.value, 10);
  2146. if (Number.isFinite(v)) queueConfigUpdate({ detector: { cfar_rank: v } });
  2147. });
  2148. if (cfarScaleInput) cfarScaleInput.addEventListener('change', () => {
  2149. const v = parseFloat(cfarScaleInput.value);
  2150. if (Number.isFinite(v)) queueConfigUpdate({ detector: { cfar_scale_db: v } });
  2151. });
  2152. if (minDurationInput) minDurationInput.addEventListener('change', () => {
  2153. const v = parseInt(minDurationInput.value, 10);
  2154. if (Number.isFinite(v)) queueConfigUpdate({ detector: { min_duration_ms: v } });
  2155. });
  2156. if (holdInput) holdInput.addEventListener('change', () => {
  2157. const v = parseInt(holdInput.value, 10);
  2158. if (Number.isFinite(v)) queueConfigUpdate({ detector: { hold_ms: v } });
  2159. });
  2160. if (emaAlphaInput) emaAlphaInput.addEventListener('change', () => {
  2161. const v = parseFloat(emaAlphaInput.value);
  2162. if (Number.isFinite(v)) queueConfigUpdate({ detector: { ema_alpha: v } });
  2163. });
  2164. if (hysteresisInput) hysteresisInput.addEventListener('change', () => {
  2165. const v = parseFloat(hysteresisInput.value);
  2166. if (Number.isFinite(v)) queueConfigUpdate({ detector: { hysteresis_db: v } });
  2167. });
  2168. if (stableFramesInput) stableFramesInput.addEventListener('change', () => {
  2169. const v = parseInt(stableFramesInput.value, 10);
  2170. if (Number.isFinite(v)) queueConfigUpdate({ detector: { min_stable_frames: v } });
  2171. });
  2172. if (gapToleranceInput) gapToleranceInput.addEventListener('change', () => {
  2173. const v = parseInt(gapToleranceInput.value, 10);
  2174. if (Number.isFinite(v)) queueConfigUpdate({ detector: { gap_tolerance_ms: v } });
  2175. });
  2176. if (classifierModeSelect) classifierModeSelect.addEventListener('change', () => {
  2177. queueConfigUpdate({ classifier_mode: classifierModeSelect.value });
  2178. });
  2179. if (edgeMarginInput) edgeMarginInput.addEventListener('change', () => {
  2180. const v = parseFloat(edgeMarginInput.value);
  2181. if (Number.isFinite(v) && v >= 0) queueConfigUpdate({ detector: { edge_margin_db: v } });
  2182. });
  2183. if (mergeGapInput) mergeGapInput.addEventListener('change', () => {
  2184. const v = parseFloat(mergeGapInput.value);
  2185. if (Number.isFinite(v)) queueConfigUpdate({ detector: { merge_gap_hz: v } });
  2186. });
  2187. if (classHistoryInput) classHistoryInput.addEventListener('change', () => {
  2188. const v = parseInt(classHistoryInput.value, 10);
  2189. if (Number.isFinite(v) && v >= 1) queueConfigUpdate({ detector: { class_history_size: v } });
  2190. });
  2191. if (classSwitchInput) classSwitchInput.addEventListener('change', () => {
  2192. const v = parseFloat(classSwitchInput.value);
  2193. if (Number.isFinite(v) && v >= 0.1 && v <= 1.0) queueConfigUpdate({ detector: { class_switch_ratio: v } });
  2194. });
  2195. agcToggle.addEventListener('change', () => queueSettingsUpdate({ agc: agcToggle.checked }));
  2196. dcToggle.addEventListener('change', () => queueSettingsUpdate({ dc_block: dcToggle.checked }));
  2197. iqToggle.addEventListener('change', () => queueSettingsUpdate({ iq_balance: iqToggle.checked }));
  2198. gpuToggle.addEventListener('change', () => queueConfigUpdate({ use_gpu_fft: gpuToggle.checked }));
  2199. if (recEnableToggle) recEnableToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { enabled: recEnableToggle.checked } }));
  2200. if (recIQToggle) recIQToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { record_iq: recIQToggle.checked } }));
  2201. if (recAudioToggle) recAudioToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { record_audio: recAudioToggle.checked } }));
  2202. if (recDemodToggle) recDemodToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { auto_demod: recDemodToggle.checked } }));
  2203. if (recDecodeToggle) recDecodeToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { auto_decode: recDecodeToggle.checked } }));
  2204. if (recMinSNR) recMinSNR.addEventListener('change', () => queueConfigUpdate({ recorder: { min_snr_db: parseFloat(recMinSNR.value) } }));
  2205. if (recMaxDisk) recMaxDisk.addEventListener('change', () => queueConfigUpdate({ recorder: { max_disk_mb: parseInt(recMaxDisk.value || '0', 10) } }));
  2206. if (recClassFilter) recClassFilter.addEventListener('change', () => {
  2207. const list = (recClassFilter.value || '')
  2208. .split(',')
  2209. .map(s => s.trim())
  2210. .filter(Boolean);
  2211. queueConfigUpdate({ recorder: { class_filter: list } });
  2212. });
  2213. if (refineAutoSpan) refineAutoSpan.addEventListener('change', () => {
  2214. queueConfigUpdate({ refinement: { auto_span: refineAutoSpan.value === 'true' } });
  2215. });
  2216. if (refineMinSpan) refineMinSpan.addEventListener('change', () => {
  2217. const v = parseFloat(refineMinSpan.value);
  2218. if (Number.isFinite(v)) queueConfigUpdate({ refinement: { min_span_hz: v } });
  2219. });
  2220. if (refineMaxSpan) refineMaxSpan.addEventListener('change', () => {
  2221. const v = parseFloat(refineMaxSpan.value);
  2222. if (Number.isFinite(v)) queueConfigUpdate({ refinement: { max_span_hz: v } });
  2223. });
  2224. if (resMaxRefine) resMaxRefine.addEventListener('change', () => {
  2225. const v = parseInt(resMaxRefine.value || '0', 10);
  2226. queueConfigUpdate({ resources: { max_refinement_jobs: v } });
  2227. });
  2228. if (resMaxRecord) resMaxRecord.addEventListener('change', () => {
  2229. const v = parseInt(resMaxRecord.value || '0', 10);
  2230. queueConfigUpdate({ resources: { max_recording_streams: v } });
  2231. });
  2232. if (resMaxDecode) resMaxDecode.addEventListener('change', () => {
  2233. const v = parseInt(resMaxDecode.value || '0', 10);
  2234. queueConfigUpdate({ resources: { max_decode_jobs: v } });
  2235. });
  2236. if (resDecisionHold) resDecisionHold.addEventListener('change', () => {
  2237. const v = parseInt(resDecisionHold.value || '0', 10);
  2238. queueConfigUpdate({ resources: { decision_hold_ms: v } });
  2239. });
  2240. avgSelect.addEventListener('change', () => {
  2241. avgAlpha = parseFloat(avgSelect.value) || 0;
  2242. resetProcessingCaches();
  2243. });
  2244. maxHoldToggle.addEventListener('change', () => {
  2245. maxHold = maxHoldToggle.checked;
  2246. maxSpectrum = null;
  2247. markSpectrumDirty();
  2248. });
  2249. if (debugOverlayToggle) debugOverlayToggle.addEventListener('change', () => {
  2250. showDebugOverlay = debugOverlayToggle.checked;
  2251. localStorage.setItem('spectre.debugOverlay', showDebugOverlay ? '1' : '0');
  2252. markSpectrumDirty();
  2253. updateHeroMetrics();
  2254. });
  2255. resetMaxBtn.addEventListener('click', () => {
  2256. maxSpectrum = null;
  2257. markSpectrumDirty();
  2258. });
  2259. followBtn.addEventListener('click', () => { followLive = true; pan = 0; });
  2260. fitBtn.addEventListener('click', fitView);
  2261. timelineFollowBtn.addEventListener('click', () => { timelineFrozen = false; });
  2262. timelineFreezeBtn.addEventListener('click', () => {
  2263. timelineFrozen = !timelineFrozen;
  2264. timelineFreezeBtn.textContent = timelineFrozen ? 'Frozen' : 'Freeze';
  2265. });
  2266. presetButtons.forEach((btn) => {
  2267. btn.addEventListener('click', () => {
  2268. const mhz = parseFloat(btn.dataset.center);
  2269. if (Number.isFinite(mhz)) tuneToFrequency(fromMHz(mhz));
  2270. });
  2271. });
  2272. function activateRailTab(tabName) {
  2273. railTabs.forEach((t) => {
  2274. const active = t.dataset.tab === tabName;
  2275. t.classList.toggle('active', active);
  2276. t.setAttribute('aria-selected', active ? 'true' : 'false');
  2277. });
  2278. tabPanels.forEach((panel) => {
  2279. const active = panel.dataset.panel === tabName;
  2280. panel.classList.toggle('active', active);
  2281. panel.hidden = !active;
  2282. panel.setAttribute('aria-hidden', active ? 'false' : 'true');
  2283. });
  2284. }
  2285. railTabs.forEach((tab) => {
  2286. tab.addEventListener('click', () => activateRailTab(tab.dataset.tab));
  2287. });
  2288. activateRailTab((railTabs.find((t) => t.classList.contains('active')) || railTabs[0])?.dataset.tab || 'radio');
  2289. drawerCloseBtn.addEventListener('click', closeDrawer);
  2290. exportEventBtn.addEventListener('click', exportSelectedEvent);
  2291. if (liveListenEventBtn) {
  2292. liveListenEventBtn.addEventListener('click', () => {
  2293. const ev = eventsById.get(selectedEventId);
  2294. if (!ev) return;
  2295. // Toggle off if already listening
  2296. if (liveListenWS && liveListenWS.playing) {
  2297. stopLiveListen();
  2298. return;
  2299. }
  2300. const freq = ev.center_hz;
  2301. const bw = ev.bandwidth_hz || 12000;
  2302. const mode = ev.class?.mod_type || 'NFM';
  2303. startLiveListen(freq, bw, mode);
  2304. });
  2305. }
  2306. if (decodeEventBtn) {
  2307. decodeEventBtn.addEventListener('click', async () => {
  2308. const ev = eventsById.get(selectedEventId);
  2309. if (!ev) return;
  2310. if (!recordingMetaEl) return;
  2311. const rec = recordings.find(r => r.event_id === ev.id) || recordings.find(r => r.center_hz === ev.center_hz);
  2312. if (!rec) {
  2313. decodeResultEl.textContent = 'Decode: no recording';
  2314. return;
  2315. }
  2316. const mode = decodeModeSelect?.value || ev.class?.mod_type || 'FT8';
  2317. if (!apiClient) {
  2318. decodeResultEl.textContent = 'Decode: failed';
  2319. return;
  2320. }
  2321. const res = await apiClient.decodeRecording(rec.id, mode);
  2322. updateApiState(res);
  2323. if (!res.ok || !res.data) {
  2324. decodeResultEl.textContent = 'Decode: failed';
  2325. return;
  2326. }
  2327. decodeResultEl.textContent = `Decode: ${String(res.data.stdout || '').slice(0, 80)}`;
  2328. });
  2329. }
  2330. jumpToEventBtn.addEventListener('click', () => {
  2331. const ev = eventsById.get(selectedEventId);
  2332. if (!ev) return;
  2333. tuneToFrequency(ev.center_hz);
  2334. });
  2335. timelineCanvas.addEventListener('click', (ev) => {
  2336. const rect = timelineCanvas.getBoundingClientRect();
  2337. const x = (ev.clientX - rect.left) * (timelineCanvas.width / rect.width);
  2338. const y = (ev.clientY - rect.top) * (timelineCanvas.height / rect.height);
  2339. for (let i = timelineRects.length - 1; i >= 0; i--) {
  2340. const r = timelineRects[i];
  2341. if (x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h) {
  2342. openDrawer(eventsById.get(r.id));
  2343. return;
  2344. }
  2345. }
  2346. });
  2347. signalList.addEventListener('click', (ev) => {
  2348. const target = ev.target.closest('.signal-item');
  2349. if (!target) return;
  2350. // Select this signal for live listening — don't retune the SDR
  2351. setSelectedSignal({
  2352. key: target.dataset.key || null,
  2353. id: target.dataset.id || null,
  2354. freq: parseFloat(target.dataset.center),
  2355. bw: parseFloat(target.dataset.bw || '12000'),
  2356. mode: target.dataset.class || ''
  2357. });
  2358. });
  2359. if (liveListenBtn) {
  2360. liveListenBtn.addEventListener('click', async () => {
  2361. // Toggle: if already listening, stop
  2362. if (liveListenWS && liveListenWS.playing) {
  2363. stopLiveListen();
  2364. return;
  2365. }
  2366. // Use selected signal if available, otherwise first in list
  2367. let freq, bw, mode;
  2368. if (window._selectedSignal) {
  2369. freq = window._selectedSignal.freq;
  2370. bw = window._selectedSignal.bw;
  2371. mode = window._selectedSignal.mode;
  2372. } else {
  2373. const first = signalList.querySelector('.signal-item');
  2374. if (!first) return;
  2375. freq = parseFloat(first.dataset.center);
  2376. bw = parseFloat(first.dataset.bw || '12000');
  2377. mode = first.dataset.class || '';
  2378. }
  2379. if (!Number.isFinite(freq)) return;
  2380. startLiveListen(freq, bw, mode);
  2381. });
  2382. }
  2383. eventList.addEventListener('click', (ev) => {
  2384. const target = ev.target.closest('.event-item');
  2385. if (!target) return;
  2386. const id = target.dataset.eventId;
  2387. openDrawer(eventsById.get(id));
  2388. });
  2389. if (recordingList) {
  2390. recordingList.addEventListener('click', async (ev) => {
  2391. const target = ev.target.closest('.recording-item');
  2392. if (!target) return;
  2393. const id = target.dataset.id;
  2394. const audio = new Audio(`/api/recordings/${id}/audio`);
  2395. audio.play();
  2396. if (recordingMetaEl) recordingMetaEl.textContent = `Recording: ${id}`;
  2397. if (recordingMetaLink) {
  2398. recordingMetaLink.href = `/api/recordings/${id}`;
  2399. recordingIQLink.href = `/api/recordings/${id}/iq`;
  2400. recordingAudioLink.href = `/api/recordings/${id}/audio`;
  2401. }
  2402. try {
  2403. if (!apiClient) return;
  2404. const res = await apiClient.getRecording(id);
  2405. updateApiState(res);
  2406. if (!res.ok || !res.data) return;
  2407. const meta = res.data;
  2408. if (decodeResultEl) {
  2409. const rds = meta.rds_ps ? `RDS: ${meta.rds_ps}` : '';
  2410. decodeResultEl.textContent = `Decode: ${rds}`;
  2411. }
  2412. if (classifierScoresEl) {
  2413. const scores = meta.classification?.scores;
  2414. if (scores && typeof scores === 'object') {
  2415. const rows = Object.entries(scores)
  2416. .sort((a, b) => b[1] - a[1])
  2417. .slice(0, 6)
  2418. .map(([k, v]) => `${k}:${v.toFixed(2)}`)
  2419. .join(' · ');
  2420. classifierScoresEl.textContent = rows ? `Classifier scores: ${rows}` : 'Classifier scores: -';
  2421. } else {
  2422. classifierScoresEl.textContent = 'Classifier scores: -';
  2423. }
  2424. }
  2425. } catch {}
  2426. });
  2427. }
  2428. if (debugOverlayToggle) debugOverlayToggle.checked = showDebugOverlay;
  2429. window.addEventListener('keydown', (ev) => {
  2430. if (ev.target && ['INPUT', 'SELECT', 'TEXTAREA'].includes(ev.target.tagName)) return;
  2431. if (ev.key === ' ') {
  2432. ev.preventDefault();
  2433. followLive = true;
  2434. pan = 0;
  2435. } else if (ev.key.toLowerCase() === 'f') {
  2436. fitView();
  2437. } else if (ev.key.toLowerCase() === 'm') {
  2438. maxHold = !maxHold;
  2439. maxHoldToggle.checked = maxHold;
  2440. if (!maxHold) maxSpectrum = null;
  2441. markSpectrumDirty();
  2442. } else if (ev.key.toLowerCase() === 'g') {
  2443. gpuToggle.checked = !gpuToggle.checked;
  2444. queueConfigUpdate({ use_gpu_fft: gpuToggle.checked });
  2445. } else if (ev.key === '[') {
  2446. zoom = Math.max(0.25, zoom * 0.88);
  2447. } else if (ev.key === ']') {
  2448. zoom = Math.min(24, zoom * 1.12);
  2449. } else if (ev.key === 'ArrowLeft') {
  2450. pan = Math.max(-0.5, pan - 0.04);
  2451. followLive = false;
  2452. } else if (ev.key === 'ArrowRight') {
  2453. pan = Math.min(0.5, pan + 0.04);
  2454. followLive = false;
  2455. }
  2456. });
  2457. updateOperatorStatus();
  2458. loadConfig();
  2459. resetLiveListenMeta();
  2460. loadStats();
  2461. loadGPU();
  2462. loadRefinement();
  2463. loadTelemetryLive();
  2464. loadPolicy();
  2465. fetchEvents(true);
  2466. fetchRecordings();
  2467. loadDecoders();
  2468. connect();
  2469. requestAnimationFrame(renderLoop);
  2470. setInterval(loadStats, 1000);
  2471. setInterval(loadGPU, 1000);
  2472. setInterval(loadRefinement, 1500);
  2473. setInterval(loadTelemetryLive, 3000);
  2474. setInterval(loadPolicy, 10000);
  2475. setInterval(() => fetchEvents(false), 2000);
  2476. setInterval(fetchRecordings, 5000);
  2477. setInterval(loadSignals, 1500);
  2478. setInterval(loadDecoders, 10000);