Files

631 lines
39 KiB
JavaScript

/* radio-panels core: shared band simulation, spectrum/waterfall renderer,
knob controls, S-meter math, WebAudio receiver, LMR call simulator.
PROTOTYPE. Exposes window.RP. No dependencies. */
(function () {
'use strict';
const RP = (window.RP = {});
RP.clamp = (v, a, b) => Math.max(a, Math.min(b, v));
function mulberry(seed) {
return function () {
seed |= 0; seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
RP.rng = mulberry;
function hash(a, b) {
let h = (a * 374761393 + b * 668265263) | 0;
h = Math.imul(h ^ (h >>> 13), 1274126177);
return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
}
RP.hash = hash;
const now = () => performance.now() / 1000;
RP.now = now;
/** Format Hz as "14.074.000". opts: {mhzDigits, pad, hzDigits:3|2|1|0, sep:'.'} */
RP.fmtFreq = function (hz, opts) {
opts = opts || {};
const sep = opts.sep == null ? '.' : opts.sep;
const hzDigits = opts.hzDigits == null ? 3 : opts.hzDigits;
hz = Math.round(hz);
const mhz = Math.floor(hz / 1e6);
const khz = Math.floor((hz % 1e6) / 1e3);
const h = hz % 1e3;
let s = String(mhz);
if (opts.mhzDigits) s = s.padStart(opts.mhzDigits, opts.pad || ' ');
s += sep + String(khz).padStart(3, '0');
if (hzDigits > 0) s += sep + String(h).padStart(3, '0').slice(0, hzDigits);
return s;
};
// band plan (IARU R2 / North America). noise = band noise floor dBm in 500 Hz
RP.BANDS = [
{ id: '160', name: '1.8', lo: 1800000, hi: 2000000, def: 1840000, mode: 'LSB', noise: -112 },
{ id: '80', name: '3.5', lo: 3500000, hi: 4000000, def: 3573000, mode: 'LSB', noise: -114 },
{ id: '60', name: '5', lo: 5330500, hi: 5406500, def: 5357000, mode: 'USB', noise: -118 },
{ id: '40', name: '7', lo: 7000000, hi: 7300000, def: 7074000, mode: 'LSB', noise: -116 },
{ id: '30', name: '10', lo: 10100000, hi: 10150000, def: 10136000, mode: 'CW', noise: -120 },
{ id: '20', name: '14', lo: 14000000, hi: 14350000, def: 14074000, mode: 'USB', noise: -122 },
{ id: '17', name: '18', lo: 18068000, hi: 18168000, def: 18100000, mode: 'USB', noise: -124 },
{ id: '15', name: '21', lo: 21000000, hi: 21450000, def: 21074000, mode: 'USB', noise: -125 },
{ id: '12', name: '24', lo: 24890000, hi: 24990000, def: 24915000, mode: 'USB', noise: -126 },
{ id: '10', name: '28', lo: 28000000, hi: 29700000, def: 28074000, mode: 'USB', noise: -127 },
{ id: '6', name: '50', lo: 50000000, hi: 54000000, def: 50313000, mode: 'USB', noise: -128 },
{ id: '4', name: '70', lo: 70000000, hi: 70500000, def: 70200000, mode: 'USB', noise: -129 },
{ id: '2', name: '144', lo: 144000000, hi: 148000000, def: 146520000, mode: 'FM', noise: -130 },
{ id: '70', name: '430', lo: 420000000, hi: 450000000, def: 446000000, mode: 'FM', noise: -131 },
{ id: 'AIR', name: 'AIR', lo: 108000000, hi: 137000000, def: 121500000, mode: 'AM', noise: -128 },
{ id: 'WX', name: 'WX', lo: 162400000, hi: 162550000, def: 162550000, mode: 'FM', noise: -130 },
{ id: 'MAR', name: 'MARINE', lo: 156000000, hi: 162025000, def: 156800000, mode: 'FM', noise: -130 },
{ id: '125', name: '220', lo: 222000000, hi: 225000000, def: 223500000, mode: 'FM', noise: -130 },
{ id: 'LMRV', name: 'VHF LMR', lo: 148000000, hi: 174000000, def: 154400000, mode: 'FM', noise: -129 },
{ id: 'GMRS', name: 'GMRS', lo: 462000000, hi: 468000000, def: 462562500, mode: 'FM', noise: -131 },
{ id: 'LMRU', name: 'UHF LMR', lo: 450000000, hi: 512000000, def: 451000000, mode: 'FM', noise: -131 },
{ id: '700', name: '700/800', lo: 764000000, hi: 870000000, def: 851012500, mode: 'FM', noise: -132 },
{ id: 'BCFM', name: 'FM BC', lo: 87500000, hi: 108000000, def: 99300000, mode: 'WFM', noise: -120 },
{ id: 'VU', name: 'VU', lo: 60000000, hi: 1300000000, def: 146520000, mode: 'FM', noise: -130 },
{ id: 'GEN', name: 'GEN', lo: 30000, hi: 60000000, def: 9650000, mode: 'AM', noise: -110 },
];
RP.bandOf = function (hz) {
for (const b of RP.BANDS) if (b.id !== 'GEN' && b.id !== 'VU' && hz >= b.lo && hz <= b.hi) return b;
return hz > 60000000 ? RP.bandById('VU') : RP.bandById('GEN');
};
RP.bandById = (id) => RP.BANDS.find((b) => b.id === id);
const OPEN = { '160': 0.3, '80': 0.6, '60': 0.7, '40': 1, '30': 0.9, '20': 1, '17': 0.9, '15': 0.8, '12': 0.6, '10': 0.55, '6': 0.25, '4': 0.1, '2': 0.5, '70': 0.5, GEN: 1 };
const CALLS = ['VE6PZA', 'K1ABC', 'W7DXX', 'JA1XYZ', 'DL2ZZ', 'VK3FEN', 'G4BAT', 'EA8DRG', 'ZL2CW', 'PY2QQ', 'KH6SUN', 'VE3NPC', 'N0ORA', 'OH2BH', 'KL7RA', 'W5KUB', 'LU1HF', 'ZS6AA', 'VA7FOX', 'K6ORG'];
RP.CALLS = CALLS;
// signal generator. type: cw ssb ft8 ft4 rtty am beacon carrier psk fm
const sigCache = new Map();
function genSignals(band) {
if (sigCache.has(band.id)) return sigCache.get(band.id);
const r = mulberry(band.lo / 1000);
const open = OPEN[band.id] || 0.5;
const out = [];
const span = band.hi - band.lo;
const add = (o) => out.push(Object.assign({ seed: Math.floor(r() * 1e9) }, o));
const dbm = (lo, hi) => (lo + r() * (hi - lo)) - (1 - open) * 25;
if (band.id === 'GEN') {
const sw = [[5900, 6200], [7300, 7600], [9400, 9900], [11600, 12100], [13570, 13870], [15100, 15800], [17480, 17900], [21450, 21850]];
for (const [a, b] of sw) for (let f = a; f < b; f += 5) if (r() < 0.33) add({ f: f * 1000, type: 'am', dbm: -95 + r() * 55, call: 'BCST' });
for (let i = 0; i < 40; i++) add({ f: 540000 + Math.floor(r() * 118) * 10000, type: 'am', dbm: -80 + r() * 45, call: 'AM' });
add({ f: 10000000, type: 'carrier', dbm: -70, call: 'WWV' }); add({ f: 5000000, type: 'carrier', dbm: -78, call: 'WWV' });
sigCache.set(band.id, out); return out;
}
if (band.id === 'AIR') {
for (const f of [118300000, 119100000, 120200000, 121500000, 122800000, 124700000, 126350000, 128950000, 132450000, 135100000]) add({ f, type: 'am', dbm: dbm(-115, -70), call: 'ATC' });
sigCache.set(band.id, out); return out;
}
if (band.id === 'WX') { for (const f of [162400000, 162475000, 162550000]) add({ f, type: 'fmc', dbm: dbm(-110, -75), call: 'NOAA' }); sigCache.set(band.id, out); return out; }
if (band.id === 'BCFM') { for (let f = 88100000; f < 108000000; f += 200000) if (r() < 0.35) add({ f, type: 'fmc', wide: true, dbm: dbm(-90, -45), call: 'FM' }); sigCache.set(band.id, out); return out; }
if (band.id === 'VU') { sigCache.set(band.id, out); return out; }
if (band.id === '2' || band.id === '70' || band.id === 'MAR' || band.id === '125' || band.id === 'LMRV' || band.id === 'GMRS' || band.id === 'LMRU' || band.id === '700') {
const step = band.id === '2' ? 15000 : band.id === '70' ? 25000 : 12500;
for (let f = band.lo + 1000000; f < band.hi; f += step) if (r() < 0.12) add({ f, type: 'fm', dbm: dbm(-120, -60), call: CALLS[Math.floor(r() * CALLS.length)] });
add({ f: band.def, type: 'fm', dbm: -85, call: 'SIMPLEX' });
sigCache.set(band.id, out); return out;
}
const digi = { '160': 1840000, '80': 3573000, '60': 5357000, '40': 7074000, '30': 10136000, '20': 14074000, '17': 18100000, '15': 21074000, '12': 24915000, '10': 28074000, '6': 50313000, '4': 70154000 }[band.id];
const cwTop = band.lo + Math.min(70000, span * 0.3);
const nCw = Math.floor((8 + r() * 14) * open) + 2;
for (let i = 0; i < nCw; i++) add({ f: band.lo + 2000 + Math.floor(r() * (cwTop - band.lo - 4000) / 50) * 50, type: 'cw', dbm: dbm(-120, -60), wpm: 14 + Math.floor(r() * 18), call: CALLS[Math.floor(r() * CALLS.length)] });
if (digi) {
const n = Math.floor(10 + r() * 22 * open);
for (let i = 0; i < n; i++) add({ f: digi + 200 + Math.floor(r() * 2700), type: 'ft8', dbm: dbm(-125, -78), slot: r() < 0.5 ? 0 : 1, call: CALLS[Math.floor(r() * CALLS.length)] });
const n4 = Math.floor(r() * 7 * open);
for (let i = 0; i < n4; i++) add({ f: digi + 6000 + 200 + Math.floor(r() * 2500), type: 'ft4', dbm: dbm(-122, -85) });
if (r() < 0.8) add({ f: digi + 12000 + Math.floor(r() * 8) * 1000, type: 'rtty', dbm: dbm(-110, -75) });
if (r() < 0.6) add({ f: digi - 3000 + Math.floor(r() * 1500), type: 'psk', dbm: dbm(-115, -85) });
}
if (band.id === '20') add({ f: 14100000, type: 'beacon', dbm: -90, call: 'NCDXF' });
if (band.id === '10') for (let i = 0; i < 4; i++) add({ f: 28200000 + Math.floor(r() * 100) * 1000, type: 'beacon', dbm: dbm(-115, -85) });
if (band.id !== '30') {
const phLo = band.id === '60' ? band.lo : Math.max(cwTop + 30000, band.lo + span * 0.45);
const nPh = Math.floor((6 + r() * 14) * open) + 1;
for (let i = 0; i < nPh; i++) add({ f: phLo + Math.floor(r() * (band.hi - phLo - 3000) / 1000) * 1000 + (r() < 0.2 ? 500 : 0), type: 'ssb', sb: band.lo < 10000000 ? 'L' : 'U', dbm: dbm(-118, -55), call: CALLS[Math.floor(r() * CALLS.length)] });
}
for (let i = 0; i < 2; i++) add({ f: band.lo + Math.floor(r() * span), type: 'carrier', dbm: -112 + r() * 10 });
sigCache.set(band.id, out);
return out;
}
RP.signalsFor = genSignals;
function activity(s, t) {
const fade = 0.75 + 0.25 * Math.sin(t * (0.3 + hash(s.seed, 1) * 0.5) + s.seed);
switch (s.type) {
case 'cw': {
const unit = 1.2 / s.wpm;
const over = Math.floor((t + hash(s.seed, 2) * 60) / 40);
if (hash(s.seed, over) < 0.25) return 0;
const idx = Math.floor(t / unit);
const h = hash(s.seed, Math.floor(idx / 2));
return (h < 0.55 ? 1 : 0) * fade;
}
case 'ssb': case 'fm': {
const period = 30 + hash(s.seed, 3) * 50;
const ph = ((t + hash(s.seed, 4) * period) % period) / period;
if (ph > 0.7) return 0;
if (s.type === 'fm') return 1;
const syl = 0.45 + 0.55 * Math.abs(Math.sin(t * 5.3 + s.seed) * Math.sin(t * 2.1 + s.seed * 0.3));
const pause = hash(s.seed, Math.floor(t * 1.7)) < 0.15 ? 0.05 : 1;
return syl * pause * fade;
}
case 'ft8': {
const cyc = Math.floor(Date.now() / 15000);
const into = (Date.now() % 15000) / 1000;
if ((cyc & 1) !== s.slot) return 0;
if (into < 0.5 || into > 13.1) return 0;
if (hash(s.seed, cyc) < 0.2) return 0;
return fade;
}
case 'ft4': { const into = (Date.now() % 7500) / 1000; return into > 0.5 && into < 5.5 && hash(s.seed, Math.floor(Date.now() / 7500)) > 0.4 ? fade : 0; }
case 'beacon': { const into = (Date.now() % 10000) / 1000; return into < 9 ? 1 : 0; }
default: return fade;
}
}
function components(s, t) {
const a = activity(s, t);
if (a <= 0.001) return null;
const p = s.dbm + 20 * Math.log10(a);
switch (s.type) {
case 'cw': case 'carrier': case 'beacon': return [[s.f, 30, p]];
case 'ft8': { const tone = Math.floor(hash(s.seed, Math.floor(Date.now() / 160)) * 8); return [[s.f + tone * 6.25, 8, p]]; }
case 'ft4': { const tone = Math.floor(hash(s.seed, Math.floor(Date.now() / 48)) * 4); return [[s.f + tone * 20.8, 22, p]]; }
case 'rtty': { const m = hash(s.seed, Math.floor(Date.now() / 22)) < 0.5; return [[s.f + (m ? 0 : 170), 40, p]]; }
case 'psk': return [[s.f, 40, p]];
case 'fm': return [[s.f, 9000, p]];
case 'fmc': return [[s.f, s.wide ? 150000 : 9000, p]];
case 'am': return [[s.f, 30, p], [s.f - 2500, 3500, p - 18 + 6 * Math.sin(t * 3 + s.seed)], [s.f + 2500, 3500, p - 18 + 6 * Math.sin(t * 3.4 + s.seed)]];
case 'ssb': { const dir = s.sb === 'L' ? -1 : 1; return [[s.f + dir * 700, 900, p], [s.f + dir * 1800, 1300, p - 8 - 6 * Math.abs(Math.sin(t * 7 + s.seed))]]; }
}
return [[s.f, 50, p]];
}
/** Passband offsets [loHz, hiHz] relative to dial freq. */
RP.PASS = function (mode, width, shift, pitch) {
shift = shift || 0; width = width || 2400;
switch (mode) {
case 'USB': case 'DATA-U': case 'USB-D': case 'PSK': case 'DATA': return [300 + shift, 300 + width + shift];
case 'LSB': case 'DATA-L': case 'LSB-D': return [-300 - width + shift, -300 + shift];
case 'RTTY': case 'FSK': case 'RTTY-L': case 'RTTY-R': return [-width / 2 + shift - 85, width / 2 + shift - 85];
case 'AM': case 'FM': case 'AM-N': case 'FM-N': case 'DATA-FM': case 'C4FM': case 'DV': return [-width / 2, width / 2];
}
return [-width / 2 + shift, width / 2 + shift]; // CW family
};
/**
* Fill out (Float32Array dB) with the spectrum across [center-span/2, center+span/2].
* rx: {freq, mode, width, preamp 0..2, att dB, rfGain 0..1}
*/
RP.spectrum = function (rx, center, span, out) {
const n = out.length, t = now();
const band = RP.bandOf(center);
const lo = center - span / 2, binHz = span / n;
const preampGain = [0, 10, 20][rx.preamp || 0] || 0;
const att = rx.att || 0;
const rf = rx.rfGain == null ? 1 : rx.rfGain;
const gainAdj = preampGain - att + (rf - 1) * 40;
const nf = band.noise + preampGain * 0.35 - att * 0.2 + (rf - 1) * 30;
const lin = new Float64Array(n);
let sigs = genSignals(band);
if (band.id !== 'GEN' && span > 300000) sigs = sigs.concat(genSignals(RP.bandById('GEN')));
for (const s of sigs) {
if (s.f < lo - 6000 || s.f > lo + span + 6000) continue;
const comps = components(s, t);
if (!comps) continue;
for (const [cf, bw, p] of comps) {
const pw = Math.pow(10, (p + gainAdj) / 10);
const sd = Math.max(bw / 2, binHz * 0.6);
const i0 = Math.max(0, Math.floor((cf - 3 * sd - lo) / binHz)), i1 = Math.min(n - 1, Math.ceil((cf + 3 * sd - lo) / binHz));
for (let i = i0; i <= i1; i++) {
const d = (lo + (i + 0.5) * binHz - cf) / sd;
lin[i] += pw * Math.exp(-d * d * 0.5) * Math.min(1, binHz / bw + 0.3);
}
}
}
for (let i = 0; i < n; i++) {
const noise = nf + gainAdj * 0.5 + (Math.random() + Math.random() + Math.random() - 1.5) * 4.5 - 2;
out[i] = 10 * Math.log10(Math.pow(10, noise / 10) + lin[i]);
}
return out;
};
/** Level in passband: {dbm, noise, comps:[{s, f, dbm}]} */
RP.rxLevel = function (rx) {
const [a, b] = RP.PASS(rx.mode, rx.width, rx.shift, rx.pitch);
const lo = rx.freq + a, hi = rx.freq + b;
const t = now();
const band = RP.bandOf(rx.freq);
const preampGain = [0, 10, 20][rx.preamp || 0] || 0;
let p = 0;
const comps = [];
for (const s of genSignals(band)) {
if (s.f < lo - 10000 || s.f > hi + 10000) continue;
const c = components(s, t);
if (!c) continue;
for (const [cf, bw, pp] of c) {
if (cf + bw / 2 < lo || cf - bw / 2 > hi) continue;
p += Math.pow(10, pp / 10);
comps.push({ s, f: cf, dbm: pp });
}
}
const noise = band.noise + 10 * Math.log10(Math.max(100, hi - lo) / 500) + 3;
const total = 10 * Math.log10(p + Math.pow(10, noise / 10));
return { dbm: total - (rx.att || 0) + preampGain * 0.15, noise, comps };
};
/** dBm to S-units. frac: 0..1 along an S0..S9+60 scale where S9 sits at 0.5. */
RP.sUnits = function (dbm) {
const s9 = -73;
if (dbm <= s9) {
const s = RP.clamp(9 + (dbm - s9) / 6, 0, 9);
return { s, over: 0, frac: (s / 9) * 0.5, text: 'S' + Math.round(s) };
}
const over = RP.clamp(dbm - s9, 0, 60);
return { s: 9, over, frac: 0.5 + over / 120, text: 'S9+' + Math.round(over / 10) * 10 };
};
// waterfall palettes
function lerpPal(stops) {
const pal = new Uint8ClampedArray(256 * 3);
for (let i = 0; i < 256; i++) {
const x = i / 255;
let k = 0; while (k < stops.length - 2 && x > stops[k + 1][0]) k++;
const [x0, c0] = stops[k], [x1, c1] = stops[k + 1];
const u = RP.clamp((x - x0) / (x1 - x0 || 1), 0, 1);
for (let j = 0; j < 3; j++) pal[i * 3 + j] = c0[j] + (c1[j] - c0[j]) * u;
}
return pal;
}
const hx = (h) => [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16)];
RP.palette = (stops) => lerpPal(stops.map(([x, c]) => [x, hx(c)]));
RP.PALETTES = {
icom: RP.palette([[0, '#000010'], [0.25, '#00186e'], [0.45, '#0064d2'], [0.6, '#00d2ff'], [0.75, '#ffff00'], [0.9, '#ff6400'], [1, '#ff0000']]),
yaesu: RP.palette([[0, '#000000'], [0.3, '#001a5c'], [0.5, '#0050ff'], [0.65, '#00e0ff'], [0.8, '#ffffff'], [1, '#ffffff']]),
kenwood: RP.palette([[0, '#000000'], [0.3, '#00102e'], [0.5, '#0040a0'], [0.65, '#18c0ff'], [0.8, '#ffe040'], [1, '#ff3030']]),
xiegu: RP.palette([[0, '#00001e'], [0.35, '#0000aa'], [0.55, '#00aaff'], [0.7, '#00ff80'], [0.85, '#ffff00'], [1, '#ff0000']]),
mono: RP.palette([[0, '#000000'], [1, '#ffffff']]),
amber: RP.palette([[0, '#100600'], [0.5, '#a04000'], [0.8, '#ffb000'], [1, '#fff0c0']]),
};
/**
* Spectrum + waterfall renderer bound to a <canvas> (sized by CSS).
* new RP.Scope(canvas, {getRx:()=>rx, palette, style, span, mode:'ctr'|'fix'|'scroll', onTune(hz, kind, dir), after(ctx, geom)})
* Mutable fields: span, mode, ref (dB), speed (rows/s), wfGain (dB), wfOn, scopeOn, markers[{f,color}], style.*
* style: {bg, grid, trace, fill, fill2, passband, marker, txMarker, text, font, scopeFrac, avg, labels, peak, rangeDb, cursor}
*/
RP.Scope = class {
constructor(canvas, opt) {
this.c = canvas; this.ctx = canvas.getContext('2d');
this.opt = opt;
this.style = Object.assign({ bg: '#000', grid: 'rgba(255,255,255,0.13)', trace: '#fff', fill: 'rgba(80,160,255,0.35)', passband: 'rgba(255,255,255,0.18)', marker: '#ff3030', text: 'rgba(255,255,255,0.7)', font: '10px sans-serif', scopeFrac: 0.45, avg: 0.55, labels: true, peak: false }, opt.style || {});
this.palette = opt.palette || RP.PALETTES.icom;
this.span = opt.span || 50000; this.mode = opt.mode || 'ctr';
this.fixedLo = null; this.ref = 0; this.speed = opt.speed || 25; this.wfGain = 0; this.wfOn = true; this.scopeOn = true; this.hold = false;
this.wfCanvas = document.createElement('canvas'); this.wfCtx = this.wfCanvas.getContext('2d');
this.bins = null; this.smooth = null; this.peakArr = null; this._acc = 0; this._last = now();
this.hover = null; this.markers = [];
this.onTune = opt.onTune || (() => {});
this._bind();
this._loop = this._loop.bind(this);
requestAnimationFrame(this._loop);
}
_resize() {
const r = this.c.getBoundingClientRect(), d = window.devicePixelRatio || 1;
const w = Math.max(50, Math.round(this.c.clientWidth * d)), h = Math.max(30, Math.round(this.c.clientHeight * d));
if (this.c.width !== w || this.c.height !== h || !this.bins) {
this.c.width = w; this.c.height = h;
const nc = document.createElement('canvas'); nc.width = w; nc.height = Math.max(1, h);
nc.getContext('2d').fillRect(0, 0, w, h);
this.wfCanvas = nc; this.wfCtx = nc.getContext('2d'); this._prefill = true;
const n = Math.min(1024, Math.max(64, Math.round(w / d)));
this.bins = new Float32Array(n); this.smooth = null; this.peakArr = null;
this.dpr = d;
}
}
range() {
const rx = this.opt.getRx();
if (this.mode === 'fix') {
const b = RP.bandOf(rx.freq);
if (this.fixedLo == null || rx.freq < this.fixedLo || rx.freq > this.fixedLo + this.span) this.fixedLo = Math.max(b.lo, Math.min(rx.freq - this.span * 0.25, b.hi - this.span));
return [this.fixedLo, this.fixedLo + this.span];
}
if (this.mode === 'scroll') {
if (this.fixedLo == null) this.fixedLo = rx.freq - this.span / 2;
if (rx.freq < this.fixedLo + this.span * 0.05) this.fixedLo = rx.freq - this.span * 0.05;
if (rx.freq > this.fixedLo + this.span * 0.95) this.fixedLo = rx.freq - this.span * 0.95;
return [this.fixedLo, this.fixedLo + this.span];
}
return [rx.freq - this.span / 2, rx.freq + this.span / 2];
}
setMode(m) { this.mode = m; this.fixedLo = null; }
xToHz(x) { const [a, b] = this.range(); return a + (x / this.c.clientWidth) * (b - a); }
_bind() {
let drag = false;
const pos = (e) => { const r = this.c.getBoundingClientRect(); const sx = this.c.clientWidth / r.width; return [(e.clientX - r.left) * sx, (e.clientY - r.top) * sx]; };
this.c.addEventListener('pointerdown', (e) => { drag = true; this.c.setPointerCapture(e.pointerId); const [x] = pos(e); this.onTune(this.xToHz(x), 'click'); });
this.c.addEventListener('pointermove', (e) => { const p = pos(e); this.hover = p; if (drag) this.onTune(this.xToHz(p[0]), 'drag'); });
this.c.addEventListener('pointerup', () => (drag = false));
this.c.addEventListener('pointerleave', () => (this.hover = null));
this.c.addEventListener('wheel', (e) => { e.preventDefault(); this.onTune(null, 'wheel', e.deltaY < 0 ? 1 : -1); }, { passive: false });
}
clearWaterfall() { this.wfCtx.fillStyle = '#000'; this.wfCtx.fillRect(0, 0, this.wfCanvas.width, this.wfCanvas.height); }
_loop() {
requestAnimationFrame(this._loop);
if (!this.c.isConnected || this.c.clientWidth === 0) return;
this._resize();
const t = now(), dt = Math.min(0.2, t - this._last); this._last = t;
const rx = this.opt.getRx();
const [lo, hi] = this.range();
const n = this.bins.length;
if (!this.hold) RP.spectrum(rx, (lo + hi) / 2, hi - lo, this.bins);
if (!this.smooth) { this.smooth = Float32Array.from(this.bins); this.peakArr = Float32Array.from(this.bins); }
const k = this.style.avg;
for (let i = 0; i < n; i++) { this.smooth[i] = this.smooth[i] * k + this.bins[i] * (1 - k); this.peakArr[i] = Math.max(this.peakArr[i] - dt * 12, this.smooth[i]); }
const W = this.c.width, H = this.c.height, ctx = this.ctx, d = this.dpr;
const sH = this.scopeOn ? (this.wfOn ? Math.round(H * this.style.scopeFrac) : H) : 0;
const wH = H - sH;
const band = RP.bandOf(rx.freq);
const floor = band.noise - 10 - this.ref, rangeDb = this.style.rangeDb || 75;
const yOf = (db) => sH - RP.clamp((db - floor) / rangeDb, 0, 1) * (sH - 4 * d);
ctx.fillStyle = this.style.bg; ctx.fillRect(0, 0, W, sH || 1);
const hzToX = (f) => ((f - lo) / (hi - lo)) * W;
if (sH > 0) {
ctx.strokeStyle = this.style.grid; ctx.lineWidth = 1;
ctx.beginPath();
for (let i = 1; i < 10; i++) { const x = Math.round((W * i) / 10) + 0.5; ctx.moveTo(x, 0); ctx.lineTo(x, sH); }
for (let i = 1; i < 8; i++) { const y = Math.round((sH * i) / 8) + 0.5; ctx.moveTo(0, y); ctx.lineTo(W, y); }
ctx.stroke();
const [pa, pb] = RP.PASS(rx.mode, rx.width, rx.shift, rx.pitch);
ctx.fillStyle = this.style.passband;
ctx.fillRect(hzToX(rx.freq + pa), 0, Math.max(2, hzToX(rx.freq + pb) - hzToX(rx.freq + pa)), sH);
if (rx.split && rx.txFreq) { ctx.fillStyle = 'rgba(255,60,60,0.18)'; ctx.fillRect(hzToX(rx.txFreq + pa), 0, Math.max(2, hzToX(rx.txFreq + pb) - hzToX(rx.txFreq + pa)), sH); }
ctx.beginPath(); ctx.moveTo(0, sH);
for (let i = 0; i < n; i++) ctx.lineTo((i / (n - 1)) * W, yOf(this.smooth[i]));
ctx.lineTo(W, sH); ctx.closePath();
if (this.style.fill) { const g = ctx.createLinearGradient(0, 0, 0, sH); g.addColorStop(0, this.style.fill); g.addColorStop(1, this.style.fill2 || this.style.fill); ctx.fillStyle = g; ctx.fill(); }
ctx.beginPath();
for (let i = 0; i < n; i++) { const x = (i / (n - 1)) * W, y = yOf(this.smooth[i]); i ? ctx.lineTo(x, y) : ctx.moveTo(x, y); }
ctx.strokeStyle = this.style.trace; ctx.lineWidth = Math.max(1, d); ctx.stroke();
if (this.style.peak) { ctx.beginPath(); for (let i = 0; i < n; i++) { const x = (i / (n - 1)) * W, y = yOf(this.peakArr[i]); i ? ctx.lineTo(x, y) : ctx.moveTo(x, y); } ctx.strokeStyle = this.style.peak; ctx.lineWidth = 1; ctx.stroke(); }
}
if (this.wfOn && wH > 2) {
this._acc += dt * this.speed;
const rows = Math.floor(this._acc);
const wc = this.wfCanvas, wx = this.wfCtx;
if (this._prefill) {
// backfill history so the waterfall is not empty on load / resize
this._prefill = false;
const tmp = new Float32Array(n), img = wx.createImageData(W, 1), pal = this.palette;
const wfFloor = band.noise - 4 - this.ref - this.wfGain;
for (let y = 0; y < wH; y += 3) {
RP.spectrum(rx, (lo + hi) / 2, hi - lo, tmp);
for (let x = 0; x < W; x++) {
const v = tmp[Math.min(n - 1, Math.floor((x / W) * n))] - 3;
const ci = Math.round(RP.clamp((v - wfFloor) / 55, 0, 1) * 255) * 3;
img.data[x * 4] = pal[ci]; img.data[x * 4 + 1] = pal[ci + 1]; img.data[x * 4 + 2] = pal[ci + 2]; img.data[x * 4 + 3] = 255;
}
for (let k = 0; k < 3 && y + k < wH; k++) wx.putImageData(img, 0, y + k);
}
}
if (rows > 0 && !this.hold) {
this._acc -= rows;
wx.drawImage(wc, 0, 0, W, wH - rows, 0, rows, W, wH - rows);
const img = wx.createImageData(W, 1), pal = this.palette;
const wfFloor = band.noise - 4 - this.ref - this.wfGain, wfRange = 55;
for (let x = 0; x < W; x++) {
const v = this.smooth[Math.min(n - 1, Math.floor((x / W) * n))];
const ci = Math.round(RP.clamp((v - wfFloor) / wfRange, 0, 1) * 255) * 3;
img.data[x * 4] = pal[ci]; img.data[x * 4 + 1] = pal[ci + 1]; img.data[x * 4 + 2] = pal[ci + 2]; img.data[x * 4 + 3] = 255;
}
for (let r = 0; r < rows; r++) wx.putImageData(img, 0, r);
}
ctx.drawImage(wc, 0, 0, W, wH, 0, sH, W, wH);
}
const mx = Math.round(hzToX(rx.freq)) + 0.5;
ctx.strokeStyle = this.style.marker; ctx.lineWidth = Math.max(1, d);
ctx.beginPath(); ctx.moveTo(mx, 0); ctx.lineTo(mx, H); ctx.stroke();
if (rx.split && rx.txFreq) { const tx = Math.round(hzToX(rx.txFreq)) + 0.5; ctx.strokeStyle = this.style.txMarker || '#ff9c00'; ctx.setLineDash([4 * d, 3 * d]); ctx.beginPath(); ctx.moveTo(tx, 0); ctx.lineTo(tx, H); ctx.stroke(); ctx.setLineDash([]); }
for (const m of this.markers) { const x = hzToX(m.f); ctx.fillStyle = m.color || '#ff0'; ctx.fillRect(x - d, 0, 2 * d, 6 * d); }
if (this.style.labels && sH > 30) {
ctx.font = this.style.font.replace(/(\d+)px/, (_, p) => p * d + 'px'); ctx.fillStyle = this.style.text; ctx.textBaseline = 'bottom';
for (let i = 1; i < 10; i += 2) { const f = lo + ((hi - lo) * i) / 10; ctx.fillText((f / 1e6).toFixed(hi - lo < 20000 ? 4 : 3), (W * i) / 10 + 3 * d, sH - 2 * d); }
}
if (this.hover && this.style.cursor !== false) {
const x = this.hover[0] * d; ctx.strokeStyle = 'rgba(255,255,255,0.35)'; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(x + 0.5, 0); ctx.lineTo(x + 0.5, H); ctx.stroke();
}
if (this.opt.after) this.opt.after(ctx, { W, H, sH, lo, hi, d, hzToX, rx });
}
};
/**
* Rotary encoder. RP.knob(el, {onStep(steps), detent: deg per step, mode:'circular'|'vertical', sens})
* Drag (circular around centre, or vertical), mouse wheel, arrow keys. Sets CSS var --rot on el.
*/
RP.knob = function (el, opt) {
opt = Object.assign({ detent: 12, sens: 1 }, opt);
let angle = 0, acc = 0, dragging = false, lastA = null, lastY = 0;
const mode = opt.mode || 'circular';
if (!el.hasAttribute('tabindex')) el.tabIndex = 0;
el.style.touchAction = 'none';
const apply = (deg) => {
angle += deg; acc += deg;
el.style.setProperty('--rot', angle + 'deg');
const steps = acc > 0 ? Math.floor(acc / opt.detent) : Math.ceil(acc / opt.detent);
if (steps) { acc -= steps * opt.detent; opt.onStep && opt.onStep(steps); }
};
const center = () => { const r = el.getBoundingClientRect(); return [r.left + r.width / 2, r.top + r.height / 2]; };
el.addEventListener('pointerdown', (e) => {
if (e.button !== 0) return; e.preventDefault(); e.stopPropagation(); dragging = true; el.setPointerCapture(e.pointerId); el.classList.add('turning');
const [cx, cy] = center(); lastA = Math.atan2(e.clientY - cy, e.clientX - cx); lastY = e.clientY;
});
el.addEventListener('pointermove', (e) => {
if (!dragging) return;
if (mode === 'vertical') { const dy = lastY - e.clientY; lastY = e.clientY; apply(dy * 2 * opt.sens); return; }
const [cx, cy] = center(); const a = Math.atan2(e.clientY - cy, e.clientX - cx);
let d = a - lastA; if (d > Math.PI) d -= 2 * Math.PI; if (d < -Math.PI) d += 2 * Math.PI; lastA = a;
apply(((d * 180) / Math.PI) * opt.sens);
});
const up = () => { dragging = false; el.classList.remove('turning'); };
el.addEventListener('pointerup', up); el.addEventListener('pointercancel', up);
el.addEventListener('wheel', (e) => { e.preventDefault(); apply((e.deltaY < 0 ? 1 : -1) * opt.detent * (e.shiftKey ? 5 : 1)); }, { passive: false });
el.addEventListener('keydown', (e) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowRight') { apply(opt.detent); e.preventDefault(); }
if (e.key === 'ArrowDown' || e.key === 'ArrowLeft') { apply(-opt.detent); e.preventDefault(); }
});
return { get angle() { return angle; }, set(deg) { angle = deg; el.style.setProperty('--rot', deg + 'deg'); } };
};
/** Absolute pot 0..1 mapped to min..max deg (default -135..135). RP.pot(el, {value, onChange(v)}) */
RP.pot = function (el, opt) {
opt = Object.assign({ value: 0.5, min: -135, max: 135 }, opt);
let v = opt.value;
const set = (nv, silent) => { v = RP.clamp(nv, 0, 1); el.style.setProperty('--rot', opt.min + (opt.max - opt.min) * v + 'deg'); el.setAttribute('aria-valuenow', Math.round(v * 100)); if (!silent && opt.onChange) opt.onChange(v); };
el.setAttribute('role', 'slider');
RP.knob(el, { detent: 2.7, mode: opt.drag || 'circular', onStep: (n) => set(v + n / 100) });
const ctl = { get value() { return v; }, set };
set(v, true);
return ctl;
};
/** Press with long-hold: RP.press(el, onClick, onHold, ms=650). Adds .down while pressed. */
RP.press = function (el, onClick, onHold, ms) {
let tm = null, held = false, isDown = false;
el.addEventListener('pointerdown', (e) => { if (e.button !== 0) return; isDown = true; held = false; el.classList.add('down'); tm = setTimeout(() => { held = true; onHold && onHold(e); }, ms || 650); });
const end = (e, fire) => { if (!isDown) return; isDown = false; el.classList.remove('down'); clearTimeout(tm); if (fire && !held) onClick && onClick(e); };
el.addEventListener('pointerup', (e) => end(e, true));
el.addEventListener('pointerleave', (e) => end(e, false));
el.addEventListener('contextmenu', (e) => e.preventDefault());
};
/** WebAudio receiver. Context starts on first pointerdown; stays silent until update() sets af. */
RP.Audio = class {
constructor() { this.ctx = null; this.on = false; this.oscs = []; }
start() {
if (this.ctx) { this.ctx.resume(); return; }
const C = window.AudioContext || window.webkitAudioContext; if (!C) return;
const ctx = (this.ctx = new C());
const len = ctx.sampleRate * 2, buf = ctx.createBuffer(1, len, ctx.sampleRate), d = buf.getChannelData(0);
let b0 = 0, b1 = 0, b2 = 0;
for (let i = 0; i < len; i++) { const w = Math.random() * 2 - 1; b0 = 0.997 * b0 + w * 0.029; b1 = 0.985 * b1 + w * 0.032; b2 = 0.95 * b2 + w * 0.048; d[i] = (b0 + b1 + b2 + w * 0.05) * 0.6; }
this.master = ctx.createGain(); this.master.gain.value = 0; this.master.connect(ctx.destination);
const mk = () => { const s = ctx.createBufferSource(); s.buffer = buf; s.loop = true; s.start(0, Math.random() * 2); return s; };
this.noise = mk(); this.hp = ctx.createBiquadFilter(); this.hp.type = 'highpass'; this.lp = ctx.createBiquadFilter(); this.lp.type = 'lowpass';
this.noiseGain = ctx.createGain(); this.noiseGain.gain.value = 0; this.noise.connect(this.hp).connect(this.lp).connect(this.noiseGain).connect(this.master);
this.voice = mk(); this.vf1 = ctx.createBiquadFilter(); this.vf1.type = 'bandpass'; this.vf1.Q.value = 3; this.vf2 = ctx.createBiquadFilter(); this.vf2.type = 'bandpass'; this.vf2.Q.value = 5;
this.voiceGain = ctx.createGain(); this.voiceGain.gain.value = 0;
const vsum = ctx.createGain(); this.voice.connect(this.vf1).connect(vsum); this.voice.connect(this.vf2).connect(vsum);
this.buzz = ctx.createOscillator(); this.buzz.type = 'sawtooth'; this.buzz.frequency.value = 140; const bz = ctx.createGain(); bz.gain.value = 0.25; this.buzz.connect(bz).connect(this.vf1); this.buzz.start();
vsum.connect(this.voiceGain).connect(this.lp);
for (let i = 0; i < 6; i++) { const o = ctx.createOscillator(); o.type = 'sine'; const g = ctx.createGain(); g.gain.value = 0; o.connect(g).connect(this.master); o.start(); this.oscs.push({ o, g }); }
this.on = true;
}
/** short square beep: beep(hz, ms, vol=0.05, whenSec=0). Works for key beeps and LMR tones. */
beep(freq, ms, vol, when) {
if (!this.ctx) return;
const ctx = this.ctx, o = ctx.createOscillator(), g = ctx.createGain(), t0 = ctx.currentTime + (when || 0);
o.frequency.value = freq; o.type = 'square'; g.gain.setValueAtTime(0, t0); g.gain.linearRampToValueAtTime(vol || 0.05, t0 + 0.005); g.gain.setValueAtTime(vol || 0.05, t0 + ms / 1000 - 0.01); g.gain.linearRampToValueAtTime(0, t0 + ms / 1000);
o.connect(g).connect(ctx.destination); o.start(t0); o.stop(t0 + ms / 1000 + 0.02);
}
/** seq([[hz, ms, vol], ...]) - hz 0 = rest */
seq(list) { let t = 0; for (const [f, ms, v] of list) { if (f) this.beep(f, ms, v, t); t += ms / 1000; } }
/** Call ~20x/s for HF panels. rx {freq, mode, width, shift, pitch}, af 0..1, opts {mute, nr, squelchOpen} */
update(rx, af, opts) {
if (!this.ctx || !this.on) return;
opts = opts || {};
const t = this.ctx.currentTime, tc = 0.04;
this.master.gain.setTargetAtTime(opts.mute ? 0 : af * af * 0.6, t, 0.05);
const [pa, pb] = RP.PASS(rx.mode, rx.width, rx.shift, rx.pitch);
const isCw = /CW/.test(rx.mode);
const isFm = /FM|C4FM|DV|NFM|WFM/.test(rx.mode);
const lowA = isCw ? Math.max(100, (rx.pitch || 600) - rx.width / 2) : rx.mode === 'AM' || isFm ? 80 : 300;
const highA = isCw ? (rx.pitch || 600) + rx.width / 2 : Math.min(9000, Math.abs(pb - pa) + (rx.mode === 'AM' || isFm ? 0 : 300));
this.hp.frequency.setTargetAtTime(lowA, t, tc); this.lp.frequency.setTargetAtTime(highA, t, tc);
this.hp.Q.value = isCw ? 4 : 0.7; this.lp.Q.value = isCw ? 4 : 0.7;
const lvl = RP.rxLevel(rx);
const sq = opts.squelchOpen === false;
const nrK = opts.nr ? 0.35 : 1;
let voice = 0, fmQuiet = false;
const tones = [];
for (const c of lvl.comps) {
const rel = RP.clamp((c.dbm - lvl.noise + 10) / 50, 0, 1.2);
if (c.s.type === 'fm' || c.s.type === 'fmc') { fmQuiet = rel > 0.3; voice = Math.max(voice, isFm ? rel : 0); continue; }
if (c.s.type === 'ssb' || c.s.type === 'am') { if (c.s.type === 'am' || (c.s.sb === 'U') === (rx.mode !== 'LSB' && rx.mode !== 'LSB-D' && rx.mode !== 'DATA-L')) voice = Math.max(voice, rel); continue; }
let tone;
if (isCw) tone = (rx.pitch || 600) + (c.f - rx.freq) * (rx.mode === 'CW-R' || rx.mode === 'CW-L' ? -1 : 1);
else if (/^(LSB|DATA-L|LSB-D)$/.test(rx.mode)) tone = rx.freq - c.f;
else tone = c.f - rx.freq;
if (tone < 60 || tone > 4000) continue;
tones.push([tone, rel]);
}
this.noiseGain.gain.setTargetAtTime(sq ? 0 : (isFm ? (fmQuiet ? 0.08 : 0.9) : 0.55) * nrK * (isCw ? 0.6 : 1), t, tc);
tones.sort((a, b) => b[1] - a[1]);
let vi = 0;
for (const o of this.oscs) {
const tt = tones[vi++];
if (tt) { o.o.frequency.setTargetAtTime(tt[0], t, 0.003); o.g.gain.setTargetAtTime(sq ? 0 : tt[1] * 0.35, t, 0.006); } else o.g.gain.setTargetAtTime(0, t, 0.01);
}
const st = RP.now();
this.vf1.frequency.setTargetAtTime(500 + 400 * Math.abs(Math.sin(st * 3.1)), t, 0.03);
this.vf2.frequency.setTargetAtTime(1400 + 900 * Math.abs(Math.sin(st * 4.7 + 1)), t, 0.03);
this.buzz.frequency.setTargetAtTime(110 + 50 * Math.sin(st * 1.3), t, 0.05);
this.voiceGain.gain.setTargetAtTime(sq ? 0 : voice * 2.2, t, 0.02);
}
};
RP.audio = new RP.Audio();
const kick = () => { RP.audio.start(); window.removeEventListener('pointerdown', kick, true); };
window.addEventListener('pointerdown', kick, true);
/**
* LMR (DMR / P25) traffic simulator.
* new RP.Trunk({channels:[{name, tg}], onCall(call), onEnd(call), rate: mean seconds between calls})
* call: {id, alias, ch, tg, tgName, kind:'grp'|'priv'|'emer', rssi dBm, dur s, slot 1|2, cc}
* .paused = true stops new calls. .stop() kills timer. .force(ch) starts a call now.
*/
RP.ALIASES = ['DISPATCH', 'UNIT 14', 'CREW 3', 'YARD', 'RIG D220', 'SUPER 2', 'TRUCK 7', 'SAFETY', 'SHOP', 'PUMP 1', 'GATE', 'MEDIC 9', 'PATROL 4', 'FOREMAN', 'VAC 12', 'LOADER 3'];
RP.Trunk = class {
constructor(opt) { this.opt = Object.assign({ rate: 12 }, opt); this.active = null; this.t = null; this.paused = false; this._sched(4000); }
_sched(ms) { clearTimeout(this.t); this.t = setTimeout(() => this._fire(), ms == null ? (this.opt.rate * 0.4 + Math.random() * this.opt.rate) * 1000 : ms); }
_fire(chForce) {
if (!chForce && (this.paused || this.active || !this.opt.channels.length)) return this._sched();
const ch = chForce || this.opt.channels[Math.floor(Math.random() * this.opt.channels.length)];
const r = Math.random();
const call = { id: 1000 + Math.floor(Math.random() * 8999), alias: RP.ALIASES[Math.floor(Math.random() * RP.ALIASES.length)], ch, tg: ch.tg, tgName: ch.name, kind: r < 0.04 ? 'emer' : r < 0.14 ? 'priv' : 'grp', rssi: -115 + Math.random() * 60, dur: 2 + Math.random() * 7, slot: 1 + Math.floor(Math.random() * 2), cc: 1 };
this.active = call;
this.opt.onCall && this.opt.onCall(call);
clearTimeout(this._endT);
this._endT = setTimeout(() => { const c = this.active; this.active = null; this.opt.onEnd && this.opt.onEnd(c); this._sched(); }, call.dur * 1000);
}
force(ch) { this._fire(ch || this.opt.channels[0]); }
stop() { clearTimeout(this.t); clearTimeout(this._endT); }
};
/** LMR receive audio: call ~20x/s. on = call audible, vol 0..1. Vocoder-ish muffled voice. */
RP.lmrVoice = function (on, vol) {
const a = RP.audio; if (!a.ctx) return;
const t = a.ctx.currentTime;
a.master.gain.setTargetAtTime(vol * vol * 0.6, t, 0.05);
a.hp.frequency.setTargetAtTime(300, t, 0.02); a.lp.frequency.setTargetAtTime(3000, t, 0.02);
a.noiseGain.gain.setTargetAtTime(0, t, 0.02);
for (const o of a.oscs) o.g.gain.setTargetAtTime(0, t, 0.02);
const st = RP.now();
a.vf1.frequency.setTargetAtTime(450 + 450 * Math.abs(Math.sin(st * 3.7)), t, 0.03);
a.vf2.frequency.setTargetAtTime(1300 + 1000 * Math.abs(Math.sin(st * 5.1 + 1)), t, 0.03);
const syl = Math.abs(Math.sin(st * 5.5) * Math.sin(st * 2.3)) > 0.18 ? 1 : 0.1;
a.voiceGain.gain.setTargetAtTime(on ? 1.6 * syl : 0, t, 0.015);
};
RP.clock = () => { const d = new Date(); return String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0'); };
RP.utc = () => { const d = new Date(); return String(d.getUTCHours()).padStart(2, '0') + ':' + String(d.getUTCMinutes()).padStart(2, '0'); };
/** Scale a fixed-size design canvas (w x h CSS px) to fit the viewport, centred. */
RP.fit = function (el, w, h, pad) {
pad = pad == null ? 24 : pad;
const f = () => { const s = Math.min((innerWidth - pad * 2) / w, (innerHeight - pad * 2) / h); el.style.transform = 'translate(-50%,-50%) scale(' + s + ')'; };
el.style.position = 'absolute'; el.style.left = '50%'; el.style.top = '50%'; el.style.width = w + 'px'; el.style.height = h + 'px'; el.style.transformOrigin = '50% 50%';
addEventListener('resize', f); f();
};
})();