NOAA APT decoder and encoder (browser, no build step)
Decoder: streaming APT.Decoder (coherent PLL or envelope demod, sync A+B tracking loop with coasting and timing-jump re-lock), telemetry analysis, Q-gated impulse (FM click) repair. GUI with fast / realtime decode, Listen, live input, telemetry table, markers. Encoder: APT.Encoder with test impairments (noise, clicks, clock offset, fading, line-timing jump); encoder dialog that feeds the decoder. Tools: offline decode/encode, quality survey, stub-DOM GUI smoke test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
4bc15bb585
12 files changed
+3375
No files matched your search
@@ -0,0 +1,98 @@
|
|||||||
|
# NOAA APT decoder and encoder
|
||||||
|
|
||||||
|
Browser decoder and encoder for NOAA APT (2400 Hz AM subcarrier, 4160 words/s, 2 lines/s).
|
||||||
|
No build step.
|
||||||
|
|
||||||
|
python3 -m http.server -d ~/dev/noaa-apt-2026 8000 # then open http://localhost:8000/
|
||||||
|
|
||||||
|
Opening `index.html` directly works for files. Live input needs the page to be
|
||||||
|
served, because browsers only allow microphone access from a secure page.
|
||||||
|
|
||||||
|
## Files
|
||||||
|
|
||||||
|
| File | What |
|
||||||
|
|---|---|
|
||||||
|
| `apt.js` | Format constants, streaming `APT.Decoder`, `APT.AnalyzeTelemetry`, `APT.RepairRow`. No DOM; also loads in node. |
|
||||||
|
| `encoder.js` | `APT.BuildLine`, `APT.TelemetryWedges`, streaming `APT.Encoder` with test impairments, `APT.EncodeAll`. |
|
||||||
|
| `wav.js` | WAV reader/writer. Reads files at their native rate, unlike `decodeAudioData`, which resamples. |
|
||||||
|
| `app.js`, `encoder-ui.js`, `index.html`, `style.css` | GUI (decoder, encoder dialog) |
|
||||||
|
| `tools/decode.js` | `node tools/decode.js in.wav out.pgm [lines.txt] [--envelope] [--repair[=strong]]` |
|
||||||
|
| `tools/encode.js` | `node tools/encode.js out.wav [--pgm img.pgm] [--lines N] [--rate R] [--snr dB] [--ppm N] [--jump LINE]` |
|
||||||
|
| `tools/survey.js` | reference-free quality figures (lock %, sync, noise) for a set of WAVs |
|
||||||
|
| `tools/gui-smoke.js` | runs the GUI scripts on a stub DOM: encoder dialog, fast decode, repair toggles |
|
||||||
|
|
||||||
|
## GUI
|
||||||
|
|
||||||
|
- **Fast decode**: decodes the whole file as fast as possible.
|
||||||
|
- **Realtime**: decodes at playback speed (1x/2x/4x/8x). **Listen** plays the audio. Pause with space; click the progress bar to start from that point.
|
||||||
|
- **Live input**: decodes a sound-card input, such as an SDR on a virtual cable. **Listen** monitors the input.
|
||||||
|
- **Levels**:
|
||||||
|
- Telemetry (default): per-frame wedge 8 = white, wedge 9 = black, interpolated between frames. Follows gain changes during a pass.
|
||||||
|
- Auto: image percentiles.
|
||||||
|
- Sync: sync pulse plateaus.
|
||||||
|
- **Telemetry table**: each 128-line frame with the AVHRR channel IDs from wedge 16. A change is shown in amber.
|
||||||
|
- **Markers**: click the image to mark a line. Each marker lists its line, time and input sample number.
|
||||||
|
- **Demod**: coherent (default) or envelope. Takes effect on the next decode.
|
||||||
|
- **Repair**: off / normal (default) / strong impulse repair, see below. Applied at display time; the decoded data are kept, so switching it off shows the raw decode. **show** tints repaired pixels red (never saved).
|
||||||
|
- **Encoder…**: see below.
|
||||||
|
|
||||||
|
## Encoder
|
||||||
|
|
||||||
|
`Encoder…` opens a dialog. Sources:
|
||||||
|
- test pattern (checkerboard ramp in A, sine pattern in B);
|
||||||
|
- one image per channel (B empty = same as A; optional invert for IR style), scaled to 909 px wide, one line per row;
|
||||||
|
- a decoded full-line APT image (2080 wide, e.g. a reference PNG or **Save PNG** with *Full line*): either every word as is, or only the two images with fresh sync and telemetry.
|
||||||
|
|
||||||
|
Lines get sync A/B, minute markers (every 120 lines: 2 black, 2 white), and the 16-wedge telemetry: ramp 1/8..8/8, zero, PRTs, patch, back scan, wedge 16 = channel ID. Each word sets the amplitude of a 2400 Hz carrier phase-locked to the word clock (255 = full, 0 = 13%), band-limited to 2.4 kHz.
|
||||||
|
|
||||||
|
Impairments for testing: noise (SNR over the full band), FM clicks per second, sample-clock offset, fading, and the July 2019 line-timing jump (line N cut off after 1040 words).
|
||||||
|
|
||||||
|
**Encode & decode** loads the signal as the decoder input and fast-decodes it; **Encode & decode realtime** decodes it at playback speed with Listen; **Download WAV** saves 16-bit PCM.
|
||||||
|
## Decoder
|
||||||
|
|
||||||
|
I/Q mix at 2400 Hz, Blackman FIR lowpass at 2150 Hz, then coherent detection (a 2 Hz PLL on the carrier; the pixel is the in-phase part) or envelope detection, then a linear resample to 8320 Hz (2 samples/word). Coherent mode also outputs the quadrature part per word (`line.quad`), which holds only noise.
|
||||||
|
|
||||||
|
Line timing:
|
||||||
|
- Locked: sync A and sync B correlated together within +-16 samples of the prediction.
|
||||||
|
- A second-order tracking loop places each line: small deviations move the line a quarter of the way (more while acquiring), weighted by sync confidence; a clearly better position (dropped samples, a jump) is taken at once. The loop also tracks the line length, so the sound-card clock offset (ppm) does not skew the image.
|
||||||
|
- Expected sync missing: wide search over the whole line, re-locking at once on a clear sync A (corr > 0.75) or sync A+B (> 0.6). This handles the satellite jumping its line timing, even at 0 dB SNR.
|
||||||
|
- Weak sync: coasts on the predicted timing for up to 120 lines (1 min) before falling back to an unlocked search across the whole line, confirmed on the next line.
|
||||||
|
|
||||||
|
## Recovery of noisy recordings
|
||||||
|
|
||||||
|
Nothing here smooths the image. Every change was checked against ground truth: a clean real pass, re-encoded with known noise/clicks, decoded and compared.
|
||||||
|
|
||||||
|
1. **Line placement** (sync A+B, tracking loop): line-start jitter at 0 dB SNR went from 1.2 words (worst 8) to 0.04 words (worst 0.1); at -3 dB the worst is 0.2 words. Only where lines go changes, not the pixels.
|
||||||
|
2. **Coherent detection**: no Rician bias (envelope detection lifts dark pixels into a noise floor at low SNR). Same as envelope above ~12 dB SNR, 3 dB lower error at 0 dB. On the noisy reference passes the space-view noise relative to image range drops by 25-30%.
|
||||||
|
3. **Impulse (click) repair**: the noisy passes have FM threshold clicks, i.e. impulsive noise: 5-8% of quadrature samples beyond 4 sigma, against 0.006% for Gaussian noise. They show as black/white specks. `APT.RepairRow` is a switching filter: a pixel is replaced by the median of its 8 neighbours only if it is off that median by > 4x the row noise and > 3x the neighbours' spread, **and** the quadrature channel spikes there. The image is all in-phase, so real detail never triggers it. Every other pixel is left as decoded. On ground truth:
|
||||||
|
|
||||||
|
| test signal | RMS error raw | repaired | pixels changed | changes that moved closer to truth |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| clean | 4.49 | 4.49 | 0 | - |
|
||||||
|
| 20 dB SNR | 9.99 | 10.01 | 0.003% | - |
|
||||||
|
| 20 dB + 40 clicks/s | 15.85 | 11.20 | 1.05% | 99% |
|
||||||
|
| 9 dB + 150 clicks/s | 40.10 | 38.60 | 0.35% | 99.9% |
|
||||||
|
|
||||||
|
*Strong* (K 3.5, Q 2.5, spread 2.5) takes more clicks at 98-99% precision. On real passes it repairs ~0.8-1.5% of pixels, mostly in bursts and at the noisy ends of the pass; mid-pass on a clean recording ~0.01%. Even the cleanest reference pass (202007151233) has a click burst at line ~838, about 100 clicks/s.
|
||||||
|
4. **Telemetry**: wedge values are medians across the wedge columns, so clicks do not bias the calibration.
|
||||||
|
|
||||||
|
Not done, on purpose: narrower filters, median or denoise filters, line averaging. They remove noise only by removing detail. Lines that are pure noise stay noise; nothing is invented.
|
||||||
|
|
||||||
|
Checked against the 253 WAV/PNG pairs in `~/Downloads/apt/{audio,raw}`: line counts match the reference decoder within +-2 lines, except where the reference stopped early or cropped. The two all-noise recordings stay unlocked.
|
||||||
|
|
||||||
|
## 201907201213: where the malfunction starts
|
||||||
|
|
||||||
|
NOAA-15 AVHRR, July 2019.
|
||||||
|
|
||||||
|
| | full `.wav` | `_glitch.wav` |
|
||||||
|
|---|---|---|
|
||||||
|
| `_glitch.wav` starts at | line 563, ~281.4 s | 0 |
|
||||||
|
| malfunction onset | line 655, **327.85 s** (sample ~3,614,600 @ 11025) | line 92, 46.44 s |
|
||||||
|
|
||||||
|
`_glitch.wav` is the same audio as the full recording from 281.4 s onward: every decoded line matches, corr > 0.99. So the full file is good up to 327.85 s.
|
||||||
|
|
||||||
|
What happens at the onset:
|
||||||
|
- The satellite's line timing jumps by 1039 words, about half a line. Line 655 has sync A at word 0 and again at word 1040.
|
||||||
|
- A decoder that keeps its old timing, like the one behind the reference PNG, shows channels A and B swapped from there on. This decoder re-locks on the next line.
|
||||||
|
- The telemetry frame keeps its 128-line period. Wedge 16 changes from A=ch2/B=ch4 to A=ch4/B=ch2, and the A image ends partway across the line.
|
||||||
|
- The diagonal streaks follow, which looks like scan-motor jitter.
|
||||||
@@ -0,0 +1,748 @@
|
|||||||
|
/*
|
||||||
|
* apt.js - NOAA APT (Automatic Picture Transmission) core: format constants,
|
||||||
|
* streaming decoder and telemetry analysis. No DOM use: runs in the browser
|
||||||
|
* (classic <script>, exposes window.APT) and in node (module.exports).
|
||||||
|
*
|
||||||
|
* Format (NOAA KLM User's Guide, sec. 4.2):
|
||||||
|
* 2400 Hz AM subcarrier, 4160 words/s, 2 lines/s, 2080 words/line.
|
||||||
|
* words 0.. 38 Sync A (4 low + 7 cycles of 1040 Hz)
|
||||||
|
* 39.. 85 Space A (minute markers every 60 lines)
|
||||||
|
* 86.. 994 Image A
|
||||||
|
* 995..1039 Telemetry A (16 wedges x 8 lines, 128-line frame)
|
||||||
|
* 1040..1078 Sync B (4 low + 7 pulses at 832 pps)
|
||||||
|
* 1079..1125 Space B
|
||||||
|
* 1126..2034 Image B
|
||||||
|
* 2035..2079 Telemetry B
|
||||||
|
*/
|
||||||
|
(function (root) {
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
const WORD_RATE = 4160;
|
||||||
|
const LINE_WORDS = 2080;
|
||||||
|
const CARRIER = 2400;
|
||||||
|
const OSR = 2; /* decoder samples per word */
|
||||||
|
const RATE = WORD_RATE * OSR; /* 8320 Hz envelope rate */
|
||||||
|
const LINE_LEN = LINE_WORDS * OSR; /* 4160 envelope samples per line */
|
||||||
|
const FRAME_LINES = 128;
|
||||||
|
const WEDGE_LINES = 8;
|
||||||
|
|
||||||
|
const REGIONS = [
|
||||||
|
{ name: 'Sync A', start: 0, len: 39 },
|
||||||
|
{ name: 'Space A', start: 39, len: 47 },
|
||||||
|
{ name: 'Image A', start: 86, len: 909 },
|
||||||
|
{ name: 'Telemetry A', start: 995, len: 45 },
|
||||||
|
{ name: 'Sync B', start: 1040, len: 39 },
|
||||||
|
{ name: 'Space B', start: 1079, len: 47 },
|
||||||
|
{ name: 'Image B', start: 1126, len: 909 },
|
||||||
|
{ name: 'Telemetry B', start: 2035, len: 45 },
|
||||||
|
];
|
||||||
|
|
||||||
|
/* AVHRR channel for the wedge (1..6) that wedge 16 matches */
|
||||||
|
const CHANNEL_NAMES = ['1', '2', '3A', '4', '5', '3B'];
|
||||||
|
const CHANNEL_DESC = {
|
||||||
|
'1': 'visible 0.6 um', '2': 'near IR 0.9 um', '3A': 'near IR 1.6 um',
|
||||||
|
'3B': 'IR 3.7 um', '4': 'thermal IR 10.8 um', '5': 'thermal IR 12 um',
|
||||||
|
};
|
||||||
|
|
||||||
|
function SyncAWords()
|
||||||
|
{
|
||||||
|
const w = [0, 0, 0, 0];
|
||||||
|
for (let i = 0; i < 7; i++)
|
||||||
|
w.push(1, 1, 0, 0);
|
||||||
|
while (w.length < 39)
|
||||||
|
w.push(0);
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SyncBWords()
|
||||||
|
{
|
||||||
|
const w = [0, 0, 0, 0];
|
||||||
|
for (let i = 0; i < 7; i++)
|
||||||
|
w.push(1, 1, 1, 0, 0);
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
|
||||||
|
function RegionAt(word)
|
||||||
|
{
|
||||||
|
for (const r of REGIONS)
|
||||||
|
if (word >= r.start && word < r.start + r.len)
|
||||||
|
return r;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Windowed-sinc (Blackman) lowpass, odd length, unity DC gain */
|
||||||
|
function LowpassTaps(fs, cutoff, ntaps)
|
||||||
|
{
|
||||||
|
ntaps |= 1;
|
||||||
|
const taps = new Float32Array(ntaps);
|
||||||
|
const m = (ntaps - 1) / 2;
|
||||||
|
const fc = cutoff / fs;
|
||||||
|
let sum = 0;
|
||||||
|
for (let i = 0; i < ntaps; i++) {
|
||||||
|
const n = i - m;
|
||||||
|
const sinc = n === 0 ? 2 * fc : Math.sin(2 * Math.PI * fc * n) / (Math.PI * n);
|
||||||
|
const win = 0.42 - 0.5 * Math.cos(2 * Math.PI * i / (ntaps - 1)) +
|
||||||
|
0.08 * Math.cos(4 * Math.PI * i / (ntaps - 1));
|
||||||
|
taps[i] = sinc * win;
|
||||||
|
sum += taps[i];
|
||||||
|
}
|
||||||
|
for (let i = 0; i < ntaps; i++)
|
||||||
|
taps[i] /= sum;
|
||||||
|
return taps;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Streaming decoder. Feed mono float samples at any rate >= ~9.6 kHz with
|
||||||
|
* process(); complete lines are delivered to onLine(line) as
|
||||||
|
* { index, words: Float32Array(2080) demodulated, quad: Float32Array(2080)
|
||||||
|
* quadrature (coherent demod only, else null), sync: 0..1 quality,
|
||||||
|
* locked, time: seconds into the input of the line start, hi, lo }
|
||||||
|
*/
|
||||||
|
class Decoder {
|
||||||
|
constructor(fs, opts)
|
||||||
|
{
|
||||||
|
opts = opts || {};
|
||||||
|
this.fs = fs;
|
||||||
|
this.onLine = opts.onLine || null;
|
||||||
|
|
||||||
|
/* I/Q mix to baseband, lowpass, magnitude */
|
||||||
|
this.phInc = 2 * Math.PI * CARRIER / fs;
|
||||||
|
this.ph = 0;
|
||||||
|
const ntaps = Math.max(31, Math.round(fs / 2400 * 14)) | 1;
|
||||||
|
this.taps = LowpassTaps(fs, 2150, ntaps);
|
||||||
|
this.ntaps = ntaps;
|
||||||
|
this.dI = new Float32Array(ntaps * 2);
|
||||||
|
this.dQ = new Float32Array(ntaps * 2);
|
||||||
|
this.di = 0;
|
||||||
|
this.groupDelay = (ntaps - 1) / 2;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Demodulation. 'coherent' (default): a slow PLL (2 Hz) tracks the
|
||||||
|
* carrier phase and the in-phase component is the pixel value.
|
||||||
|
* Linear, unbiased, and half the noise power of 'envelope' (|z|),
|
||||||
|
* which also lifts dark pixels at low SNR (Rician bias). The PLL
|
||||||
|
* averages ~0.1 s of carrier, so it holds where single pixels are
|
||||||
|
* buried in noise; the APT carrier never drops below ~13%.
|
||||||
|
*/
|
||||||
|
this.coherent = (opts.demod || 'coherent') === 'coherent';
|
||||||
|
const wn = 2 * Math.PI * 2 / fs;
|
||||||
|
this.pllKp = 2 * 0.707 * wn;
|
||||||
|
this.pllKi = wn * wn;
|
||||||
|
this.pllTh = 0;
|
||||||
|
this.pllF = 0;
|
||||||
|
this.pllAmp = 0;
|
||||||
|
this.pllA = 1 - Math.exp(-2 * Math.PI * 5 / fs);
|
||||||
|
|
||||||
|
/* linear resampler to RATE */
|
||||||
|
this.step = fs / RATE;
|
||||||
|
this.inPos = -1; /* absolute index of the current input sample */
|
||||||
|
this.prevMag = 0;
|
||||||
|
this.tNext = 0; /* input position of the next output sample */
|
||||||
|
|
||||||
|
/* envelope buffer */
|
||||||
|
this.buf = new Float32Array(LINE_LEN * 8);
|
||||||
|
this.qbuf = new Float32Array(LINE_LEN * 8); /* quadrature (coherent only) */
|
||||||
|
this.prevQ = 0;
|
||||||
|
this.bufLen = 0;
|
||||||
|
this.bufBase = 0; /* absolute envelope index of buf[0] */
|
||||||
|
|
||||||
|
/* sync */
|
||||||
|
const sa = SyncAWords();
|
||||||
|
this.tmplOn = [];
|
||||||
|
this.tmplOff = [];
|
||||||
|
const t = new Float32Array(sa.length * OSR);
|
||||||
|
for (let i = 0; i < t.length; i++)
|
||||||
|
t[i] = sa[(i / OSR) | 0] ? 1 : -1;
|
||||||
|
let mean = 0;
|
||||||
|
for (let i = 0; i < t.length; i++)
|
||||||
|
mean += t[i];
|
||||||
|
mean /= t.length;
|
||||||
|
let nrm = 0;
|
||||||
|
for (let i = 0; i < t.length; i++) {
|
||||||
|
t[i] -= mean;
|
||||||
|
nrm += t[i] * t[i];
|
||||||
|
}
|
||||||
|
this.tmpl = t;
|
||||||
|
this.tmplNorm = Math.sqrt(nrm);
|
||||||
|
/* sync B, 1040 words later: a second timing measurement per line */
|
||||||
|
const sbw = SyncBWords();
|
||||||
|
const tb = new Float32Array(sbw.length * OSR);
|
||||||
|
let mb = 0;
|
||||||
|
for (let i = 0; i < tb.length; i++)
|
||||||
|
mb += (tb[i] = sbw[(i / OSR) | 0] ? 1 : -1);
|
||||||
|
mb /= tb.length;
|
||||||
|
let nb = 0;
|
||||||
|
for (let i = 0; i < tb.length; i++) {
|
||||||
|
tb[i] -= mb;
|
||||||
|
nb += tb[i] * tb[i];
|
||||||
|
}
|
||||||
|
this.tmplB = tb;
|
||||||
|
this.tmplBNorm = Math.sqrt(nb);
|
||||||
|
this.offB = 1040 * OSR;
|
||||||
|
/* plateau samples for level estimates: middle of each 2-word run */
|
||||||
|
for (let c = 0; c < 7; c++) {
|
||||||
|
const on = (4 + 4 * c) * OSR, off = (6 + 4 * c) * OSR;
|
||||||
|
this.tmplOn.push(on + 1, on + 2);
|
||||||
|
this.tmplOff.push(off + 1, off + 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.tracking = opts.tracking !== false;
|
||||||
|
this.coastLines = opts.coast || 120;
|
||||||
|
this.jumped = false;
|
||||||
|
this.trackLines = 0;
|
||||||
|
this.nextStart = LINE_LEN / 2; /* relative to buf[0] */
|
||||||
|
this.locked = false;
|
||||||
|
this.weak = 0;
|
||||||
|
this.lineLenEst = LINE_LEN;
|
||||||
|
this.lastStrongAbs = -1;
|
||||||
|
this.lastStrongLine = -1;
|
||||||
|
this.lineCount = 0;
|
||||||
|
this.lastSync = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Input samples (Float32Array or Array), any length */
|
||||||
|
process(x)
|
||||||
|
{
|
||||||
|
const taps = this.taps, nt = this.ntaps;
|
||||||
|
const dI = this.dI, dQ = this.dQ;
|
||||||
|
const c0 = Math.cos(this.phInc), s0 = Math.sin(this.phInc);
|
||||||
|
let cr = Math.cos(this.ph), ci = Math.sin(this.ph);
|
||||||
|
let di = this.di;
|
||||||
|
for (let n = 0; n < x.length; n++) {
|
||||||
|
const v = x[n];
|
||||||
|
dI[di] = dI[di + nt] = v * cr;
|
||||||
|
dQ[di] = dQ[di + nt] = -v * ci;
|
||||||
|
di++;
|
||||||
|
if (di >= nt)
|
||||||
|
di = 0;
|
||||||
|
/* rotate oscillator */
|
||||||
|
const t = cr * c0 - ci * s0;
|
||||||
|
ci = cr * s0 + ci * c0;
|
||||||
|
cr = t;
|
||||||
|
|
||||||
|
let si = 0, sq = 0;
|
||||||
|
for (let k = 0; k < nt; k++) {
|
||||||
|
si += taps[k] * dI[di + k];
|
||||||
|
sq += taps[k] * dQ[di + k];
|
||||||
|
}
|
||||||
|
let mag, quad = 0;
|
||||||
|
if (this.coherent) {
|
||||||
|
const ct = Math.cos(this.pllTh), st = Math.sin(this.pllTh);
|
||||||
|
const a = si * ct + sq * st, b = sq * ct - si * st;
|
||||||
|
this.pllAmp += this.pllA * (Math.sqrt(si * si + sq * sq) - this.pllAmp);
|
||||||
|
const e = this.pllAmp > 1e-9 ? Math.max(-1, Math.min(1, b / this.pllAmp)) : 0;
|
||||||
|
this.pllF += this.pllKi * e;
|
||||||
|
this.pllTh += this.pllF + this.pllKp * e;
|
||||||
|
if (this.pllTh > Math.PI)
|
||||||
|
this.pllTh -= 2 * Math.PI;
|
||||||
|
else if (this.pllTh < -Math.PI)
|
||||||
|
this.pllTh += 2 * Math.PI;
|
||||||
|
mag = 2 * a;
|
||||||
|
quad = 2 * b;
|
||||||
|
} else {
|
||||||
|
mag = 2 * Math.sqrt(si * si + sq * sq);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.inPos++;
|
||||||
|
while (this.tNext <= this.inPos) {
|
||||||
|
const f = this.tNext - (this.inPos - 1);
|
||||||
|
this._push(this.prevMag + (mag - this.prevMag) * f, this.prevQ + (quad - this.prevQ) * f);
|
||||||
|
this.tNext += this.step;
|
||||||
|
}
|
||||||
|
this.prevMag = mag;
|
||||||
|
this.prevQ = quad;
|
||||||
|
}
|
||||||
|
/* renormalize oscillator against drift */
|
||||||
|
const r = 1 / Math.sqrt(cr * cr + ci * ci);
|
||||||
|
this.ph = Math.atan2(ci * r, cr * r);
|
||||||
|
this.di = di;
|
||||||
|
this._scan();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Emit whatever is buffered as (possibly partial-sync) lines */
|
||||||
|
flush()
|
||||||
|
{
|
||||||
|
this._scan();
|
||||||
|
}
|
||||||
|
|
||||||
|
_push(v, q)
|
||||||
|
{
|
||||||
|
if (this.bufLen >= this.buf.length) {
|
||||||
|
const nb = new Float32Array(this.buf.length * 2);
|
||||||
|
nb.set(this.buf);
|
||||||
|
this.buf = nb;
|
||||||
|
const nq = new Float32Array(this.qbuf.length * 2);
|
||||||
|
nq.set(this.qbuf);
|
||||||
|
this.qbuf = nq;
|
||||||
|
}
|
||||||
|
this.qbuf[this.bufLen] = q;
|
||||||
|
this.buf[this.bufLen++] = v;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* sync A and sync B together: the timing estimate for a line */
|
||||||
|
_ncorrAB(k)
|
||||||
|
{
|
||||||
|
return 0.5 * (this._ncorr(k) + this._ncorr(k + this.offB, this.tmplB, this.tmplBNorm));
|
||||||
|
}
|
||||||
|
|
||||||
|
_ncorr(k, tmpl, tnorm)
|
||||||
|
{
|
||||||
|
const b = this.buf, t = tmpl || this.tmpl, n = t.length;
|
||||||
|
let sum = 0, s1 = 0, s2 = 0;
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const v = b[k + i];
|
||||||
|
sum += t[i] * v;
|
||||||
|
s1 += v;
|
||||||
|
s2 += v * v;
|
||||||
|
}
|
||||||
|
const varn = s2 - s1 * s1 / n;
|
||||||
|
if (varn <= 1e-12)
|
||||||
|
return 0;
|
||||||
|
return sum / (Math.sqrt(varn) * (tnorm || this.tmplNorm));
|
||||||
|
}
|
||||||
|
|
||||||
|
_scan()
|
||||||
|
{
|
||||||
|
const L = LINE_LEN, T = this.tmpl.length;
|
||||||
|
for (;;) {
|
||||||
|
/* drop consumed samples */
|
||||||
|
const drop = Math.floor(this.nextStart - L);
|
||||||
|
if (drop > L * 2) {
|
||||||
|
this.buf.copyWithin(0, drop, this.bufLen);
|
||||||
|
this.qbuf.copyWithin(0, drop, this.bufLen);
|
||||||
|
this.bufLen -= drop;
|
||||||
|
this.bufBase += drop;
|
||||||
|
this.nextStart -= drop;
|
||||||
|
}
|
||||||
|
|
||||||
|
const S = this.locked ? 16 : L / 2;
|
||||||
|
const lo = Math.max(0, Math.floor(this.nextStart - S));
|
||||||
|
const hi = Math.floor(this.nextStart + S);
|
||||||
|
const need = this.locked ? Math.floor(this.nextStart) + L / 2 + L + T + 2 : hi + 2 * L + T + 2;
|
||||||
|
if (this.bufLen < need)
|
||||||
|
break;
|
||||||
|
|
||||||
|
let best = -2, bestK = Math.round(this.nextStart);
|
||||||
|
for (let k = lo; k <= hi; k++) {
|
||||||
|
let c;
|
||||||
|
if (this.locked)
|
||||||
|
c = this._ncorrAB(k);
|
||||||
|
else
|
||||||
|
c = 0.5 * (this._ncorr(k) + this._ncorr(k + L));
|
||||||
|
if (c > best) {
|
||||||
|
best = c;
|
||||||
|
bestK = k;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const thr = this.locked ? 0.3 : 0.5;
|
||||||
|
if (this.locked && best <= thr) {
|
||||||
|
/*
|
||||||
|
* Lost the expected sync: the satellite may have jumped
|
||||||
|
* its line timing. Look across the whole line for one
|
||||||
|
* clear sync and re-lock there at once.
|
||||||
|
*/
|
||||||
|
const wlo = Math.max(0, Math.floor(this.nextStart - L / 2));
|
||||||
|
let bestAB = -2, bestKAB = bestK;
|
||||||
|
for (let k = wlo; k < wlo + L; k++) {
|
||||||
|
const c = this._ncorr(k);
|
||||||
|
if (c > best) {
|
||||||
|
best = c;
|
||||||
|
bestK = k;
|
||||||
|
}
|
||||||
|
/* sync A + B: re-locks through noise after a jump */
|
||||||
|
if (c > 0.2) {
|
||||||
|
const cab = 0.5 * (c + this._ncorr(k + this.offB, this.tmplB, this.tmplBNorm));
|
||||||
|
if (cab > bestAB) {
|
||||||
|
bestAB = cab;
|
||||||
|
bestKAB = k;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (best < 0.75 && bestAB >= 0.6) {
|
||||||
|
best = 0.75;
|
||||||
|
bestK = bestKAB;
|
||||||
|
}
|
||||||
|
if (best < 0.75)
|
||||||
|
best = Math.min(best, thr);
|
||||||
|
else {
|
||||||
|
this.lastStrongLine = -1;
|
||||||
|
this.jumped = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let start;
|
||||||
|
if (best > thr) {
|
||||||
|
/* parabolic sub-sample refinement */
|
||||||
|
const cf = this.locked && !this.jumped ? (k) => this._ncorrAB(k) : (k) => this._ncorr(k);
|
||||||
|
let frac = 0;
|
||||||
|
if (bestK > 0) {
|
||||||
|
const a = cf(bestK - 1), b = cf(bestK), c = cf(bestK + 1);
|
||||||
|
const d = a - 2 * b + c;
|
||||||
|
if (d < 0)
|
||||||
|
frac = Math.max(-0.5, Math.min(0.5, 0.5 * (a - c) / d));
|
||||||
|
}
|
||||||
|
start = bestK + frac;
|
||||||
|
/*
|
||||||
|
* Tracking: the satellite's line clock is very stable, so a
|
||||||
|
* small deviation from the prediction is mostly noise. Move
|
||||||
|
* a quarter of the way unless the measured position is
|
||||||
|
* clearly better (dropped samples, a timing jump), which is
|
||||||
|
* taken at once. Pixels are not touched, only line placement.
|
||||||
|
*/
|
||||||
|
let tracked = false;
|
||||||
|
if (this.locked && !this.jumped && this.tracking) {
|
||||||
|
const dev = start - this.nextStart;
|
||||||
|
const kp = Math.round(this.nextStart);
|
||||||
|
if (Math.abs(dev) < 4 || best - cf(kp) < 0.12) {
|
||||||
|
/* second-order loop: also steer the line length */
|
||||||
|
/*
|
||||||
|
* wide loop while acquiring, then narrow; weighted
|
||||||
|
* by sync confidence so noise peaks (0.3..0.4)
|
||||||
|
* barely move the timing or the line length
|
||||||
|
*/
|
||||||
|
const acq = this.trackLines < 24;
|
||||||
|
const wgt = Math.max(0, Math.min(1, (best - 0.35) / 0.3));
|
||||||
|
start = this.nextStart + (acq ? 0.6 : 0.25) * wgt * dev;
|
||||||
|
this.lineLenEst += (acq ? 0.15 : 0.03) * wgt * dev;
|
||||||
|
tracked = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/* sound cards are within a few hundred ppm */
|
||||||
|
this.lineLenEst = Math.max(LINE_LEN * 0.997, Math.min(LINE_LEN * 1.003, this.lineLenEst));
|
||||||
|
this.trackLines = tracked ? this.trackLines + 1 : 0;
|
||||||
|
this.jumped = false;
|
||||||
|
const abs = this.bufBase + start;
|
||||||
|
if (!tracked && this.lastStrongLine === this.lineCount - 1 && this.lastStrongAbs >= 0) {
|
||||||
|
const obs = abs - this.lastStrongAbs;
|
||||||
|
if (Math.abs(obs - this.lineLenEst) < 8 && best > 0.5)
|
||||||
|
this.lineLenEst += 0.05 * (obs - this.lineLenEst);
|
||||||
|
}
|
||||||
|
this.lastStrongAbs = abs;
|
||||||
|
this.lastStrongLine = this.lineCount;
|
||||||
|
this.locked = true;
|
||||||
|
this.weak = 0;
|
||||||
|
} else {
|
||||||
|
const wasLocked = this.locked;
|
||||||
|
start = wasLocked ? this.nextStart : Math.max(0, this.nextStart - L / 2);
|
||||||
|
/* coast on the predicted timing through fades: the line
|
||||||
|
* clock is stable, and the wide search above still
|
||||||
|
* catches a real jump */
|
||||||
|
if (++this.weak > this.coastLines)
|
||||||
|
this.locked = false;
|
||||||
|
this.lastSync = Math.max(0, best);
|
||||||
|
this._emit(start, this.lastSync);
|
||||||
|
/* unlocked: nextStart is the centre of a one-line search window */
|
||||||
|
this.nextStart = start + this.lineLenEst + (this.locked ? 0 : L / 2);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
this.lastSync = Math.max(0, best);
|
||||||
|
this._emit(start, this.lastSync);
|
||||||
|
this.nextStart = start + this.lineLenEst;
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_sample(p, b)
|
||||||
|
{
|
||||||
|
const i = Math.floor(p), f = p - i;
|
||||||
|
b = b || this.buf;
|
||||||
|
return b[i] + (b[i + 1] - b[i]) * f;
|
||||||
|
}
|
||||||
|
|
||||||
|
_emit(start, q)
|
||||||
|
{
|
||||||
|
const words = new Float32Array(LINE_WORDS);
|
||||||
|
for (let w = 0; w < LINE_WORDS; w++) {
|
||||||
|
const p = start + w * OSR;
|
||||||
|
words[w] = 0.5 * (this._sample(p) + this._sample(p + 1));
|
||||||
|
}
|
||||||
|
/* quadrature words: noise only (no image), used to spot clicks */
|
||||||
|
let quad = null;
|
||||||
|
if (this.coherent) {
|
||||||
|
quad = new Float32Array(LINE_WORDS);
|
||||||
|
const qb = this.qbuf;
|
||||||
|
for (let w = 0; w < LINE_WORDS; w++) {
|
||||||
|
const p = start + w * OSR;
|
||||||
|
quad[w] = 0.5 * (this._sample(p, qb) + this._sample(p + 1, qb));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let hi = 0, lo = 0;
|
||||||
|
for (const s of this.tmplOn)
|
||||||
|
hi += this._sample(start + s);
|
||||||
|
for (const s of this.tmplOff)
|
||||||
|
lo += this._sample(start + s);
|
||||||
|
hi /= this.tmplOn.length;
|
||||||
|
lo /= this.tmplOff.length;
|
||||||
|
const abs = this.bufBase + start;
|
||||||
|
const line = {
|
||||||
|
index: this.lineCount++,
|
||||||
|
words: words,
|
||||||
|
quad: quad,
|
||||||
|
sync: q,
|
||||||
|
locked: this.locked,
|
||||||
|
time: (abs * this.step - this.groupDelay) / this.fs,
|
||||||
|
hi: hi,
|
||||||
|
lo: lo,
|
||||||
|
};
|
||||||
|
if (this.onLine)
|
||||||
|
this.onLine(line);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Sample clock offset implied by the tracked line length, in ppm */
|
||||||
|
clockPpm()
|
||||||
|
{
|
||||||
|
return (this.lineLenEst / LINE_LEN - 1) * 1e6;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Telemetry: find the 128-line frames in a list of decoded lines and read
|
||||||
|
* the wedges. Returns { phase, frames: [{ start, a: [16], b: [16], chA,
|
||||||
|
* chB, quality }] }. Wedge 8 is white, wedge 9 is black (zero modulation),
|
||||||
|
* wedge 16 equals the wedge (1..6) of the channel being sent.
|
||||||
|
*/
|
||||||
|
function TelemetryColumns(lines)
|
||||||
|
{
|
||||||
|
const n = lines.length;
|
||||||
|
const ta = new Float32Array(n), tb = new Float32Array(n);
|
||||||
|
/* median across the wedge columns: clicks do not pull it */
|
||||||
|
const va = new Float32Array(33), vb = new Float32Array(33);
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const w = lines[i].words;
|
||||||
|
for (let k = 0; k < 33; k++) {
|
||||||
|
va[k] = w[1001 + k];
|
||||||
|
vb[k] = w[2041 + k];
|
||||||
|
}
|
||||||
|
va.sort();
|
||||||
|
vb.sort();
|
||||||
|
ta[i] = va[16];
|
||||||
|
tb[i] = vb[16];
|
||||||
|
}
|
||||||
|
return { ta, tb };
|
||||||
|
}
|
||||||
|
|
||||||
|
function WedgeMean(col, start, k)
|
||||||
|
{
|
||||||
|
const a = start + (k - 1) * WEDGE_LINES + 2, b = start + k * WEDGE_LINES - 2;
|
||||||
|
if (a < 0 || b > col.length)
|
||||||
|
return NaN;
|
||||||
|
let s = 0;
|
||||||
|
for (let i = a; i < b; i++)
|
||||||
|
s += col[i];
|
||||||
|
return s / (b - a);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Sum of the steps at the wedge 1..9 boundaries if a frame starts here */
|
||||||
|
function EdgeScore(col, start)
|
||||||
|
{
|
||||||
|
let e = 0;
|
||||||
|
for (let k = 0; k <= 9; k++) {
|
||||||
|
const i = start + k * WEDGE_LINES;
|
||||||
|
if (i < 1 || i >= col.length)
|
||||||
|
continue;
|
||||||
|
e += Math.abs(col[i] - col[i - 1]);
|
||||||
|
}
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Correlation of wedges 1..9 against the 1/8..8/8, 0 ramp */
|
||||||
|
function RampScore(col, start)
|
||||||
|
{
|
||||||
|
const ref = [1, 2, 3, 4, 5, 6, 7, 8, 0];
|
||||||
|
const v = [];
|
||||||
|
for (let k = 1; k <= 9; k++) {
|
||||||
|
const m = WedgeMean(col, start, k);
|
||||||
|
if (isNaN(m))
|
||||||
|
return NaN;
|
||||||
|
v.push(m);
|
||||||
|
}
|
||||||
|
let mr = 0, mv = 0;
|
||||||
|
for (let i = 0; i < 9; i++) {
|
||||||
|
mr += ref[i];
|
||||||
|
mv += v[i];
|
||||||
|
}
|
||||||
|
mr /= 9;
|
||||||
|
mv /= 9;
|
||||||
|
let sxy = 0, sxx = 0, syy = 0;
|
||||||
|
for (let i = 0; i < 9; i++) {
|
||||||
|
sxy += (ref[i] - mr) * (v[i] - mv);
|
||||||
|
sxx += (ref[i] - mr) ** 2;
|
||||||
|
syy += (v[i] - mv) ** 2;
|
||||||
|
}
|
||||||
|
if (sxx === 0 || syy === 0)
|
||||||
|
return 0;
|
||||||
|
return sxy / Math.sqrt(sxx * syy);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AnalyzeTelemetry(lines)
|
||||||
|
{
|
||||||
|
const out = { phase: -1, frames: [] };
|
||||||
|
if (lines.length < FRAME_LINES)
|
||||||
|
return out;
|
||||||
|
const { ta, tb } = TelemetryColumns(lines);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Frame starts: local maxima of the wedge 1..9 ramp score (both
|
||||||
|
* columns). Found per frame rather than with one global phase, since a
|
||||||
|
* line-timing jump on the satellite moves the frame phase too.
|
||||||
|
*/
|
||||||
|
const n = lines.length;
|
||||||
|
const score = new Float32Array(n).fill(-2);
|
||||||
|
for (let st = 0; st + 9 * WEDGE_LINES <= n; st++) {
|
||||||
|
const ra = RampScore(ta, st), rb = RampScore(tb, st);
|
||||||
|
if (!isNaN(ra) && !isNaN(rb))
|
||||||
|
score[st] = 0.5 * (ra + rb);
|
||||||
|
}
|
||||||
|
const starts = [];
|
||||||
|
for (let st = 0; st < n; st++) {
|
||||||
|
if (score[st] < 0.9)
|
||||||
|
continue;
|
||||||
|
let isMax = true;
|
||||||
|
for (let k = Math.max(0, st - 60); k < Math.min(n, st + 60) && isMax; k++)
|
||||||
|
if (score[k] > score[st] || (score[k] === score[st] && k < st))
|
||||||
|
isMax = false;
|
||||||
|
if (!isMax)
|
||||||
|
continue;
|
||||||
|
/* the ramp score is flat over a few lines: refine on wedge edges */
|
||||||
|
let bestSt = st, bestE = -1;
|
||||||
|
for (let k = Math.max(1, st - 4); k <= st + 4; k++) {
|
||||||
|
const e = EdgeScore(ta, k) + EdgeScore(tb, k);
|
||||||
|
if (e > bestE) {
|
||||||
|
bestE = e;
|
||||||
|
bestSt = k;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!starts.length || bestSt > starts[starts.length - 1].st)
|
||||||
|
starts.push({ st: bestSt, q: score[st] });
|
||||||
|
}
|
||||||
|
out.phase = starts.length ? starts[0].st % FRAME_LINES : -1;
|
||||||
|
|
||||||
|
for (const { st, q } of starts) {
|
||||||
|
const a = [], b = [];
|
||||||
|
for (let k = 1; k <= 16; k++) {
|
||||||
|
a.push(WedgeMean(ta, st, k));
|
||||||
|
b.push(WedgeMean(tb, st, k));
|
||||||
|
}
|
||||||
|
const complete = !isNaN(a[15]);
|
||||||
|
out.frames.push({
|
||||||
|
start: st,
|
||||||
|
a: a,
|
||||||
|
b: b,
|
||||||
|
chA: complete ? ChannelFromWedges(a) : '?',
|
||||||
|
chB: complete ? ChannelFromWedges(b) : '?',
|
||||||
|
quality: q,
|
||||||
|
complete: complete,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Impulse repair for FM threshold clicks. A switching filter, not a
|
||||||
|
* smoothing one: a word is replaced by the median of its 8 neighbours only
|
||||||
|
* when all of these hold:
|
||||||
|
* - it is off that median by more than K x the row's noise scale and
|
||||||
|
* KS x the spread of the neighbours themselves (edges, texture stay);
|
||||||
|
* - the quadrature channel spikes there (|Q| > KQ x its noise). The
|
||||||
|
* image is all in-phase, so real detail never shows in Q, while a
|
||||||
|
* click lands at a random carrier phase and almost always does.
|
||||||
|
* Everything else is copied unchanged; with no Q (envelope demod) nothing
|
||||||
|
* is repaired. line/prev/next are decoded lines; prev/next may be null.
|
||||||
|
* Returns { words, mask, count }.
|
||||||
|
*/
|
||||||
|
const IMG_A = 86, IMG_B = 1126, IMG_W = 909;
|
||||||
|
const med8 = new Float32Array(8), dev8 = new Float32Array(8);
|
||||||
|
|
||||||
|
function Median8(a)
|
||||||
|
{
|
||||||
|
for (let i = 1; i < 8; i++) {
|
||||||
|
const v = a[i];
|
||||||
|
let j = i - 1;
|
||||||
|
while (j >= 0 && a[j] > v) {
|
||||||
|
a[j + 1] = a[j];
|
||||||
|
j--;
|
||||||
|
}
|
||||||
|
a[j + 1] = v;
|
||||||
|
}
|
||||||
|
return 0.5 * (a[3] + a[4]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function RobustSigma(v, off, len)
|
||||||
|
{
|
||||||
|
const a = new Float32Array(Math.ceil(len / 2));
|
||||||
|
let n = 0;
|
||||||
|
for (let x = 0; x < len; x += 2)
|
||||||
|
a[n++] = Math.abs(v[off + x]);
|
||||||
|
a.sort();
|
||||||
|
return 1.4826 * a[n >> 1] + 1e-9;
|
||||||
|
}
|
||||||
|
|
||||||
|
function RepairRow(line, prev, next, opts)
|
||||||
|
{
|
||||||
|
opts = opts || {};
|
||||||
|
const cur = line.words, q = line.quad;
|
||||||
|
const out = new Float32Array(cur);
|
||||||
|
const mask = new Uint8Array(LINE_WORDS);
|
||||||
|
if (!prev || !next || !q)
|
||||||
|
return { words: out, mask, count: 0 };
|
||||||
|
const K = opts.k || 4, KS = opts.ks || 3, KQ = opts.kq || 3;
|
||||||
|
const p = prev.words, n = next.words;
|
||||||
|
/* noise scales never below 1.5% of the sync contrast: on a clean
|
||||||
|
* signal Q holds only filter leakage at sharp edges */
|
||||||
|
const floor = 0.015 * Math.max(1e-6, line.hi - line.lo);
|
||||||
|
let count = 0;
|
||||||
|
const dev = new Float32Array(IMG_W), med = new Float32Array(IMG_W), spr = new Float32Array(IMG_W);
|
||||||
|
for (const off of [IMG_A, IMG_B]) {
|
||||||
|
const sq = Math.max(floor, RobustSigma(q, off, IMG_W));
|
||||||
|
for (let x = 1; x < IMG_W - 1; x++) {
|
||||||
|
const k = off + x;
|
||||||
|
med8[0] = p[k - 1]; med8[1] = p[k]; med8[2] = p[k + 1];
|
||||||
|
med8[3] = cur[k - 1]; med8[4] = cur[k + 1];
|
||||||
|
med8[5] = n[k - 1]; med8[6] = n[k]; med8[7] = n[k + 1];
|
||||||
|
const m = Median8(med8);
|
||||||
|
for (let i = 0; i < 8; i++)
|
||||||
|
dev8[i] = Math.abs(med8[i] - m);
|
||||||
|
spr[x] = 1.4826 * Median8(dev8);
|
||||||
|
med[x] = m;
|
||||||
|
dev[x] = cur[k] - m;
|
||||||
|
}
|
||||||
|
const sd = Math.max(floor, RobustSigma(dev, 1, IMG_W - 2));
|
||||||
|
for (let x = 1; x < IMG_W - 1; x++) {
|
||||||
|
const k = off + x, a = Math.abs(dev[x]);
|
||||||
|
if (a <= K * sd || a <= KS * spr[x])
|
||||||
|
continue;
|
||||||
|
const qa = Math.max(Math.abs(q[k - 1]), Math.abs(q[k]), Math.abs(q[k + 1]));
|
||||||
|
if (qa <= KQ * sq)
|
||||||
|
continue;
|
||||||
|
out[k] = med[x];
|
||||||
|
mask[k] = 1;
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { words: out, mask, count };
|
||||||
|
}
|
||||||
|
|
||||||
|
function ChannelFromWedges(w)
|
||||||
|
{
|
||||||
|
let best = -1, bd = 1e9;
|
||||||
|
for (let k = 0; k < 6; k++) {
|
||||||
|
const d = Math.abs(w[15] - w[k]);
|
||||||
|
if (d < bd) {
|
||||||
|
bd = d;
|
||||||
|
best = k;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best < 0 ? '?' : CHANNEL_NAMES[best];
|
||||||
|
}
|
||||||
|
|
||||||
|
const APT = {
|
||||||
|
WORD_RATE, LINE_WORDS, CARRIER, OSR, RATE, LINE_LEN, FRAME_LINES, WEDGE_LINES,
|
||||||
|
REGIONS, CHANNEL_NAMES, CHANNEL_DESC,
|
||||||
|
SyncAWords, SyncBWords, RegionAt, LowpassTaps,
|
||||||
|
Decoder, AnalyzeTelemetry, TelemetryColumns, RepairRow,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (typeof module !== 'undefined' && module.exports)
|
||||||
|
module.exports = APT;
|
||||||
|
else
|
||||||
|
root.APT = APT;
|
||||||
|
})(typeof window !== 'undefined' ? window : globalThis);
|
||||||
+271
@@ -0,0 +1,271 @@
|
|||||||
|
/*
|
||||||
|
* encoder-ui.js - encoder dialog: build APT lines from a test pattern, two
|
||||||
|
* channel images or a decoded full-line APT image, preview them, add
|
||||||
|
* impairments, then download a WAV or hand the signal to the decoder
|
||||||
|
* (window.AptApp from app.js).
|
||||||
|
*/
|
||||||
|
(function () {
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
const $ = (id) => document.getElementById(id);
|
||||||
|
const W = APT.LINE_WORDS, IW = 909;
|
||||||
|
|
||||||
|
const enc = {
|
||||||
|
lines: [], /* Uint8Array(2080) per line */
|
||||||
|
imgA: null, /* { w: 909, h, data: Uint8Array } */
|
||||||
|
imgB: null,
|
||||||
|
frame: null, /* { h, data: Uint8Array(2080 * h) } */
|
||||||
|
busy: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const id of ['encChA', 'encChB'])
|
||||||
|
for (const c of APT.CHANNEL_NAMES) {
|
||||||
|
const o = document.createElement('option');
|
||||||
|
o.value = c;
|
||||||
|
o.textContent = `${c} (${APT.CHANNEL_DESC[c]})`;
|
||||||
|
$(id).appendChild(o);
|
||||||
|
}
|
||||||
|
$('encChA').value = '2';
|
||||||
|
$('encChB').value = '4';
|
||||||
|
|
||||||
|
const srcKind = () => document.querySelector('input[name=encSrc]:checked').value;
|
||||||
|
|
||||||
|
/* image file -> grayscale, scaled to the given width (height keeps aspect) */
|
||||||
|
async function LoadGray(file, width)
|
||||||
|
{
|
||||||
|
const bmp = await createImageBitmap(file);
|
||||||
|
const h = Math.max(1, Math.round(bmp.height * width / bmp.width));
|
||||||
|
const c = document.createElement('canvas');
|
||||||
|
c.width = width;
|
||||||
|
c.height = h;
|
||||||
|
const ctx = c.getContext('2d', { willReadFrequently: true });
|
||||||
|
ctx.imageSmoothingQuality = 'high';
|
||||||
|
ctx.drawImage(bmp, 0, 0, width, h);
|
||||||
|
const px = ctx.getImageData(0, 0, width, h).data;
|
||||||
|
const g = new Uint8Array(width * h);
|
||||||
|
for (let i = 0; i < g.length; i++)
|
||||||
|
g[i] = Math.round(0.299 * px[4 * i] + 0.587 * px[4 * i + 1] + 0.114 * px[4 * i + 2]);
|
||||||
|
return { w: width, h, data: g };
|
||||||
|
}
|
||||||
|
|
||||||
|
/* the same test pattern as tools/encode.js */
|
||||||
|
function Pattern(i, x, ch)
|
||||||
|
{
|
||||||
|
if (ch === 0)
|
||||||
|
return ((x >> 5) + (i >> 5)) & 1 ? Math.round(x / 908 * 255) : 255 - Math.round(x / 908 * 255);
|
||||||
|
return Math.round(127.5 + 127.5 * Math.sin(x / 40 + i / 25) * Math.cos(i / 60));
|
||||||
|
}
|
||||||
|
|
||||||
|
function BuildLines()
|
||||||
|
{
|
||||||
|
const opts = { chA: $('encChA').value, chB: $('encChB').value };
|
||||||
|
const out = [];
|
||||||
|
const kind = srcKind();
|
||||||
|
if (kind === 'pattern') {
|
||||||
|
const n = Math.max(8, Math.min(8000, parseInt($('encLines').value, 10) || 600));
|
||||||
|
const a = new Uint8Array(IW), b = new Uint8Array(IW);
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
for (let x = 0; x < IW; x++) {
|
||||||
|
a[x] = Pattern(i, x, 0);
|
||||||
|
b[x] = Pattern(i, x, 1);
|
||||||
|
}
|
||||||
|
out.push(APT.BuildLine(i, a, b, opts));
|
||||||
|
}
|
||||||
|
} else if (kind === 'images') {
|
||||||
|
const A = enc.imgA, B = enc.imgB || enc.imgA;
|
||||||
|
if (!A)
|
||||||
|
return out;
|
||||||
|
const n = Math.max(A.h, B.h);
|
||||||
|
const inv = $('encInvB').checked;
|
||||||
|
const a = new Uint8Array(IW), b = new Uint8Array(IW);
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const ra = Math.min(i, A.h - 1), rb = Math.min(i, B.h - 1);
|
||||||
|
for (let x = 0; x < IW; x++) {
|
||||||
|
a[x] = i < A.h ? A.data[ra * IW + x] : 0;
|
||||||
|
const v = i < B.h ? B.data[rb * IW + x] : 0;
|
||||||
|
b[x] = inv ? 255 - v : v;
|
||||||
|
}
|
||||||
|
out.push(APT.BuildLine(i, a, b, opts));
|
||||||
|
}
|
||||||
|
} else if (enc.frame) {
|
||||||
|
const F = enc.frame, keep = $('encKeepTel').checked;
|
||||||
|
for (let i = 0; i < F.h; i++) {
|
||||||
|
const row = F.data.subarray(i * W, (i + 1) * W);
|
||||||
|
if (keep) {
|
||||||
|
out.push(new Uint8Array(row));
|
||||||
|
} else {
|
||||||
|
/* keep the two images, regenerate sync, space and telemetry */
|
||||||
|
out.push(APT.BuildLine(i, row.subarray(86, 995), row.subarray(1126, 2035), opts));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Preview()
|
||||||
|
{
|
||||||
|
enc.lines = BuildLines();
|
||||||
|
const n = enc.lines.length, c = $('encCanvas');
|
||||||
|
const rate = parseInt($('encRate').value, 10);
|
||||||
|
if (!n) {
|
||||||
|
c.height = 1;
|
||||||
|
$('encInfo').textContent = srcKind() === 'pattern' ? '' : 'choose an image';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
c.width = W;
|
||||||
|
c.height = n;
|
||||||
|
const ctx = c.getContext('2d');
|
||||||
|
const id = ctx.createImageData(W, n);
|
||||||
|
const d = id.data;
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const l = enc.lines[i];
|
||||||
|
for (let x = 0; x < W; x++) {
|
||||||
|
const p = (i * W + x) * 4;
|
||||||
|
d[p] = d[p + 1] = d[p + 2] = l[x];
|
||||||
|
d[p + 3] = 255;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ctx.putImageData(id, 0, 0);
|
||||||
|
const sec = n / 2;
|
||||||
|
$('encInfo').textContent = `${n} lines, ${Math.floor(sec / 60)}:${String(Math.round(sec % 60)).padStart(2, '0')} at 2 lines/s, ` +
|
||||||
|
`${(sec * rate * 2 / 1048576).toFixed(1)} MB as 16-bit WAV at ${rate} Hz`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function EncOpts()
|
||||||
|
{
|
||||||
|
const num = (id, d) => {
|
||||||
|
const v = parseFloat($(id).value);
|
||||||
|
return isFinite(v) ? v : d;
|
||||||
|
};
|
||||||
|
const o = { ppm: num('encPpm', 0), fade: Math.max(0, Math.min(1, num('encFade', 0))), seed: (Math.random() * 1e9) | 0 };
|
||||||
|
if ($('encNoiseOn').checked)
|
||||||
|
o.snr = num('encSnr', 12);
|
||||||
|
if ($('encClicksOn').checked)
|
||||||
|
o.clicks = Math.max(0, num('encClicks', 0));
|
||||||
|
if ($('encJumpOn').checked)
|
||||||
|
o.jumpAt = Math.max(1, Math.round(num('encJump', 300)));
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* modulate in slices so the page stays responsive */
|
||||||
|
function Encode()
|
||||||
|
{
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const lines = enc.lines, n = lines.length;
|
||||||
|
const rate = parseInt($('encRate').value, 10);
|
||||||
|
const e = new APT.Encoder(rate, (i) => (i < n ? lines[i] : null), EncOpts());
|
||||||
|
const total = Math.ceil((n / 2 + 0.1) * rate);
|
||||||
|
const chunk = Math.round(rate / 4);
|
||||||
|
let out = new Float32Array(total), len = 0;
|
||||||
|
const step = () => {
|
||||||
|
const t = performance.now();
|
||||||
|
while (performance.now() - t < 40) {
|
||||||
|
const p = e.render(chunk);
|
||||||
|
if (len + p.length > out.length) {
|
||||||
|
const nb = new Float32Array(Math.max(out.length * 2, len + p.length));
|
||||||
|
nb.set(out.subarray(0, len));
|
||||||
|
out = nb;
|
||||||
|
}
|
||||||
|
out.set(p, len);
|
||||||
|
len += p.length;
|
||||||
|
if (p.length < chunk) {
|
||||||
|
$('encBarFill').style.width = '100%';
|
||||||
|
resolve({ rate, data: out.slice(0, len) });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$('encBarFill').style.width = (100 * len / total).toFixed(1) + '%';
|
||||||
|
setTimeout(step, 0);
|
||||||
|
};
|
||||||
|
step();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function BaseName()
|
||||||
|
{
|
||||||
|
const k = srcKind();
|
||||||
|
const o = EncOpts();
|
||||||
|
let s = 'apt-' + (k === 'pattern' ? 'pattern' : k === 'images' ? 'images' : 'frame');
|
||||||
|
if (o.snr !== undefined)
|
||||||
|
s += `-snr${o.snr}`;
|
||||||
|
if (o.clicks)
|
||||||
|
s += `-clk${o.clicks}`;
|
||||||
|
if (o.jumpAt)
|
||||||
|
s += `-jump${o.jumpAt}`;
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function Run(action)
|
||||||
|
{
|
||||||
|
if (enc.busy)
|
||||||
|
return;
|
||||||
|
Preview();
|
||||||
|
if (!enc.lines.length)
|
||||||
|
return;
|
||||||
|
enc.busy = true;
|
||||||
|
for (const id of ['encDecode', 'encRealtime', 'encSave'])
|
||||||
|
$(id).disabled = true;
|
||||||
|
try {
|
||||||
|
const sig = await Encode();
|
||||||
|
const name = BaseName() + '.wav';
|
||||||
|
if (action === 'save') {
|
||||||
|
const blob = new Blob([Wav.Build(sig.data, sig.rate)], { type: 'audio/wav' });
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = URL.createObjectURL(blob);
|
||||||
|
a.download = name;
|
||||||
|
a.click();
|
||||||
|
setTimeout(() => URL.revokeObjectURL(a.href), 10000);
|
||||||
|
} else {
|
||||||
|
$('encDialog').close();
|
||||||
|
window.AptApp.LoadSource({ name: name + ' (encoded)', rate: sig.rate, data: sig.data });
|
||||||
|
if (action === 'realtime')
|
||||||
|
window.AptApp.StartRealtime();
|
||||||
|
else
|
||||||
|
window.AptApp.StartFast();
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
enc.busy = false;
|
||||||
|
for (const id of ['encDecode', 'encRealtime', 'encSave'])
|
||||||
|
$(id).disabled = false;
|
||||||
|
$('encBarFill').style.width = '0';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Pick(kind)
|
||||||
|
{
|
||||||
|
document.querySelector(`input[name=encSrc][value=${kind}]`).checked = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
$('btnEncoder').onclick = () => {
|
||||||
|
$('encDialog').showModal();
|
||||||
|
Preview();
|
||||||
|
};
|
||||||
|
$('encImgA').onchange = async (e) => {
|
||||||
|
enc.imgA = e.target.files[0] ? await LoadGray(e.target.files[0], IW) : null;
|
||||||
|
Pick('images');
|
||||||
|
Preview();
|
||||||
|
};
|
||||||
|
$('encImgB').onchange = async (e) => {
|
||||||
|
enc.imgB = e.target.files[0] ? await LoadGray(e.target.files[0], IW) : null;
|
||||||
|
Pick('images');
|
||||||
|
Preview();
|
||||||
|
};
|
||||||
|
$('encFrame').onchange = async (e) => {
|
||||||
|
const f = e.target.files[0];
|
||||||
|
if (f) {
|
||||||
|
const g = await LoadGray(f, W);
|
||||||
|
enc.frame = { h: g.h, data: g.data };
|
||||||
|
} else {
|
||||||
|
enc.frame = null;
|
||||||
|
}
|
||||||
|
Pick('frame');
|
||||||
|
Preview();
|
||||||
|
};
|
||||||
|
for (const id of ['encLines', 'encChA', 'encChB', 'encRate', 'encInvB', 'encKeepTel'])
|
||||||
|
$(id).addEventListener('change', Preview);
|
||||||
|
for (const el of document.querySelectorAll('input[name=encSrc]'))
|
||||||
|
el.addEventListener('change', Preview);
|
||||||
|
$('encDecode').onclick = () => Run('decode');
|
||||||
|
$('encRealtime').onclick = () => Run('realtime');
|
||||||
|
$('encSave').onclick = () => Run('save');
|
||||||
|
})();
|
||||||
+291
@@ -0,0 +1,291 @@
|
|||||||
|
/*
|
||||||
|
* encoder.js - NOAA APT encoder. Loads after apt.js and adds APT.Encoder,
|
||||||
|
* APT.BuildLine and APT.TelemetryWedges. No DOM use; also loads in node.
|
||||||
|
*
|
||||||
|
* Signal (NOAA KLM User's Guide, sec. 4.2): each 8-bit word sets the
|
||||||
|
* amplitude of a 2400 Hz carrier, 255 = full scale, 0 = 13% (87% modulation).
|
||||||
|
* The carrier is phase locked to the word clock: 1200 cycles per line.
|
||||||
|
* The word stream is band-limited before modulation, like the D/A filter on
|
||||||
|
* the satellite, so the output fits an 11025 Hz recording.
|
||||||
|
*
|
||||||
|
* Optional impairments, for testing decoders: additive noise at a given SNR,
|
||||||
|
* a sample-clock offset, slow fading, and a line-timing jump (the satellite
|
||||||
|
* restarting its line half a line late, as NOAA-15 did in July 2019).
|
||||||
|
*/
|
||||||
|
(function (root) {
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
const APT = root.APT || (typeof require !== 'undefined' ? require('./apt.js') : null);
|
||||||
|
if (!APT)
|
||||||
|
throw new Error('encoder.js needs apt.js');
|
||||||
|
|
||||||
|
const W = APT.LINE_WORDS;
|
||||||
|
const SYNC_HI = 244, SYNC_LO = 11;
|
||||||
|
const MOD_DEPTH = 0.87;
|
||||||
|
|
||||||
|
/* Channel IDs: wedge number (1..6) that wedge 16 repeats */
|
||||||
|
const CHANNEL_WEDGE = { '1': 1, '2': 2, '3A': 3, '4': 4, '5': 5, '3B': 6 };
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Values of the 16 telemetry wedges for one channel. Wedges 1-8 are the
|
||||||
|
* 1/8..8/8 ramp, 9 is zero modulation, 10-13 the black-body PRTs, 14 the
|
||||||
|
* patch temperature, 15 the back scan, 16 the channel ID.
|
||||||
|
*/
|
||||||
|
function TelemetryWedges(channel, opts)
|
||||||
|
{
|
||||||
|
opts = opts || {};
|
||||||
|
const w = [];
|
||||||
|
for (let k = 1; k <= 8; k++)
|
||||||
|
w.push(Math.round(255 * k / 8));
|
||||||
|
w.push(0);
|
||||||
|
const prt = opts.prt || [105, 106, 104, 105];
|
||||||
|
w.push(...prt);
|
||||||
|
w.push(opts.patch !== undefined ? opts.patch : 98);
|
||||||
|
const ir = channel === '3B' || channel === '4' || channel === '5';
|
||||||
|
w.push(opts.backScan !== undefined ? opts.backScan : (ir ? 120 : 10));
|
||||||
|
const id = CHANNEL_WEDGE[channel] || 1;
|
||||||
|
w.push(w[id - 1]);
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* One 2080-word line.
|
||||||
|
* index line number (sets the telemetry wedge and minute markers)
|
||||||
|
* a, b Uint8Array/Array(909) image pixels, or null for black
|
||||||
|
* chA, chB channel IDs ('1','2','3A','3B','4','5') for wedge 16
|
||||||
|
* spaceA/B space-view word (default: black for visible, white for IR)
|
||||||
|
*/
|
||||||
|
function BuildLine(index, a, b, opts, out)
|
||||||
|
{
|
||||||
|
opts = opts || {};
|
||||||
|
const words = out || new Uint8Array(W);
|
||||||
|
const sa = APT.SyncAWords(), sb = APT.SyncBWords();
|
||||||
|
const chA = opts.chA || '2', chB = opts.chB || '4';
|
||||||
|
const tA = opts.telA || TelemetryWedges(chA, opts);
|
||||||
|
const tB = opts.telB || TelemetryWedges(chB, opts);
|
||||||
|
const isIR = (c) => c === '3B' || c === '4' || c === '5';
|
||||||
|
const spA = opts.spaceA !== undefined ? opts.spaceA : (isIR(chA) ? 255 : 0);
|
||||||
|
const spB = opts.spaceB !== undefined ? opts.spaceB : (isIR(chB) ? 255 : 0);
|
||||||
|
const frame = (index + (opts.framePhase || 0)) % APT.FRAME_LINES;
|
||||||
|
const wedge = Math.floor((frame < 0 ? frame + APT.FRAME_LINES : frame) / APT.WEDGE_LINES);
|
||||||
|
/* minute markers: every 120 lines, two black then two white */
|
||||||
|
const mm = index % 120;
|
||||||
|
const marker = mm < 2 ? 0 : mm < 4 ? 255 : -1;
|
||||||
|
|
||||||
|
for (let i = 0; i < 39; i++) {
|
||||||
|
words[i] = sa[i] ? SYNC_HI : SYNC_LO;
|
||||||
|
words[1040 + i] = sb[i] ? SYNC_HI : SYNC_LO;
|
||||||
|
}
|
||||||
|
words.fill(marker >= 0 ? marker : spA, 39, 86);
|
||||||
|
words.fill(marker >= 0 ? marker : spB, 1079, 1126);
|
||||||
|
for (let i = 0; i < 909; i++) {
|
||||||
|
words[86 + i] = a ? a[i] : 0;
|
||||||
|
words[1126 + i] = b ? b[i] : 0;
|
||||||
|
}
|
||||||
|
words.fill(tA[wedge], 995, 1040);
|
||||||
|
words.fill(tB[wedge], 2035, 2080);
|
||||||
|
return words;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Streaming modulator. source(lineIndex) returns a 2080-word line (any
|
||||||
|
* array of 0..255) or null when there are no more lines. render(n) returns
|
||||||
|
* the next n samples (Float32Array, peak ~0.9) and fewer at the end.
|
||||||
|
*
|
||||||
|
* opts: snr (dB, carrier power over noise in the 0..fs/2 band; omit for
|
||||||
|
* none), ppm (sample clock offset), fade (depth 0..1), fadePeriod (s),
|
||||||
|
* jumpAt (line at which the satellite restarts its line timing),
|
||||||
|
* jumpWords (how far, default 1040), clicks (FM threshold clicks per
|
||||||
|
* second), seed, gain.
|
||||||
|
*/
|
||||||
|
class Encoder {
|
||||||
|
constructor(fs, source, opts)
|
||||||
|
{
|
||||||
|
opts = opts || {};
|
||||||
|
this.fs = fs;
|
||||||
|
this.source = source;
|
||||||
|
this.opts = opts;
|
||||||
|
this.gain = opts.gain !== undefined ? opts.gain : 0.9;
|
||||||
|
/* word clock, in words per output sample */
|
||||||
|
this.wordStep = APT.WORD_RATE / fs * (1 + (opts.ppm || 0) * 1e-6);
|
||||||
|
this.wordPos = 0; /* fractional word position in the stream */
|
||||||
|
this.carrierInc = 2 * Math.PI * APT.CARRIER / APT.WORD_RATE; /* per word */
|
||||||
|
this.line = null;
|
||||||
|
this.lineIndex = -1; /* satellite line counter */
|
||||||
|
this.wordInLine = W; /* force a fetch */
|
||||||
|
this.done = false;
|
||||||
|
this.samples = 0;
|
||||||
|
|
||||||
|
/* band-limit the word stream: FIR over a word-rate ZOH, applied at
|
||||||
|
* 8 sub-samples per word, then sampled at fs by linear interpolation */
|
||||||
|
this.sub = 8;
|
||||||
|
this.taps = APT.LowpassTaps(APT.WORD_RATE * this.sub, opts.bandwidth || 2400, 8 * this.sub + 1);
|
||||||
|
this.hist = new Float32Array(this.taps.length * 2);
|
||||||
|
this.hi = 0;
|
||||||
|
this.subPos = 0; /* sub-samples generated */
|
||||||
|
this.env0 = 0;
|
||||||
|
this.env1 = 0;
|
||||||
|
this.tail = 0;
|
||||||
|
/* start ahead by the filter delay so line 0 begins at t = 0 */
|
||||||
|
this.wordPos = (this.taps.length - 1) / 2 / this.sub;
|
||||||
|
this.wordPos0 = this.wordPos;
|
||||||
|
|
||||||
|
this.noise = 0;
|
||||||
|
if (opts.snr !== undefined && opts.snr !== null && isFinite(opts.snr)) {
|
||||||
|
/* mean carrier power of an average APT line ~ (0.6 * gain)^2 / 2 */
|
||||||
|
const pc = (0.6 * this.gain) ** 2 / 2;
|
||||||
|
this.noise = Math.sqrt(pc / Math.pow(10, opts.snr / 10));
|
||||||
|
}
|
||||||
|
this.rng = Mulberry32(opts.seed || 1);
|
||||||
|
this.clickRate = (opts.clicks || 0) / fs; /* clicks per second */
|
||||||
|
this.clickW = 0.06e-3 * fs; /* pulse sigma, samples */
|
||||||
|
this.clickHalf = Math.ceil(3 * this.clickW);
|
||||||
|
this.clicks = [];
|
||||||
|
this.spare = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* next word of the stream, or -1 once the source has ended */
|
||||||
|
_word()
|
||||||
|
{
|
||||||
|
const o = this.opts;
|
||||||
|
const cut = o.jumpAt !== undefined && this.lineIndex === o.jumpAt ?
|
||||||
|
W - (o.jumpWords !== undefined ? o.jumpWords : 1040) : W;
|
||||||
|
if (this.wordInLine >= cut) {
|
||||||
|
/* at jumpAt the satellite drops the rest of the line and
|
||||||
|
* starts the next one early */
|
||||||
|
this.lineIndex++;
|
||||||
|
this.line = this.done ? null : this.source(this.lineIndex);
|
||||||
|
if (!this.line)
|
||||||
|
this.done = true;
|
||||||
|
this.wordInLine = 0;
|
||||||
|
}
|
||||||
|
if (this.done)
|
||||||
|
return -1;
|
||||||
|
return this.line[this.wordInLine++];
|
||||||
|
}
|
||||||
|
|
||||||
|
/* next band-limited sub-sample of the amplitude envelope */
|
||||||
|
_subSample()
|
||||||
|
{
|
||||||
|
if (this.subPos % this.sub === 0)
|
||||||
|
this.curWord = this.done ? -1 : this._word();
|
||||||
|
this.subPos++;
|
||||||
|
if (this.curWord < 0)
|
||||||
|
this.tail++;
|
||||||
|
const amp = this.curWord < 0 ? 0 : 1 - MOD_DEPTH * (1 - this.curWord / 255);
|
||||||
|
const n = this.taps.length;
|
||||||
|
this.hist[this.hi] = this.hist[this.hi + n] = amp;
|
||||||
|
this.hi = (this.hi + 1) % n;
|
||||||
|
let s = 0;
|
||||||
|
for (let k = 0; k < n; k++)
|
||||||
|
s += this.taps[k] * this.hist[this.hi + k];
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
render(n)
|
||||||
|
{
|
||||||
|
const out = new Float32Array(n);
|
||||||
|
const o = this.opts;
|
||||||
|
const fade = o.fade || 0, fadeP = o.fadePeriod || 7;
|
||||||
|
let i = 0;
|
||||||
|
for (; i < n; i++) {
|
||||||
|
/* advance the envelope to wordPos */
|
||||||
|
const target = this.wordPos * this.sub;
|
||||||
|
while (this.subPos <= target + 1) {
|
||||||
|
this.env0 = this.env1;
|
||||||
|
this.env1 = this._subSample();
|
||||||
|
}
|
||||||
|
if (this.tail > this.taps.length)
|
||||||
|
break;
|
||||||
|
const f = target - (this.subPos - 2);
|
||||||
|
const env = this.env0 + (this.env1 - this.env0) * Math.max(0, Math.min(1, f));
|
||||||
|
/* carrier locked to the word clock */
|
||||||
|
let v = env * Math.sin(this.carrierInc * (this.wordPos - this.wordPos0));
|
||||||
|
if (fade)
|
||||||
|
v *= 1 - fade * 0.5 * (1 - Math.cos(2 * Math.PI * this.samples / this.fs / fadeP));
|
||||||
|
v *= this.gain;
|
||||||
|
if (this.noise)
|
||||||
|
v += this.noise * this._gauss();
|
||||||
|
if (this.clickRate) {
|
||||||
|
/* FM threshold clicks: short pulses of random sign */
|
||||||
|
if (this.rng() < this.clickRate)
|
||||||
|
this.clicks.push({ t: 0, a: (this.rng() < 0.5 ? -1 : 1) * (0.3 + this.rng()) * this.gain });
|
||||||
|
for (let k = this.clicks.length - 1; k >= 0; k--) {
|
||||||
|
const c = this.clicks[k], u = (c.t - this.clickHalf) / this.clickW;
|
||||||
|
v += c.a * Math.exp(-0.5 * u * u);
|
||||||
|
if (++c.t > 2 * this.clickHalf)
|
||||||
|
this.clicks.splice(k, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out[i] = v;
|
||||||
|
this.wordPos += this.wordStep;
|
||||||
|
this.samples++;
|
||||||
|
}
|
||||||
|
return i < n ? out.subarray(0, i) : out;
|
||||||
|
}
|
||||||
|
|
||||||
|
_gauss()
|
||||||
|
{
|
||||||
|
if (this.spare !== null) {
|
||||||
|
const s = this.spare;
|
||||||
|
this.spare = null;
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
let u, v, r;
|
||||||
|
do {
|
||||||
|
u = 2 * this.rng() - 1;
|
||||||
|
v = 2 * this.rng() - 1;
|
||||||
|
r = u * u + v * v;
|
||||||
|
} while (r >= 1 || r === 0);
|
||||||
|
const m = Math.sqrt(-2 * Math.log(r) / r);
|
||||||
|
this.spare = v * m;
|
||||||
|
return u * m;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* seconds of signal emitted so far */
|
||||||
|
time()
|
||||||
|
{
|
||||||
|
return this.samples / this.fs;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Mulberry32(a)
|
||||||
|
{
|
||||||
|
return function () {
|
||||||
|
a |= 0;
|
||||||
|
a = (a + 0x6D2B79F5) | 0;
|
||||||
|
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
||||||
|
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||||
|
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Render a whole source to one Float32Array */
|
||||||
|
function EncodeAll(fs, source, opts)
|
||||||
|
{
|
||||||
|
const enc = new Encoder(fs, source, opts);
|
||||||
|
const parts = [];
|
||||||
|
let total = 0;
|
||||||
|
for (;;) {
|
||||||
|
const p = enc.render(fs);
|
||||||
|
parts.push(p);
|
||||||
|
total += p.length;
|
||||||
|
if (p.length < fs)
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const out = new Float32Array(total);
|
||||||
|
let o = 0;
|
||||||
|
for (const p of parts) {
|
||||||
|
out.set(p, o);
|
||||||
|
o += p.length;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.assign(APT, {
|
||||||
|
SYNC_HI, SYNC_LO, MOD_DEPTH, CHANNEL_WEDGE,
|
||||||
|
TelemetryWedges, BuildLine, Encoder, EncodeAll,
|
||||||
|
});
|
||||||
|
if (typeof module !== 'undefined' && module.exports)
|
||||||
|
module.exports = APT;
|
||||||
|
})(typeof window !== 'undefined' ? window : globalThis);
|
||||||
+179
@@ -0,0 +1,179 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>NOAA APT Decoder / Encoder</title>
|
||||||
|
<link rel="stylesheet" href="style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header id="toolbar">
|
||||||
|
<div class="group">
|
||||||
|
<span class="title">APT</span>
|
||||||
|
<label class="btn" title="Open a WAV (or any audio the browser can decode)">Open…
|
||||||
|
<input type="file" id="fileInput" accept="audio/*,.wav" hidden>
|
||||||
|
</label>
|
||||||
|
<span id="srcName" class="dim">no file</span>
|
||||||
|
<button id="btnEncoder" title="Make an APT signal from images or a test pattern">Encoder…</button>
|
||||||
|
</div>
|
||||||
|
<div class="group">
|
||||||
|
<button id="btnFast" disabled title="Decode the whole file as fast as possible">Fast decode</button>
|
||||||
|
<button id="btnRealtime" disabled title="Decode at playback speed">Realtime</button>
|
||||||
|
<select id="speed" title="Realtime speed">
|
||||||
|
<option value="1">1x</option><option value="2">2x</option>
|
||||||
|
<option value="4">4x</option><option value="8">8x</option>
|
||||||
|
</select>
|
||||||
|
<label class="chk" title="Play the audio while decoding in realtime / monitor live input"><input type="checkbox" id="listen" checked> Listen</label>
|
||||||
|
<input type="range" id="volume" min="0" max="1" step="0.01" value="0.5" title="Volume">
|
||||||
|
<button id="btnPause" disabled title="Pause / resume (space)">Pause</button>
|
||||||
|
<button id="btnStop" disabled>Stop</button>
|
||||||
|
</div>
|
||||||
|
<div class="group">
|
||||||
|
<button id="btnLive" title="Decode live audio input (SDR via line-in / virtual cable)">Live input</button>
|
||||||
|
<select id="device" title="Input device"><option value="">default input</option></select>
|
||||||
|
</div>
|
||||||
|
<div class="group">
|
||||||
|
<select id="view" title="View">
|
||||||
|
<option value="full">Full line</option>
|
||||||
|
<option value="AB">A + B images</option>
|
||||||
|
<option value="A">Channel A</option>
|
||||||
|
<option value="B">Channel B</option>
|
||||||
|
</select>
|
||||||
|
<select id="demod" title="Demodulator (applies to the next decode)">
|
||||||
|
<option value="coherent">Coherent</option>
|
||||||
|
<option value="envelope">Envelope</option>
|
||||||
|
</select>
|
||||||
|
<select id="repair" title="Impulse (click) repair: replaces only pixels that are clearly corrupted; the raw decode is kept">
|
||||||
|
<option value="off">Repair off</option>
|
||||||
|
<option value="normal" selected>Repair</option>
|
||||||
|
<option value="strong">Repair strong</option>
|
||||||
|
</select>
|
||||||
|
<label class="chk" title="Tint repaired pixels red (not saved)"><input type="checkbox" id="showRepairs"> show</label>
|
||||||
|
<select id="contrast" title="Levels">
|
||||||
|
<option value="telemetry">Telemetry levels</option>
|
||||||
|
<option value="auto">Auto contrast</option>
|
||||||
|
<option value="sync">Sync levels</option>
|
||||||
|
</select>
|
||||||
|
<select id="zoom" title="Zoom">
|
||||||
|
<option value="fit">Fit width</option>
|
||||||
|
<option value="1">1:1</option>
|
||||||
|
<option value="0.5">1:2</option>
|
||||||
|
</select>
|
||||||
|
<label class="chk"><input type="checkbox" id="follow" checked> Follow</label>
|
||||||
|
<button id="btnSave" disabled>Save PNG</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div id="progress" title="Click to seek (realtime)"><div id="progressFill"></div><div id="progressPlay"></div></div>
|
||||||
|
|
||||||
|
<main>
|
||||||
|
<div id="viewport">
|
||||||
|
<div id="drop" class="hint">Drop an APT recording here, or use Open… / Live input</div>
|
||||||
|
<div id="stack">
|
||||||
|
<canvas id="image" width="2080" height="0"></canvas>
|
||||||
|
<canvas id="overlay" width="2080" height="0"></canvas>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<aside id="side">
|
||||||
|
<section>
|
||||||
|
<h2>Status</h2>
|
||||||
|
<table class="kv">
|
||||||
|
<tr><th>Mode</th><td id="stMode">idle</td></tr>
|
||||||
|
<tr><th>Input</th><td id="stRate">-</td></tr>
|
||||||
|
<tr><th>Position</th><td id="stPos">-</td></tr>
|
||||||
|
<tr><th>Lines</th><td id="stLines">0</td></tr>
|
||||||
|
<tr><th>Sync</th><td><span id="stLock" class="badge">-</span> <span id="stSync">-</span></td></tr>
|
||||||
|
<tr><th>Clock</th><td id="stClock">-</td></tr>
|
||||||
|
<tr><th>Repaired</th><td id="stRepair">-</td></tr>
|
||||||
|
</table>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<h2>Spectrum</h2>
|
||||||
|
<canvas id="spectrum" width="320" height="90"></canvas>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<h2>Last line</h2>
|
||||||
|
<canvas id="scope" width="320" height="80"></canvas>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<h2>Sync quality</h2>
|
||||||
|
<canvas id="synchist" width="320" height="40"></canvas>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<h2>Telemetry</h2>
|
||||||
|
<canvas id="wedges" width="320" height="70"></canvas>
|
||||||
|
<div id="frames" class="scroll"></div>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<h2>Cursor</h2>
|
||||||
|
<div id="cursor" class="mono dim">hover the image</div>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<h2>Markers <button id="btnCopyMarks" class="small" title="Copy marker list">copy</button> <button id="btnClearMarks" class="small">clear</button></h2>
|
||||||
|
<div id="markers" class="scroll mono"><span class="dim">click the image to mark a line</span></div>
|
||||||
|
</section>
|
||||||
|
</aside>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<dialog id="encDialog">
|
||||||
|
<form method="dialog" id="encForm">
|
||||||
|
<header class="dlg-head">
|
||||||
|
<span class="title">APT encoder</span>
|
||||||
|
<button value="close" class="small" title="Close">×</button>
|
||||||
|
</header>
|
||||||
|
<div class="enc-body">
|
||||||
|
<div class="enc-opts">
|
||||||
|
<fieldset>
|
||||||
|
<legend>Source</legend>
|
||||||
|
<label><input type="radio" name="encSrc" value="pattern" checked> Test pattern,
|
||||||
|
<input type="number" id="encLines" value="600" min="8" max="8000" step="1"> lines</label>
|
||||||
|
<label><input type="radio" name="encSrc" value="images"> Images for channels A and B</label>
|
||||||
|
<div class="sub">
|
||||||
|
<label>A <input type="file" id="encImgA" accept="image/*"></label>
|
||||||
|
<label>B <input type="file" id="encImgB" accept="image/*"> <span class="dim">(empty: same as A)</span></label>
|
||||||
|
<label class="chk"><input type="checkbox" id="encInvB"> invert B (IR: cold = white)</label>
|
||||||
|
</div>
|
||||||
|
<label><input type="radio" name="encSrc" value="frame"> Decoded APT image, full line (2080 wide)</label>
|
||||||
|
<div class="sub">
|
||||||
|
<input type="file" id="encFrame" accept="image/*">
|
||||||
|
<label class="chk"><input type="checkbox" id="encKeepTel" checked> keep its sync and telemetry</label>
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
<fieldset>
|
||||||
|
<legend>Signal</legend>
|
||||||
|
<label>Channel A <select id="encChA"></select></label>
|
||||||
|
<label>Channel B <select id="encChB"></select></label>
|
||||||
|
<label>Sample rate <select id="encRate">
|
||||||
|
<option selected>11025</option><option>20800</option><option>44100</option><option>48000</option>
|
||||||
|
</select> Hz</label>
|
||||||
|
</fieldset>
|
||||||
|
<fieldset>
|
||||||
|
<legend>Impairments</legend>
|
||||||
|
<label class="chk"><input type="checkbox" id="encNoiseOn"> noise, SNR <input type="number" id="encSnr" value="12" step="1"> dB</label>
|
||||||
|
<label class="chk"><input type="checkbox" id="encClicksOn"> FM clicks <input type="number" id="encClicks" value="40" min="0" step="5"> /s</label>
|
||||||
|
<label>Clock offset <input type="number" id="encPpm" value="0" step="10"> ppm</label>
|
||||||
|
<label>Fading depth <input type="number" id="encFade" value="0" min="0" max="1" step="0.1"></label>
|
||||||
|
<label class="chk"><input type="checkbox" id="encJumpOn"> line-timing jump at line <input type="number" id="encJump" value="300" min="1" step="1"></label>
|
||||||
|
</fieldset>
|
||||||
|
</div>
|
||||||
|
<div class="enc-preview">
|
||||||
|
<canvas id="encCanvas" width="2080" height="1"></canvas>
|
||||||
|
<div id="encInfo" class="dim mono"></div>
|
||||||
|
<div id="encBar"><div id="encBarFill"></div></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<footer class="dlg-foot">
|
||||||
|
<button type="button" id="encDecode" title="Encode, load as the decoder input and fast decode">Encode & decode</button>
|
||||||
|
<button type="button" id="encRealtime" title="Encode, load and decode in realtime (with Listen)">Encode & decode realtime</button>
|
||||||
|
<button type="button" id="encSave">Download WAV</button>
|
||||||
|
</footer>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
|
<script src="wav.js"></script>
|
||||||
|
<script src="apt.js"></script>
|
||||||
|
<script src="encoder.js"></script>
|
||||||
|
<script src="app.js"></script>
|
||||||
|
<script src="encoder-ui.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
:root {
|
||||||
|
--bg: #121417;
|
||||||
|
--panel: #1b1e23;
|
||||||
|
--line: #2c3138;
|
||||||
|
--fg: #d8dde3;
|
||||||
|
--dim: #7d8691;
|
||||||
|
--accent: #4fb3ff;
|
||||||
|
--ok: #4cd07d;
|
||||||
|
--warn: #f0b429;
|
||||||
|
--bad: #ff5d5d;
|
||||||
|
}
|
||||||
|
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
|
||||||
|
html, body {
|
||||||
|
margin: 0;
|
||||||
|
height: 100%;
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--fg);
|
||||||
|
font: 13px/1.35 system-ui, -apple-system, "Segoe UI", sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
#toolbar {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 6px 18px;
|
||||||
|
align-items: center;
|
||||||
|
padding: 8px 10px;
|
||||||
|
background: var(--panel);
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.group {
|
||||||
|
display: flex;
|
||||||
|
gap: 6px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.title {
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: 0.08em;
|
||||||
|
color: var(--accent);
|
||||||
|
margin-right: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
button, .btn, select {
|
||||||
|
background: #262b32;
|
||||||
|
color: var(--fg);
|
||||||
|
border: 1px solid #3a414b;
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 4px 10px;
|
||||||
|
font: inherit;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover:not(:disabled), .btn:hover { border-color: var(--accent); }
|
||||||
|
button:disabled { opacity: 0.4; cursor: default; }
|
||||||
|
button.active { background: #1f4a6b; border-color: var(--accent); }
|
||||||
|
button.small { padding: 0 6px; font-size: 11px; }
|
||||||
|
select { padding: 4px 6px; }
|
||||||
|
|
||||||
|
.chk { display: flex; gap: 4px; align-items: center; cursor: pointer; }
|
||||||
|
#volume { width: 70px; }
|
||||||
|
|
||||||
|
.dim { color: var(--dim); }
|
||||||
|
.mono { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font-size: 12px; }
|
||||||
|
|
||||||
|
#srcName {
|
||||||
|
max-width: 260px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
#progress {
|
||||||
|
position: relative;
|
||||||
|
height: 8px;
|
||||||
|
background: #0c0e10;
|
||||||
|
cursor: pointer;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
#progressFill {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0 auto 0 0;
|
||||||
|
width: 0;
|
||||||
|
background: #24577e;
|
||||||
|
}
|
||||||
|
|
||||||
|
#progressPlay {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
bottom: 0;
|
||||||
|
width: 2px;
|
||||||
|
left: 0;
|
||||||
|
background: var(--accent);
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
main {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#viewport {
|
||||||
|
flex: 1;
|
||||||
|
overflow: auto;
|
||||||
|
position: relative;
|
||||||
|
background: #0a0b0c;
|
||||||
|
}
|
||||||
|
|
||||||
|
#viewport.dragover { outline: 2px dashed var(--accent); outline-offset: -6px; }
|
||||||
|
|
||||||
|
.hint {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
color: var(--dim);
|
||||||
|
font-size: 15px;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
#stack {
|
||||||
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
#stack canvas {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
image-rendering: pixelated;
|
||||||
|
}
|
||||||
|
|
||||||
|
#overlay {
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
top: 0;
|
||||||
|
cursor: crosshair;
|
||||||
|
}
|
||||||
|
|
||||||
|
#side {
|
||||||
|
width: 344px;
|
||||||
|
flex: none;
|
||||||
|
overflow-y: auto;
|
||||||
|
background: var(--panel);
|
||||||
|
border-left: 1px solid var(--line);
|
||||||
|
padding: 4px 12px 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#side section { margin-top: 10px; }
|
||||||
|
|
||||||
|
#side h2 {
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 600;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.08em;
|
||||||
|
color: var(--dim);
|
||||||
|
margin: 0 0 4px;
|
||||||
|
display: flex;
|
||||||
|
gap: 6px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
#side canvas {
|
||||||
|
display: block;
|
||||||
|
width: 320px;
|
||||||
|
background: #0c0e10;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
table.kv { border-collapse: collapse; width: 100%; }
|
||||||
|
table.kv th { text-align: left; font-weight: normal; color: var(--dim); width: 72px; padding: 1px 0; }
|
||||||
|
table.kv td { padding: 1px 0; font-variant-numeric: tabular-nums; }
|
||||||
|
|
||||||
|
.badge {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 0 6px;
|
||||||
|
border-radius: 3px;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 600;
|
||||||
|
background: #333;
|
||||||
|
}
|
||||||
|
.badge.lock { background: #1d5a37; color: #b9f5cf; }
|
||||||
|
.badge.search { background: #5a3a1d; color: #f5dcb9; }
|
||||||
|
|
||||||
|
.scroll {
|
||||||
|
max-height: 150px;
|
||||||
|
overflow-y: auto;
|
||||||
|
margin-top: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#frames table { border-collapse: collapse; width: 100%; font-size: 12px; }
|
||||||
|
#frames td, #frames th { padding: 1px 4px; text-align: left; font-variant-numeric: tabular-nums; }
|
||||||
|
#frames th { color: var(--dim); font-weight: normal; }
|
||||||
|
#frames tr.change td { color: var(--warn); }
|
||||||
|
#frames tr.poor td { color: var(--dim); }
|
||||||
|
#frames tr:hover td { background: #262b32; cursor: pointer; }
|
||||||
|
|
||||||
|
#markers div { display: flex; justify-content: space-between; gap: 6px; padding: 1px 0; }
|
||||||
|
#markers div:hover { background: #262b32; cursor: pointer; }
|
||||||
|
#markers .x { color: var(--bad); cursor: pointer; padding: 0 4px; }
|
||||||
|
|
||||||
|
/* encoder dialog */
|
||||||
|
dialog#encDialog {
|
||||||
|
width: min(1100px, 96vw);
|
||||||
|
max-height: 92vh;
|
||||||
|
padding: 0;
|
||||||
|
background: var(--panel);
|
||||||
|
color: var(--fg);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 6px;
|
||||||
|
}
|
||||||
|
dialog#encDialog::backdrop { background: rgba(0, 0, 0, 0.55); }
|
||||||
|
#encForm { display: flex; flex-direction: column; max-height: 92vh; }
|
||||||
|
.dlg-head, .dlg-foot {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
align-items: center;
|
||||||
|
padding: 8px 12px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
.dlg-head { justify-content: space-between; }
|
||||||
|
.dlg-foot { border-bottom: 0; border-top: 1px solid var(--line); justify-content: flex-end; }
|
||||||
|
.enc-body { display: flex; gap: 12px; padding: 10px 12px; overflow: auto; min-height: 0; }
|
||||||
|
.enc-opts { flex: 0 0 340px; display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
.enc-opts fieldset { border: 1px solid var(--line); border-radius: 4px; margin: 0; padding: 6px 10px 8px; display: flex; flex-direction: column; gap: 5px; }
|
||||||
|
.enc-opts legend { color: var(--dim); padding: 0 4px; }
|
||||||
|
.enc-opts .sub { margin-left: 22px; display: flex; flex-direction: column; gap: 4px; }
|
||||||
|
.enc-opts input[type=number] { width: 64px; background: #262b32; color: var(--fg); border: 1px solid #3a414b; border-radius: 3px; padding: 2px 4px; font: inherit; }
|
||||||
|
.enc-opts input[type=file] { max-width: 250px; font-size: 12px; }
|
||||||
|
.enc-preview { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 6px; }
|
||||||
|
#encCanvas { width: 100%; image-rendering: pixelated; background: #0d0d0f; border: 1px solid var(--line); max-height: 62vh; object-fit: contain; object-position: top; }
|
||||||
|
#encBar { height: 4px; background: #262b32; border-radius: 2px; overflow: hidden; }
|
||||||
|
#encBarFill { height: 100%; width: 0; background: var(--accent); }
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
/*
|
||||||
|
* node tools/decode.js in.wav out.pgm [lines.txt] [--envelope] [--repair[=strong]]
|
||||||
|
* offline decode; prints telemetry frames and, with --repair, repaired pixels
|
||||||
|
*/
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const APT = require(path.join(__dirname, '..', 'apt.js'));
|
||||||
|
const Wav = require(path.join(__dirname, '..', 'wav.js'));
|
||||||
|
|
||||||
|
const flags = process.argv.filter((a) => a.startsWith('--'));
|
||||||
|
process.argv = process.argv.filter((a) => !a.startsWith('--'));
|
||||||
|
const repair = flags.find((f) => f.startsWith('--repair'));
|
||||||
|
const w = Wav.Parse(fs.readFileSync(process.argv[2]));
|
||||||
|
const lines = [];
|
||||||
|
const t0 = Date.now();
|
||||||
|
const dec = new APT.Decoder(w.rate, { onLine: (l) => lines.push(l), demod: flags.includes('--envelope') ? 'envelope' : 'coherent' });
|
||||||
|
const CH = 4096;
|
||||||
|
for (let i = 0; i < w.data.length; i += CH)
|
||||||
|
dec.process(w.data.subarray(i, i + CH));
|
||||||
|
dec.flush();
|
||||||
|
console.log(`rate ${w.rate} lines ${lines.length} in ${Date.now() - t0} ms, clock ${dec.clockPpm().toFixed(1)} ppm`);
|
||||||
|
|
||||||
|
if (repair) {
|
||||||
|
const opts = repair === '--repair=strong' ? { k: 3.5, kq: 2.5, ks: 2.5 } : {};
|
||||||
|
const ok = (l) => (l && l.locked ? l : null);
|
||||||
|
const fixed = lines.map((l, i) => APT.RepairRow(l, ok(lines[i - 1]), ok(lines[i + 1]), opts));
|
||||||
|
let n = 0;
|
||||||
|
fixed.forEach((r, i) => {
|
||||||
|
if (lines[i].locked) {
|
||||||
|
n += r.count;
|
||||||
|
lines[i] = Object.assign({}, lines[i], { words: r.words });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
console.log(`repaired ${n} pixels (${(100 * n / (lines.length * 1818)).toFixed(3)}%)`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* contrast from image areas of locked lines */
|
||||||
|
const vals = [];
|
||||||
|
for (const l of lines)
|
||||||
|
if (l.sync > 0.4)
|
||||||
|
for (let k = 86; k < 995; k += 7)
|
||||||
|
vals.push(l.words[k], l.words[k + 1040]);
|
||||||
|
vals.sort((a, b) => a - b);
|
||||||
|
const lo = vals[Math.floor(vals.length * 0.005)], hi = vals[Math.floor(vals.length * 0.995)];
|
||||||
|
const out = Buffer.alloc(lines.length * 2080);
|
||||||
|
lines.forEach((l, i) => {
|
||||||
|
for (let k = 0; k < 2080; k++)
|
||||||
|
out[i * 2080 + k] = Math.max(0, Math.min(255, Math.round((l.words[k] - lo) / (hi - lo) * 255)));
|
||||||
|
});
|
||||||
|
fs.writeFileSync(process.argv[3], Buffer.concat([Buffer.from(`P5\n2080 ${lines.length}\n255\n`), out]));
|
||||||
|
if (process.argv[4]) {
|
||||||
|
let s = '';
|
||||||
|
for (const l of lines)
|
||||||
|
s += `${l.index} ${l.time.toFixed(4)} ${l.sync.toFixed(3)} ${l.locked ? 1 : 0}\n`;
|
||||||
|
fs.writeFileSync(process.argv[4], s);
|
||||||
|
}
|
||||||
|
const tel = APT.AnalyzeTelemetry(lines);
|
||||||
|
console.log('telemetry phase', tel.phase);
|
||||||
|
for (const f of tel.frames)
|
||||||
|
console.log(`frame @${f.start} q=${f.quality.toFixed(2)} A=ch${f.chA} B=ch${f.chB}`);
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
/*
|
||||||
|
* node tools/encode.js out.wav [options] - test-pattern / image encoder
|
||||||
|
* --rate 11025 output sample rate
|
||||||
|
* --lines 600 lines for the test pattern
|
||||||
|
* --pgm in.pgm 2080-wide P5 image: re-encode every word as is
|
||||||
|
* (any other width: used as both channel images, scaled to 909)
|
||||||
|
* --snr 20 add noise, dB
|
||||||
|
* --ppm 50 sample clock offset
|
||||||
|
* --jump 300 line-timing jump at line 300
|
||||||
|
* --chA 2 --chB 4 channel IDs
|
||||||
|
*/
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const APT = require(path.join(__dirname, '..', 'encoder.js'));
|
||||||
|
const Wav = require(path.join(__dirname, '..', 'wav.js'));
|
||||||
|
|
||||||
|
const args = process.argv.slice(2);
|
||||||
|
const out = args.shift();
|
||||||
|
const opt = {};
|
||||||
|
for (let i = 0; i < args.length; i += 2)
|
||||||
|
opt[args[i].replace(/^--/, '')] = args[i + 1];
|
||||||
|
|
||||||
|
function ReadPGM(file)
|
||||||
|
{
|
||||||
|
const b = fs.readFileSync(file);
|
||||||
|
const hdr = b.toString('latin1', 0, 64).match(/^P5\s+(\d+)\s+(\d+)\s+(\d+)\s/);
|
||||||
|
if (!hdr)
|
||||||
|
throw new Error('need a binary P5 PGM');
|
||||||
|
return { w: +hdr[1], h: +hdr[2], data: b.subarray(hdr[0].length) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/* gradient + grid test pattern, different in A and B */
|
||||||
|
function Pattern(i, x, ch)
|
||||||
|
{
|
||||||
|
if (ch === 0)
|
||||||
|
return ((x >> 5) + (i >> 5)) & 1 ? Math.round(x / 908 * 255) : 255 - Math.round(x / 908 * 255);
|
||||||
|
return Math.round(127.5 + 127.5 * Math.sin(x / 40 + i / 25) * Math.cos(i / 60));
|
||||||
|
}
|
||||||
|
|
||||||
|
const lineOpts = { chA: opt.chA || '2', chB: opt.chB || '4' };
|
||||||
|
let source;
|
||||||
|
if (opt.pgm) {
|
||||||
|
const img = ReadPGM(opt.pgm);
|
||||||
|
if (img.w === 2080) {
|
||||||
|
source = (i) => i < img.h ? img.data.subarray(i * 2080, (i + 1) * 2080) : null;
|
||||||
|
} else {
|
||||||
|
const row = new Uint8Array(909);
|
||||||
|
source = (i) => {
|
||||||
|
if (i >= img.h)
|
||||||
|
return null;
|
||||||
|
for (let x = 0; x < 909; x++)
|
||||||
|
row[x] = img.data[i * img.w + Math.min(img.w - 1, Math.floor(x * img.w / 909))];
|
||||||
|
return APT.BuildLine(i, row, row, lineOpts);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const n = +(opt.lines || 600);
|
||||||
|
const a = new Uint8Array(909), b = new Uint8Array(909);
|
||||||
|
source = (i) => {
|
||||||
|
if (i >= n)
|
||||||
|
return null;
|
||||||
|
for (let x = 0; x < 909; x++) {
|
||||||
|
a[x] = Pattern(i, x, 0);
|
||||||
|
b[x] = Pattern(i, x, 1);
|
||||||
|
}
|
||||||
|
return APT.BuildLine(i, a, b, lineOpts);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const rate = +(opt.rate || 11025);
|
||||||
|
const sig = APT.EncodeAll(rate, source, {
|
||||||
|
snr: opt.snr !== undefined ? +opt.snr : undefined,
|
||||||
|
ppm: +(opt.ppm || 0),
|
||||||
|
jumpAt: opt.jump !== undefined ? +opt.jump : undefined,
|
||||||
|
seed: +(opt.seed || 1),
|
||||||
|
});
|
||||||
|
fs.writeFileSync(out, Buffer.from(Wav.Build(sig, rate)));
|
||||||
|
console.log(`${out}: ${(sig.length / rate).toFixed(1)} s at ${rate} Hz`);
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
/*
|
||||||
|
* node tools/gui-smoke.js - loads the GUI scripts against a stub DOM and runs
|
||||||
|
* encoder dialog -> fast decode with repair. No browser needed; catches
|
||||||
|
* wiring and runtime errors, not layout.
|
||||||
|
*/
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs'), path = require('path'), vm = require('vm');
|
||||||
|
const dir = path.join(__dirname, '..');
|
||||||
|
const html = fs.readFileSync(path.join(dir, 'index.html'), 'utf8');
|
||||||
|
|
||||||
|
const els = {};
|
||||||
|
function El(id, tag) {
|
||||||
|
const e = {
|
||||||
|
id, tagName: (tag || 'div').toUpperCase(), style: {}, dataset: {}, children: [],
|
||||||
|
textContent: '', innerHTML: '', value: '', checked: false, disabled: false, files: [],
|
||||||
|
width: 300, height: 150, clientWidth: 1000, clientHeight: 600, scrollTop: 0,
|
||||||
|
classList: { add() {}, remove() {}, toggle() {} },
|
||||||
|
addEventListener(t, f) { (this['_' + t] = this['_' + t] || []).push(f); },
|
||||||
|
appendChild(c) { this.children.push(c); return c; },
|
||||||
|
querySelector() { return El('q'); },
|
||||||
|
getBoundingClientRect() { return { left: 0, top: 0, width: 1000, height: 600 }; },
|
||||||
|
showModal() { this.open = true; }, close() { this.open = false; },
|
||||||
|
getContext() { return Ctx(this); },
|
||||||
|
toBlob(cb) { cb({}); }, click() {},
|
||||||
|
};
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
function Ctx(c) {
|
||||||
|
return new Proxy({
|
||||||
|
createImageData: (w, h) => ({ width: w, height: h, data: new Uint8ClampedArray(w * h * 4) }),
|
||||||
|
getImageData: (x, y, w, h) => ({ data: new Uint8ClampedArray(w * h * 4).fill(128) }),
|
||||||
|
measureText: () => ({ width: 10 }),
|
||||||
|
}, { get: (t, k) => (k in t ? t[k] : () => {}) });
|
||||||
|
}
|
||||||
|
/* ids, tags and default values from the markup */
|
||||||
|
for (const m of html.matchAll(/<(\w+)([^>]*?)\sid="([^"]+)"([^>]*)>/g)) {
|
||||||
|
const e = El(m[3], m[1]);
|
||||||
|
const attrs = m[2] + m[4];
|
||||||
|
const v = attrs.match(/value="([^"]*)"/);
|
||||||
|
if (v) e.value = v[1];
|
||||||
|
if (/\schecked/.test(attrs)) e.checked = true;
|
||||||
|
els[m[3]] = e;
|
||||||
|
}
|
||||||
|
/* select defaults: first or selected option */
|
||||||
|
for (const m of html.matchAll(/<select id="([^"]+)"[^>]*>([\s\S]*?)<\/select>/g)) {
|
||||||
|
const opts = [...m[2].matchAll(/<option(?: value="([^"]*)")?([^>]*)>([^<]*)/g)];
|
||||||
|
const sel = opts.find((o) => /selected/.test(o[2])) || opts[0];
|
||||||
|
if (sel) els[m[1]].value = sel[1] !== undefined ? sel[1] : sel[3];
|
||||||
|
}
|
||||||
|
const radios = [...html.matchAll(/<input type="radio" name="encSrc" value="(\w+)"( checked)?/g)].map((m) => ({ value: m[1], checked: !!m[2], addEventListener() {} }));
|
||||||
|
|
||||||
|
const timers = [];
|
||||||
|
const ctx = {
|
||||||
|
console, Math, Date, JSON, Promise, Float32Array, Float64Array, Uint8Array, Uint8ClampedArray, Int16Array, ArrayBuffer, DataView, Map, Proxy, Blob: class { constructor(p) { this.parts = p; } },
|
||||||
|
URL: { createObjectURL: () => 'blob:x', revokeObjectURL() {} },
|
||||||
|
performance: { now: () => Date.now() },
|
||||||
|
setTimeout: (f) => timers.push(f), setInterval: () => 0, requestAnimationFrame: (f) => { ctx._raf = f; },
|
||||||
|
navigator: { mediaDevices: { enumerateDevices: async () => [] } },
|
||||||
|
alert: (m) => { throw new Error('alert: ' + m); },
|
||||||
|
document: {
|
||||||
|
getElementById: (id) => els[id] || (els[id] = El(id)),
|
||||||
|
createElement: (t) => El('new', t),
|
||||||
|
querySelector: (q) => {
|
||||||
|
const m = q.match(/value=(\w+)/);
|
||||||
|
return m ? radios.find((r) => r.value === m[1]) : radios.find((r) => r.checked);
|
||||||
|
},
|
||||||
|
querySelectorAll: () => radios,
|
||||||
|
},
|
||||||
|
addEventListener() {},
|
||||||
|
};
|
||||||
|
ctx.window = ctx;
|
||||||
|
ctx.globalThis = ctx;
|
||||||
|
vm.createContext(ctx);
|
||||||
|
for (const f of ['wav.js', 'apt.js', 'encoder.js', 'app.js', 'encoder-ui.js'])
|
||||||
|
vm.runInContext(fs.readFileSync(path.join(dir, f), 'utf8'), ctx, { filename: f });
|
||||||
|
|
||||||
|
const drain = async (max) => {
|
||||||
|
for (let i = 0; i < max && timers.length; i++) {
|
||||||
|
timers.shift()();
|
||||||
|
if (i % 20 === 0) { ctx._raf && ctx._raf(); await null; }
|
||||||
|
}
|
||||||
|
ctx._raf && ctx._raf();
|
||||||
|
};
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
/* encoder: pattern, 120 lines, 11025 Hz, noise + clicks + jump */
|
||||||
|
els.encLines.value = '120';
|
||||||
|
els.encRate.value = '11025';
|
||||||
|
els.encNoiseOn.checked = true; els.encSnr.value = '15';
|
||||||
|
els.encClicksOn.checked = true; els.encClicks.value = '60';
|
||||||
|
els.encJumpOn.checked = true; els.encJump.value = '70';
|
||||||
|
els.btnEncoder.onclick();
|
||||||
|
console.log('preview:', els.encInfo.textContent, '| canvas', els.encCanvas.width, 'x', els.encCanvas.height);
|
||||||
|
els.encDecode.onclick();
|
||||||
|
for (let k = 0; k < 50; k++) await drain(5000);
|
||||||
|
console.log('source:', els.srcName.textContent, '| status:', els.stMode.textContent, '| lines', els.stLines.textContent,
|
||||||
|
'| sync', els.stSync.textContent, '| clock', els.stClock.textContent, '| repaired', els.stRepair.textContent);
|
||||||
|
/* toggles */
|
||||||
|
els.repair.value = 'strong'; els.repair.onchange({ target: els.repair });
|
||||||
|
els.showRepairs.checked = true; els.showRepairs.onchange({ target: els.showRepairs });
|
||||||
|
ctx._raf();
|
||||||
|
console.log('strong repaired:', els.stRepair.textContent);
|
||||||
|
els.btnSave.onclick();
|
||||||
|
els.repair.value = 'off'; els.repair.onchange({ target: els.repair }); ctx._raf();
|
||||||
|
console.log('repair off:', els.stRepair.textContent);
|
||||||
|
/* save path */
|
||||||
|
els.encSave.onclick();
|
||||||
|
for (let k = 0; k < 20; k++) await drain(5000);
|
||||||
|
console.log('frames table has rows:', /<tr/.test(els.frames.innerHTML));
|
||||||
|
console.log('OK');
|
||||||
|
})().catch((e) => { console.error('FAIL', e); process.exit(1); });
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
/*
|
||||||
|
* node tools/survey.js file.wav [...] - per-recording quality figures without
|
||||||
|
* a reference image: lock %, median sync, and noise = mean within-line std of
|
||||||
|
* the Space A / Space B words (flat in a clean signal) over the sync contrast.
|
||||||
|
*/
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const APT = require(path.join(__dirname, '..', 'apt.js'));
|
||||||
|
const Wav = require(path.join(__dirname, '..', 'wav.js'));
|
||||||
|
|
||||||
|
function Std(w, a, b)
|
||||||
|
{
|
||||||
|
let s = 0, s2 = 0;
|
||||||
|
for (let k = a; k < b; k++) { s += w[k]; s2 += w[k] * w[k]; }
|
||||||
|
const n = b - a, m = s / n;
|
||||||
|
return Math.sqrt(Math.max(0, s2 / n - m * m));
|
||||||
|
}
|
||||||
|
|
||||||
|
function Survey(file, opts)
|
||||||
|
{
|
||||||
|
const w = Wav.Parse(fs.readFileSync(file));
|
||||||
|
const lines = [];
|
||||||
|
const dec = new APT.Decoder(w.rate, Object.assign({ onLine: (l) => lines.push(l) }, opts || {}));
|
||||||
|
for (let i = 0; i < w.data.length; i += 8192)
|
||||||
|
dec.process(w.data.subarray(i, i + 8192));
|
||||||
|
dec.flush();
|
||||||
|
let locked = 0, nz = [], sy = [];
|
||||||
|
for (const l of lines) {
|
||||||
|
sy.push(l.sync);
|
||||||
|
if (!l.locked || l.sync < 0.3)
|
||||||
|
continue;
|
||||||
|
locked++;
|
||||||
|
const c = l.hi - l.lo;
|
||||||
|
if (c <= 0)
|
||||||
|
continue;
|
||||||
|
nz.push(0.5 * (Std(l.words, 42, 84) + Std(l.words, 1082, 1124)) / c);
|
||||||
|
}
|
||||||
|
const med = (a) => { if (!a.length) return NaN; a.sort((x, y) => x - y); return a[a.length >> 1]; };
|
||||||
|
return { file: path.basename(file), rate: w.rate, lines: lines.length,
|
||||||
|
lock: locked / Math.max(1, lines.length), sync: med(sy), noise: med(nz) };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = Survey;
|
||||||
|
if (require.main === module)
|
||||||
|
for (const f of process.argv.slice(2)) {
|
||||||
|
try {
|
||||||
|
const r = Survey(f);
|
||||||
|
console.log(`${r.noise.toFixed(4)}\t${r.sync.toFixed(3)}\t${(r.lock * 100).toFixed(0)}%\t${r.lines}\t${r.rate}\t${r.file}`);
|
||||||
|
} catch (e) { console.log(`ERR\t${path.basename(f)}\t${e.message}`); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
/*
|
||||||
|
* wav.js - minimal RIFF/WAVE reader and writer (PCM 8/16/24/32, float 32/64,
|
||||||
|
* WAVE_FORMAT_EXTENSIBLE). Parse() returns { rate, channels, data } with data
|
||||||
|
* the first channel as Float32Array in -1..1, so the decoder sees the file's
|
||||||
|
* native rate instead of a browser-resampled copy.
|
||||||
|
*/
|
||||||
|
(function (root) {
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
function Parse(buffer)
|
||||||
|
{
|
||||||
|
const u8 = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
|
||||||
|
const dv = new DataView(u8.buffer, u8.byteOffset, u8.byteLength);
|
||||||
|
const tag = (o) => String.fromCharCode(u8[o], u8[o + 1], u8[o + 2], u8[o + 3]);
|
||||||
|
if (u8.length < 12 || tag(0) !== 'RIFF' || tag(8) !== 'WAVE')
|
||||||
|
throw new Error('not a RIFF/WAVE file');
|
||||||
|
|
||||||
|
let fmt = null, dataOff = -1, dataLen = 0;
|
||||||
|
let o = 12;
|
||||||
|
while (o + 8 <= u8.length) {
|
||||||
|
const id = tag(o);
|
||||||
|
let len = dv.getUint32(o + 4, true);
|
||||||
|
const body = o + 8;
|
||||||
|
if (id === 'fmt ') {
|
||||||
|
fmt = {
|
||||||
|
format: dv.getUint16(body, true),
|
||||||
|
channels: dv.getUint16(body + 2, true),
|
||||||
|
rate: dv.getUint32(body + 4, true),
|
||||||
|
align: dv.getUint16(body + 12, true),
|
||||||
|
bits: dv.getUint16(body + 14, true),
|
||||||
|
};
|
||||||
|
if (fmt.format === 0xfffe && len >= 26)
|
||||||
|
fmt.format = dv.getUint16(body + 24, true);
|
||||||
|
} else if (id === 'data') {
|
||||||
|
dataOff = body;
|
||||||
|
/* streamed / truncated recordings: clamp to the file */
|
||||||
|
if (len === 0 || len === 0xffffffff || body + len > u8.length)
|
||||||
|
len = u8.length - body;
|
||||||
|
dataLen = len;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
o = body + len + (len & 1);
|
||||||
|
}
|
||||||
|
if (!fmt || dataOff < 0)
|
||||||
|
throw new Error('WAVE file without fmt/data chunk');
|
||||||
|
|
||||||
|
const bps = fmt.bits >> 3;
|
||||||
|
const align = fmt.align || bps * fmt.channels;
|
||||||
|
const n = Math.floor(dataLen / align);
|
||||||
|
const data = new Float32Array(n);
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const p = dataOff + i * align;
|
||||||
|
let v;
|
||||||
|
if (fmt.format === 3)
|
||||||
|
v = bps === 8 ? dv.getFloat64(p, true) : dv.getFloat32(p, true);
|
||||||
|
else if (bps === 1)
|
||||||
|
v = (u8[p] - 128) / 128;
|
||||||
|
else if (bps === 2)
|
||||||
|
v = dv.getInt16(p, true) / 32768;
|
||||||
|
else if (bps === 3)
|
||||||
|
v = ((u8[p] | (u8[p + 1] << 8) | (u8[p + 2] << 16)) << 8 >> 8) / 8388608;
|
||||||
|
else if (bps === 4)
|
||||||
|
v = dv.getInt32(p, true) / 2147483648;
|
||||||
|
else
|
||||||
|
throw new Error('unsupported sample size ' + fmt.bits);
|
||||||
|
data[i] = v;
|
||||||
|
}
|
||||||
|
return { rate: fmt.rate, channels: fmt.channels, data: data };
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Mono 16-bit PCM WAV from Float32Array samples in -1..1 */
|
||||||
|
function Build(samples, rate)
|
||||||
|
{
|
||||||
|
const n = samples.length;
|
||||||
|
const out = new Uint8Array(44 + n * 2);
|
||||||
|
const dv = new DataView(out.buffer);
|
||||||
|
const put = (o, s) => { for (let i = 0; i < 4; i++) out[o + i] = s.charCodeAt(i); };
|
||||||
|
put(0, 'RIFF');
|
||||||
|
dv.setUint32(4, 36 + n * 2, true);
|
||||||
|
put(8, 'WAVE');
|
||||||
|
put(12, 'fmt ');
|
||||||
|
dv.setUint32(16, 16, true);
|
||||||
|
dv.setUint16(20, 1, true);
|
||||||
|
dv.setUint16(22, 1, true);
|
||||||
|
dv.setUint32(24, rate, true);
|
||||||
|
dv.setUint32(28, rate * 2, true);
|
||||||
|
dv.setUint16(32, 2, true);
|
||||||
|
dv.setUint16(34, 16, true);
|
||||||
|
put(36, 'data');
|
||||||
|
dv.setUint32(40, n * 2, true);
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const v = Math.max(-1, Math.min(1, samples[i]));
|
||||||
|
dv.setInt16(44 + i * 2, Math.round(v * 32767), true);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const Wav = { Parse, Build };
|
||||||
|
if (typeof module !== 'undefined' && module.exports)
|
||||||
|
module.exports = Wav;
|
||||||
|
else
|
||||||
|
root.Wav = Wav;
|
||||||
|
})(typeof window !== 'undefined' ? window : globalThis);
|
||||||
Reference in new issue
Block a user