Wideband autonomous SDR analysis engine forked from sdr-visual-suite
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

2941 satır
105KB

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