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.

2849 líneas
102KB

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