From 4bc15bb585b618624e096890bda42a06ffbd16d9 Mon Sep 17 00:00:00 2001 From: zefie Date: Thu, 3 Dec 2026 20:58:22 -0500 Subject: [PATCH] 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 --- README.md | 98 ++++ app.js | 1140 ++++++++++++++++++++++++++++++++++++++++++++ apt.js | 748 +++++++++++++++++++++++++++++ encoder-ui.js | 271 +++++++++++ encoder.js | 291 +++++++++++ index.html | 179 +++++++ style.css | 243 ++++++++++ tools/decode.js | 61 +++ tools/encode.js | 79 +++ tools/gui-smoke.js | 111 +++++ tools/survey.js | 51 ++ wav.js | 103 ++++ 12 files changed, 3375 insertions(+) create mode 100644 README.md create mode 100644 app.js create mode 100644 apt.js create mode 100644 encoder-ui.js create mode 100644 encoder.js create mode 100644 index.html create mode 100644 style.css create mode 100644 tools/decode.js create mode 100644 tools/encode.js create mode 100644 tools/gui-smoke.js create mode 100644 tools/survey.js create mode 100644 wav.js diff --git a/README.md b/README.md new file mode 100644 index 0000000..590f862 --- /dev/null +++ b/README.md @@ -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. diff --git a/app.js b/app.js new file mode 100644 index 0000000..c71820b --- /dev/null +++ b/app.js @@ -0,0 +1,1140 @@ +/* + * app.js - decoder GUI: file fast / realtime decode (with listening), live + * audio input, image view, telemetry, spectrum, markers. + */ +(function () { + 'use strict'; + + const $ = (id) => document.getElementById(id); + const W = APT.LINE_WORDS; + + const VIEWS = { + full: [[0, W]], + AB: [[86, 909], [1126, 909]], + A: [[86, 909]], + B: [[1126, 909]], + }; + + const state = { + src: null, /* { name, rate, data, duration, audioBuffer } */ + mode: 'idle', /* idle | fast | realtime | paused | live | done */ + dec: null, + offset: 0, /* seconds of the first sample fed to dec */ + fedPos: 0, /* next sample of src.data to feed */ + lines: [], + view: 'full', + contrast: 'telemetry', + markers: [], + levels: null, /* { lo: Float32Array, hi: Float32Array } per line */ + tel: { frames: [] }, + telAt: 0, + autoAt: 0, + ring: new Float32Array(4096), + ringPos: 0, + ringRate: 11025, + demod: 'coherent', + repair: 'normal', /* off | normal | strong */ + showRepairs: false, + rep: [], /* per line: RepairRow result, once its next line exists */ + repCount: 0, + }; + + const REPAIR_OPTS = { + normal: {}, + strong: { k: 3.5, kq: 2.5, ks: 2.5 }, + }; + + const audio = { + ctx: null, + gain: null, + source: null, + speed: 1, + t0: 0, + pos0: 0, + live: null, /* { stream, node, proc, queue } */ + }; + + /* ---------------------------------------------------------------- */ + /* image rendering */ + + const img = { + canvas: $('image'), + overlay: $('overlay'), + ctx: null, + octx: null, + data: null, /* ImageData, width x cap */ + width: W, + cap: 0, + rendered: 0, + dirtyFrom: -1, + }; + img.ctx = img.canvas.getContext('2d'); + img.octx = img.overlay.getContext('2d'); + + function ViewWidth() + { + return VIEWS[state.view].reduce((s, r) => s + r[1], 0); + } + + /* Map a view column to a line word, or -1 */ + function ColumnToWord(col) + { + for (const [start, len] of VIEWS[state.view]) { + if (col < len) + return start + col; + col -= len; + } + return -1; + } + + function AllocImage(rows) + { + const cap = Math.max(256, Math.ceil((rows + 1) / 256) * 256); + img.width = ViewWidth(); + img.cap = cap; + img.canvas.width = img.overlay.width = img.width; + img.canvas.height = img.overlay.height = cap; + img.data = img.ctx.createImageData(img.width, cap); + const d = img.data.data; + for (let i = 0; i < d.length; i += 4) { + d[i] = d[i + 1] = 13; + d[i + 2] = 15; + d[i + 3] = 255; + } + img.rendered = 0; + img.dirtyFrom = 0; + ApplyZoom(); + DrawOverlay(); + } + + function Rerender() + { + img.rendered = 0; + img.dirtyFrom = 0; + } + + /* + * Words to show for line r: the decoded words, or the impulse-repaired + * copy. Repair needs the next line, so the newest line is shown raw and + * redrawn when its successor arrives. The decoded lines are never changed. + */ + function RowRepair(r) + { + if (state.repair === 'off') + return null; + if (state.rep[r]) + return state.rep[r]; + const L = state.lines; + const ok = (l) => l && l.locked; + if (!ok(L[r]) || r + 1 >= L.length) + return null; + const res = APT.RepairRow(L[r], ok(L[r - 1]) ? L[r - 1] : null, ok(L[r + 1]) ? L[r + 1] : null, + REPAIR_OPTS[state.repair]); + state.rep[r] = res; + state.repCount += res.count; + return res; + } + + function ResetRepairs() + { + state.rep = []; + state.repCount = 0; + Rerender(); + } + + function LevelsFor(i) + { + const lv = state.levels; + if (lv && i < lv.lo.length && lv.hi[i] > lv.lo[i]) + return [lv.lo[i], lv.hi[i]]; + return [0, 1]; + } + + function RenderRows(from, to, target, tint) + { + const d = (target || img.data).data, w = img.width, spans = VIEWS[state.view]; + if (tint === undefined) + tint = state.showRepairs; + for (let r = from; r < to; r++) { + const rp = RowRepair(r); + const words = rp ? rp.words : state.lines[r].words; + const mask = rp && tint && rp.count ? rp.mask : null; + const [lo, hi] = LevelsFor(r); + const k = 255 / (hi - lo); + let p = r * w * 4; + for (const [start, len] of spans) { + for (let c = 0; c < len; c++) { + let v = (words[start + c] - lo) * k; + v = v < 0 ? 0 : v > 255 ? 255 : v; + if (mask && mask[start + c]) { + d[p] = 255; + d[p + 1] = d[p + 2] = v * 0.3; + } else { + d[p] = d[p + 1] = d[p + 2] = v; + } + p += 4; + } + } + } + } + + function FlushImage() + { + const rows = state.lines.length; + if (rows === 0) + return; + if (rows > img.cap || img.width !== ViewWidth()) + AllocImage(rows); + if (img.rendered < rows) { + RenderRows(img.rendered, rows); + if (img.dirtyFrom < 0 || img.dirtyFrom > img.rendered) + img.dirtyFrom = img.rendered; + /* the newest line is redrawn once its repair can be done */ + img.rendered = state.repair !== 'off' && !state.rep[rows - 1] && state.mode !== 'done' && state.mode !== 'idle' ? rows - 1 : rows; + } + if (img.dirtyFrom >= 0) { + img.ctx.putImageData(img.data, 0, 0, 0, img.dirtyFrom, img.width, rows - img.dirtyFrom); + img.dirtyFrom = -1; + if ($('follow').checked && state.mode !== 'idle' && state.mode !== 'done') + ScrollToRow(rows); + } + } + + function RowToY(row) + { + return row * img.canvas.clientHeight / Math.max(1, img.cap); + } + + function ScrollToRow(row) + { + const vp = $('viewport'); + const y = RowToY(row); + const top = Math.max(0, y - vp.clientHeight + 24); + if (Math.abs(vp.scrollTop - top) > 2) + vp.scrollTop = top; + } + + function ApplyZoom() + { + const z = $('zoom').value; + const st = $('stack'); + if (z === 'fit') + st.style.width = '100%'; + else + st.style.width = (img.width * parseFloat(z)) + 'px'; + } + + function DrawOverlay() + { + const o = img.octx; + o.clearRect(0, 0, img.overlay.width, img.overlay.height); + const lw = Math.max(1, img.width / Math.max(1, img.overlay.clientWidth)); + for (const m of state.markers) { + o.fillStyle = 'rgba(255,80,80,0.85)'; + o.fillRect(0, m.line, img.width, lw); + o.font = (12 * lw) + 'px sans-serif'; + o.fillText(m.label, 4 * lw, m.line - 3 * lw); + } + } + + /* ---------------------------------------------------------------- */ + /* levels */ + + function UpdateLevels(force) + { + const n = state.lines.length; + if (n === 0) + return; + const lo = new Float32Array(n), hi = new Float32Array(n); + const mode = state.contrast; + let ok = false; + + if (mode === 'telemetry') { + const frames = state.tel.frames.filter((f) => f.quality > 0.9 && !isNaN(f.a[8])); + if (frames.length) { + /* wedge 8 = white, wedge 9 = black; per frame, interpolated */ + const pts = frames.map((f) => ({ + c: f.start + APT.FRAME_LINES / 2, + lo: 0.5 * (f.a[8] + f.b[8]), + hi: 0.5 * (f.a[7] + f.b[7]), + })); + let j = 0; + for (let i = 0; i < n; i++) { + while (j < pts.length - 1 && pts[j + 1].c <= i) + j++; + const a = pts[j], b = pts[Math.min(j + 1, pts.length - 1)]; + let t = b.c === a.c ? 0 : (i - a.c) / (b.c - a.c); + t = Math.max(0, Math.min(1, t)); + lo[i] = a.lo + (b.lo - a.lo) * t; + hi[i] = a.hi + (b.hi - a.hi) * t; + } + ok = true; + } + } + if (mode === 'sync') { + /* sync pulse plateaus, smoothed over a few lines */ + let el = state.lines[0].lo, eh = state.lines[0].hi; + for (let i = 0; i < n; i++) { + const l = state.lines[i]; + if (l.sync > 0.5) { + el += 0.2 * (l.lo - el); + eh += 0.2 * (l.hi - eh); + } + lo[i] = el; + hi[i] = eh; + } + ok = true; + } + if (!ok) { + /* auto: percentiles of the image areas of synced lines */ + const vals = []; + const step = Math.max(1, Math.floor(n / 600)); + for (let i = 0; i < n; i += step) { + const l = state.lines[i]; + if (l.sync < 0.4 && n > 20) + continue; + for (let k = 90; k < 990; k += 9) + vals.push(l.words[k], l.words[k + 1040]); + } + if (vals.length < 10) + for (let k = 0; k < W; k += 5) + vals.push(state.lines[n - 1].words[k]); + vals.sort((a, b) => a - b); + const a = vals[Math.floor(vals.length * 0.005)]; + const b = vals[Math.min(vals.length - 1, Math.floor(vals.length * 0.995))]; + lo.fill(a); + hi.fill(b > a ? b : a + 1e-3); + } + + /* rerender only if something visible moved */ + const old = state.levels; + let changed = force || !old || old.lo.length === 0; + if (!changed) { + const m = Math.min(old.lo.length, n); + for (let i = 0; i < m; i += 7) { + const span = Math.max(1e-6, hi[i] - lo[i]); + if (Math.abs(old.lo[i] - lo[i]) / span > 0.01 || Math.abs(old.hi[i] - hi[i]) / span > 0.01) { + changed = true; + break; + } + } + } + state.levels = { lo, hi }; + if (changed) + Rerender(); + } + + function Analyze(force) + { + const n = state.lines.length; + const every = state.mode === 'fast' ? 256 : 32; + if (!force && n - state.telAt < every) + return; + state.telAt = n; + state.tel = APT.AnalyzeTelemetry(state.lines); + UpdateLevels(force); + DrawFrames(); + } + + /* ---------------------------------------------------------------- */ + /* decoder plumbing */ + + function NewDecoder(rate, offset) + { + state.dec = new APT.Decoder(rate, { + demod: state.demod, + onLine: (l) => { + l.time += offset; + state.lines.push(l); + /* new lines use the last known levels until the next analysis */ + const lv = state.levels; + if (lv && lv.lo.length) { + const lo = new Float32Array(state.lines.length), hi = new Float32Array(state.lines.length); + lo.set(lv.lo); + hi.set(lv.hi); + lo[state.lines.length - 1] = lv.lo[lv.lo.length - 1]; + hi[state.lines.length - 1] = lv.hi[lv.hi.length - 1]; + state.levels = { lo, hi }; + } + }, + }); + state.offset = offset; + state.ringRate = rate; + } + + function ResetImage() + { + state.lines = []; + state.rep = []; + state.repCount = 0; + state.levels = null; + state.tel = { frames: [] }; + state.telAt = 0; + img.rendered = 0; + AllocImage(0); + $('drop').style.display = 'none'; + DrawFrames(); + } + + function Feed(x) + { + state.dec.process(x); + const r = state.ring, n = r.length; + if (x.length >= n) { + r.set(x.subarray(x.length - n)); + state.ringPos = 0; + } else { + for (let i = 0; i < x.length; i++) { + r[state.ringPos] = x[i]; + state.ringPos = (state.ringPos + 1) % n; + } + } + if (state.lines.length === 1 && !state.levels) + UpdateLevels(true); + Analyze(false); + } + + /* ---------------------------------------------------------------- */ + /* file loading */ + + async function LoadFile(file) + { + Stop(); + const buf = await file.arrayBuffer(); + let src; + try { + const w = Wav.Parse(buf); + src = { rate: w.rate, data: w.data }; + } catch (e) { + /* not a WAV we read: let the browser decode it (resampled) */ + const ctx = EnsureAudio(); + const ab = await ctx.decodeAudioData(buf.slice(0)); + src = { rate: ab.sampleRate, data: ab.getChannelData(0).slice(0) }; + } + src.name = file.name; + LoadSource(src); + } + + /* Use { name, rate, data: Float32Array } as the input (file or encoder) */ + function LoadSource(src) + { + Stop(); + src.duration = src.data.length / src.rate; + src.audioBuffer = null; + state.src = src; + $('srcName').textContent = src.name; + $('srcName').classList.remove('dim'); + $('stRate').textContent = `${src.rate} Hz, ${FormatTime(src.duration)}`; + if (src.rate < 9600) + $('stRate').textContent += ' (too low for APT)'; + SetMode('idle'); + ResetImage(); + $('progressFill').style.width = '0'; + } + + /* ---------------------------------------------------------------- */ + /* fast decode */ + + function StartFast() + { + if (!state.src) + return; + Stop(); + ResetImage(); + NewDecoder(state.src.rate, 0); + state.fedPos = 0; + SetMode('fast'); + FastTick(); + } + + function FastTick() + { + if (state.mode !== 'fast') + return; + const data = state.src.data; + const t = performance.now(); + const chunk = 8192; + while (performance.now() - t < 30 && state.fedPos < data.length) { + const n = Math.min(chunk, data.length - state.fedPos); + Feed(data.subarray(state.fedPos, state.fedPos + n)); + state.fedPos += n; + } + if (state.fedPos >= data.length) { + state.dec.flush(); + Finish(); + return; + } + setTimeout(FastTick, 0); + } + + function Finish() + { + Analyze(true); + Rerender(); + SetMode('done'); + StopAudio(); + } + + /* ---------------------------------------------------------------- */ + /* realtime decode with listening */ + + function EnsureAudio() + { + if (!audio.ctx) { + audio.ctx = new (window.AudioContext || window.webkitAudioContext)(); + audio.gain = audio.ctx.createGain(); + audio.gain.connect(audio.ctx.destination); + ApplyVolume(); + } + if (audio.ctx.state === 'suspended') + audio.ctx.resume(); + return audio.ctx; + } + + function ApplyVolume() + { + if (audio.gain) + audio.gain.gain.value = $('listen').checked ? parseFloat($('volume').value) : 0; + } + + function StartRealtime(posSec) + { + if (!state.src) + return; + Stop(); + ResetImage(); + posSec = Math.max(0, Math.min(posSec || 0, state.src.duration - 1)); + state.fedPos = Math.floor(posSec * state.src.rate); + NewDecoder(state.src.rate, state.fedPos / state.src.rate); + SetMode('realtime'); + PlayFrom(state.fedPos); + } + + function PlayFrom(samplePos) + { + const ctx = EnsureAudio(); + const src = state.src; + if (!src.audioBuffer) { + src.audioBuffer = ctx.createBuffer(1, src.data.length, src.rate); + src.audioBuffer.copyToChannel(src.data, 0); + } + StopSource(); + const node = ctx.createBufferSource(); + node.buffer = src.audioBuffer; + node.playbackRate.value = audio.speed; + node.connect(audio.gain); + const pos = samplePos / src.rate; + node.start(0, pos); + audio.source = node; + audio.t0 = ctx.currentTime; + audio.pos0 = pos; + } + + function StopSource() + { + if (audio.source) { + try { + audio.source.stop(); + } catch (e) { + /* already stopped */ + } + audio.source.disconnect(); + audio.source = null; + } + } + + function PlayPosition() + { + return audio.pos0 + (audio.ctx.currentTime - audio.t0) * audio.speed; + } + + function RealtimeTick() + { + if (state.mode !== 'realtime') + return; + const src = state.src; + const target = Math.min(src.data.length, Math.floor(PlayPosition() * src.rate)); + if (target > state.fedPos) { + Feed(src.data.subarray(state.fedPos, target)); + state.fedPos = target; + } + if (state.fedPos >= src.data.length) { + state.dec.flush(); + Finish(); + } + } + + function TogglePause() + { + if (state.mode === 'realtime') { + StopSource(); + SetMode('paused'); + } else if (state.mode === 'paused') { + SetMode('realtime'); + PlayFrom(state.fedPos); + } + } + + function SetSpeed(v) + { + audio.speed = v; + if (state.mode === 'realtime') + PlayFrom(state.fedPos); + } + + /* ---------------------------------------------------------------- */ + /* live input */ + + async function StartLive() + { + Stop(); + const ctx = EnsureAudio(); + const devId = $('device').value; + let stream; + try { + stream = await navigator.mediaDevices.getUserMedia({ + audio: { + deviceId: devId ? { exact: devId } : undefined, + echoCancellation: false, + noiseSuppression: false, + autoGainControl: false, + channelCount: 1, + }, + }); + } catch (e) { + alert('Could not open audio input: ' + e.message + + '\n\nBrowsers allow audio input only from a secure page: serve this folder ' + + '(python3 -m http.server) and open http://localhost:8000/'); + return; + } + ListDevices(); + const node = ctx.createMediaStreamSource(stream); + const proc = ctx.createScriptProcessor(4096, 1, 1); + const queue = []; + proc.onaudioprocess = (e) => { + queue.push(new Float32Array(e.inputBuffer.getChannelData(0))); + e.outputBuffer.getChannelData(0).fill(0); + }; + node.connect(proc); + proc.connect(ctx.destination); + node.connect(audio.gain); /* monitor, follows Listen */ + audio.live = { stream, node, proc, queue }; + + ResetImage(); + NewDecoder(ctx.sampleRate, 0); + $('srcName').textContent = 'live input'; + $('stRate').textContent = `${ctx.sampleRate} Hz live`; + SetMode('live'); + } + + function LiveTick() + { + if (state.mode !== 'live' || !audio.live) + return; + const q = audio.live.queue; + while (q.length) + Feed(q.shift()); + } + + function StopLive() + { + const l = audio.live; + if (!l) + return; + l.proc.disconnect(); + l.node.disconnect(); + l.stream.getTracks().forEach((t) => t.stop()); + audio.live = null; + } + + async function ListDevices() + { + if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) + return; + const devs = await navigator.mediaDevices.enumerateDevices(); + const sel = $('device'); + const cur = sel.value; + sel.innerHTML = ''; + for (const d of devs) { + if (d.kind !== 'audioinput' || !d.deviceId || d.deviceId === 'default') + continue; + const o = document.createElement('option'); + o.value = d.deviceId; + o.textContent = d.label || ('input ' + sel.length); + sel.appendChild(o); + } + sel.value = cur; + } + + /* ---------------------------------------------------------------- */ + /* stop / modes */ + + function StopAudio() + { + StopSource(); + StopLive(); + } + + function Stop() + { + if (state.mode === 'live' || state.mode === 'realtime' || state.mode === 'paused' || state.mode === 'fast') { + if (state.dec) + state.dec.flush(); + StopAudio(); + Analyze(true); + SetMode(state.lines.length ? 'done' : 'idle'); + } + } + + function SetMode(m) + { + state.mode = m; + const busy = m === 'fast' || m === 'realtime' || m === 'paused' || m === 'live'; + $('btnFast').disabled = !state.src || m === 'live'; + $('btnRealtime').disabled = !state.src || m === 'live'; + $('btnPause').disabled = !(m === 'realtime' || m === 'paused'); + $('btnPause').textContent = m === 'paused' ? 'Resume' : 'Pause'; + $('btnStop').disabled = !busy; + $('btnLive').classList.toggle('active', m === 'live'); + $('btnFast').classList.toggle('active', m === 'fast'); + $('btnRealtime').classList.toggle('active', m === 'realtime' || m === 'paused'); + $('btnSave').disabled = state.lines.length === 0 && !busy; + $('progressPlay').style.display = (m === 'realtime' || m === 'paused') ? 'block' : 'none'; + $('stMode').textContent = { idle: 'idle', fast: 'fast decode', realtime: 'realtime', paused: 'paused', live: 'live input', done: 'done' }[m]; + } + + /* ---------------------------------------------------------------- */ + /* side panels */ + + function FormatTime(s) + { + if (!isFinite(s)) + return '-'; + const m = Math.floor(s / 60); + const r = s - m * 60; + return `${m}:${r < 10 ? '0' : ''}${r.toFixed(3)}`; + } + + function UpdateStatus() + { + const n = state.lines.length; + $('stLines').textContent = n; + const dec = state.dec; + if (dec) { + const last = state.lines[n - 1]; + const lk = $('stLock'); + lk.textContent = dec.locked ? 'LOCK' : 'SEARCH'; + lk.className = 'badge ' + (dec.locked ? 'lock' : 'search'); + $('stSync').textContent = last ? (last.sync * 100).toFixed(0) + '%' : '-'; + $('stClock').textContent = (dec.clockPpm() >= 0 ? '+' : '') + dec.clockPpm().toFixed(0) + ' ppm'; + const px = state.lines.length * 1818; + $('stRepair').textContent = state.repair === 'off' ? 'off' : + !dec.coherent ? 'needs coherent demod' : + `${state.repCount} px (${px ? (100 * state.repCount / px).toFixed(2) : '0.00'}%)`; + } + if (state.src && state.mode !== 'live') { + let pos = state.fedPos / state.src.rate; + if (state.mode === 'realtime') + pos = Math.min(state.src.duration, PlayPosition()); + $('stPos').textContent = `${FormatTime(pos)} / ${FormatTime(state.src.duration)}`; + const pct = 100 * pos / state.src.duration; + $('progressFill').style.width = (100 * state.fedPos / state.src.data.length) + '%'; + $('progressPlay').style.left = pct + '%'; + } else if (state.mode === 'live' && n) { + $('stPos').textContent = FormatTime(state.lines[n - 1].time); + } + $('btnSave').disabled = n === 0; + } + + function FFT(re, im) + { + const n = re.length; + for (let i = 1, j = 0; i < n; i++) { + let bit = n >> 1; + for (; j & bit; bit >>= 1) + j ^= bit; + j ^= bit; + if (i < j) { + [re[i], re[j]] = [re[j], re[i]]; + [im[i], im[j]] = [im[j], im[i]]; + } + } + for (let len = 2; len <= n; len <<= 1) { + const ang = -2 * Math.PI / len; + const wr = Math.cos(ang), wi = Math.sin(ang); + for (let i = 0; i < n; i += len) { + let cr = 1, ci = 0; + for (let k = 0; k < len / 2; k++) { + const a = i + k, b = a + len / 2; + const tr = re[b] * cr - im[b] * ci, ti = re[b] * ci + im[b] * cr; + re[b] = re[a] - tr; + im[b] = im[a] - ti; + re[a] += tr; + im[a] += ti; + const t = cr * wr - ci * wi; + ci = cr * wi + ci * wr; + cr = t; + } + } + } + } + + function DrawSpectrum() + { + const c = $('spectrum'), g = c.getContext('2d'); + const N = 4096, re = new Float32Array(N), im = new Float32Array(N); + const r = state.ring; + for (let i = 0; i < N; i++) { + const w = 0.5 - 0.5 * Math.cos(2 * Math.PI * i / (N - 1)); + re[i] = r[(state.ringPos + i) % N] * w; + } + FFT(re, im); + const fs = state.ringRate, fmax = Math.min(fs / 2, 5500); + g.fillStyle = '#0c0e10'; + g.fillRect(0, 0, c.width, c.height); + /* APT band */ + const x = (f) => f / fmax * c.width; + g.fillStyle = 'rgba(79,179,255,0.08)'; + g.fillRect(x(2400 - 2080), 0, x(4160), c.height); + g.strokeStyle = 'rgba(79,179,255,0.5)'; + g.beginPath(); + g.moveTo(x(2400) + 0.5, 0); + g.lineTo(x(2400) + 0.5, c.height); + g.stroke(); + g.strokeStyle = '#7fe3a0'; + g.beginPath(); + for (let px = 0; px < c.width; px++) { + const b0 = Math.floor(px / c.width * fmax / fs * N), b1 = Math.max(b0 + 1, Math.floor((px + 1) / c.width * fmax / fs * N)); + let m = 0; + for (let b = b0; b < b1; b++) + m = Math.max(m, re[b] * re[b] + im[b] * im[b]); + const db = 10 * Math.log10(m + 1e-12); + const y = Math.max(0, Math.min(c.height, c.height - (db + 40) / 90 * c.height)); + if (px === 0) + g.moveTo(px, y); + else + g.lineTo(px, y); + } + g.stroke(); + g.fillStyle = '#7d8691'; + g.font = '10px sans-serif'; + g.fillText('2400 Hz', x(2400) + 3, 10); + g.fillText(fmax.toFixed(0) + ' Hz', c.width - 44, c.height - 3); + } + + function DrawScope() + { + const c = $('scope'), g = c.getContext('2d'); + g.fillStyle = '#0c0e10'; + g.fillRect(0, 0, c.width, c.height); + const n = state.lines.length; + if (!n) + return; + const l = state.lines[n - 1]; + const [lo, hi] = LevelsFor(n - 1); + const sx = c.width / W; + const shade = { 'Sync A': '#3a2020', 'Sync B': '#3a2020', 'Space A': '#20283a', 'Space B': '#20283a', 'Telemetry A': '#2c3a20', 'Telemetry B': '#2c3a20' }; + for (const r of APT.REGIONS) { + if (!shade[r.name]) + continue; + g.fillStyle = shade[r.name]; + g.fillRect(r.start * sx, 0, Math.max(1, r.len * sx), c.height); + } + g.strokeStyle = '#d8dde3'; + g.beginPath(); + for (let px = 0; px < c.width; px++) { + const a = Math.floor(px / sx), b = Math.max(a + 1, Math.floor((px + 1) / sx)); + let mn = 1e9, mx = -1e9; + for (let k = a; k < b && k < W; k++) { + mn = Math.min(mn, l.words[k]); + mx = Math.max(mx, l.words[k]); + } + const y = (v) => c.height - 2 - (v - lo) / (hi - lo) * (c.height - 4); + g.moveTo(px + 0.5, y(mx)); + g.lineTo(px + 0.5, y(mn) + 1); + } + g.stroke(); + } + + function DrawSyncHist() + { + const c = $('synchist'), g = c.getContext('2d'); + g.fillStyle = '#0c0e10'; + g.fillRect(0, 0, c.width, c.height); + const n = state.lines.length; + const from = Math.max(0, n - c.width); + for (let i = from; i < n; i++) { + const l = state.lines[i]; + const h = l.sync * c.height; + g.fillStyle = l.sync > 0.6 ? '#4cd07d' : l.sync > 0.3 ? '#f0b429' : '#ff5d5d'; + g.fillRect(i - from, c.height - h, 1, h); + } + } + + function DrawWedges() + { + const c = $('wedges'), g = c.getContext('2d'); + g.fillStyle = '#0c0e10'; + g.fillRect(0, 0, c.width, c.height); + const fr = state.tel.frames.filter((f) => f.complete); + if (!fr.length) { + g.fillStyle = '#7d8691'; + g.font = '11px sans-serif'; + g.fillText('waiting for a full 128-line telemetry frame', 8, 38); + return; + } + const f = fr[fr.length - 1]; + const lo = 0.5 * (f.a[8] + f.b[8]), hi = 0.5 * (f.a[7] + f.b[7]); + const draw = (w, y0, label) => { + const bw = (c.width - 40) / 16; + g.fillStyle = '#7d8691'; + g.font = '10px sans-serif'; + g.fillText(label, 2, y0 + 20); + for (let k = 0; k < 16; k++) { + const v = Math.max(0, Math.min(1, (w[k] - lo) / (hi - lo))); + const s = Math.round(v * 255); + g.fillStyle = `rgb(${s},${s},${s})`; + g.fillRect(40 + k * bw, y0 + 2, bw - 2, 26); + } + }; + draw(f.a, 2, 'A ch' + f.chA); + draw(f.b, 36, 'B ch' + f.chB); + } + + function DrawFrames() + { + const el = $('frames'); + const fr = state.tel.frames; + if (!fr.length) { + el.innerHTML = 'no frames yet'; + DrawWedges(); + return; + } + let h = ''; + let prev = null; + for (const f of fr) { + const t = state.lines[f.start] ? state.lines[f.start].time : NaN; + const id = f.chA + '/' + f.chB; + const cls = !f.complete || f.quality < 0.95 ? 'poor' : (prev && prev !== id ? 'change' : ''); + h += `` + + `` + + ``; + if (f.complete) + prev = id; + } + el.innerHTML = h + '
linetimeABq
${f.start}${FormatTime(t)}${f.chA}${f.chB}${f.quality.toFixed(2)}
'; + DrawWedges(); + } + + /* ---------------------------------------------------------------- */ + /* cursor / markers */ + + function EventToCell(e) + { + const r = img.overlay.getBoundingClientRect(); + const row = Math.floor((e.clientY - r.top) / r.height * img.cap); + const col = Math.floor((e.clientX - r.left) / r.width * img.width); + return { row, col, word: ColumnToWord(col) }; + } + + function OnHover(e) + { + const { row, word } = EventToCell(e); + const l = state.lines[row]; + if (!l || word < 0) { + $('cursor').innerHTML = '-'; + return; + } + const reg = APT.RegionAt(word); + const [lo, hi] = LevelsFor(row); + const v = (l.words[word] - lo) / (hi - lo); + const fr = state.tel.frames.filter((f) => f.start <= row).pop(); + $('cursor').innerHTML = + `line ${row} t=${FormatTime(l.time)}
` + + `word ${word} ${reg ? reg.name + ' +' + (word - reg.start) : ''}
` + + `level ${(v * 100).toFixed(1)}% sync ${(l.sync * 100).toFixed(0)}%${l.locked ? '' : ' (free-run)'}` + + (fr ? `
frame @${fr.start} line ${row - fr.start}, wedge ${Math.floor((row - fr.start) / 8) + 1}` : ''); + } + + function OnClick(e) + { + const { row } = EventToCell(e); + const l = state.lines[row]; + if (!l) + return; + state.markers.push({ line: row, time: l.time, label: 'M' + (state.markers.length + 1) }); + state.markers.sort((a, b) => a.line - b.line); + DrawMarkers(); + DrawOverlay(); + } + + function DrawMarkers() + { + const el = $('markers'); + if (!state.markers.length) { + el.innerHTML = 'click the image to mark a line'; + return; + } + el.innerHTML = ''; + state.markers.forEach((m, i) => { + const d = document.createElement('div'); + const sample = state.src ? Math.round(m.time * state.src.rate) : null; + d.innerHTML = `${m.label} line ${m.line}${FormatTime(m.time)}${sample !== null ? ' #' + sample : ''}x`; + d.querySelector('.x').onclick = (ev) => { + ev.stopPropagation(); + state.markers.splice(i, 1); + DrawMarkers(); + DrawOverlay(); + }; + d.onclick = () => ScrollToRow(m.line + 40); + el.appendChild(d); + }); + } + + function MarkerText() + { + return state.markers.map((m) => { + const s = state.src ? ' sample ' + Math.round(m.time * state.src.rate) : ''; + return `${m.label}\tline ${m.line}\t${m.time.toFixed(4)} s\t${FormatTime(m.time)}${s}`; + }).join('\n'); + } + + /* ---------------------------------------------------------------- */ + /* save */ + + function SavePNG() + { + const n = state.lines.length; + if (!n) + return; + FlushImage(); + const t = document.createElement('canvas'); + t.width = img.width; + t.height = n; + if (state.showRepairs) { + /* save without the repair tint */ + const id = t.getContext('2d').createImageData(img.width, n); + for (let i = 3; i < id.data.length; i += 4) + id.data[i] = 255; + RenderRows(0, n, id, false); + t.getContext('2d').putImageData(id, 0, 0); + } else { + t.getContext('2d').drawImage(img.canvas, 0, 0, img.width, n, 0, 0, img.width, n); + } + const base = state.src && state.mode !== 'live' ? state.src.name.replace(/\.[^.]*$/, '') : 'apt-live'; + t.toBlob((b) => { + const a = document.createElement('a'); + a.href = URL.createObjectURL(b); + a.download = `${base}-${state.view}.png`; + a.click(); + setTimeout(() => URL.revokeObjectURL(a.href), 5000); + }, 'image/png'); + } + + /* ---------------------------------------------------------------- */ + /* wiring */ + + $('fileInput').onchange = (e) => { + if (e.target.files[0]) + LoadFile(e.target.files[0]).catch((err) => alert('Could not load: ' + err.message)); + e.target.value = ''; + }; + $('btnFast').onclick = StartFast; + $('btnRealtime').onclick = () => StartRealtime(0); + $('btnPause').onclick = TogglePause; + $('btnStop').onclick = Stop; + $('btnLive').onclick = () => (state.mode === 'live' ? Stop() : StartLive()); + $('btnSave').onclick = SavePNG; + $('speed').onchange = (e) => SetSpeed(parseFloat(e.target.value)); + $('listen').onchange = ApplyVolume; + $('volume').oninput = ApplyVolume; + $('view').onchange = (e) => { + state.view = e.target.value; + AllocImage(state.lines.length); + FlushImage(); + }; + $('contrast').onchange = (e) => { + state.contrast = e.target.value; + UpdateLevels(true); + }; + $('demod').onchange = (e) => { + state.demod = e.target.value; + }; + $('repair').onchange = (e) => { + state.repair = e.target.value; + ResetRepairs(); + }; + $('showRepairs').onchange = (e) => { + state.showRepairs = e.target.checked; + Rerender(); + }; + $('zoom').onchange = () => { + ApplyZoom(); + DrawOverlay(); + }; + $('progress').onclick = (e) => { + if (!state.src) + return; + const r = e.currentTarget.getBoundingClientRect(); + StartRealtime((e.clientX - r.left) / r.width * state.src.duration); + }; + img.overlay.addEventListener('mousemove', OnHover); + img.overlay.addEventListener('click', OnClick); + $('frames').onclick = (e) => { + const tr = e.target.closest('tr[data-line]'); + if (tr) + ScrollToRow(parseInt(tr.dataset.line, 10) + 60); + }; + $('btnCopyMarks').onclick = () => navigator.clipboard && navigator.clipboard.writeText(MarkerText()); + $('btnClearMarks').onclick = () => { + state.markers = []; + DrawMarkers(); + DrawOverlay(); + }; + window.addEventListener('keydown', (e) => { + if (e.code === 'Space' && e.target.tagName !== 'INPUT' && e.target.tagName !== 'SELECT') { + e.preventDefault(); + TogglePause(); + } + }); + window.addEventListener('resize', DrawOverlay); + + const vp = $('viewport'); + vp.addEventListener('dragover', (e) => { + e.preventDefault(); + vp.classList.add('dragover'); + }); + vp.addEventListener('dragleave', () => vp.classList.remove('dragover')); + vp.addEventListener('drop', (e) => { + e.preventDefault(); + vp.classList.remove('dragover'); + const f = e.dataTransfer.files[0]; + if (f) + LoadFile(f).catch((err) => alert('Could not load: ' + err.message)); + }); + + /* feeding runs on a timer so it keeps going in a background tab */ + setInterval(() => { + RealtimeTick(); + LiveTick(); + }, 40); + + function Frame() + { + FlushImage(); + UpdateStatus(); + if (state.mode === 'realtime' || state.mode === 'live' || state.mode === 'fast') + DrawSpectrum(); + DrawScope(); + DrawSyncHist(); + requestAnimationFrame(Frame); + } + + /* for encoder-ui.js */ + window.AptApp = { LoadSource, StartRealtime: () => StartRealtime(0), StartFast, state }; + + SetMode('idle'); + DrawFrames(); + ListDevices(); + requestAnimationFrame(Frame); +})(); diff --git a/apt.js b/apt.js new file mode 100644 index 0000000..6a043ae --- /dev/null +++ b/apt.js @@ -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 + + + + + + diff --git a/style.css b/style.css new file mode 100644 index 0000000..342dfe6 --- /dev/null +++ b/style.css @@ -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); } diff --git a/tools/decode.js b/tools/decode.js new file mode 100644 index 0000000..636e1b3 --- /dev/null +++ b/tools/decode.js @@ -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}`); diff --git a/tools/encode.js b/tools/encode.js new file mode 100644 index 0000000..5b3f7c9 --- /dev/null +++ b/tools/encode.js @@ -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`); diff --git a/tools/gui-smoke.js b/tools/gui-smoke.js new file mode 100644 index 0000000..1afbace --- /dev/null +++ b/tools/gui-smoke.js @@ -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(/ ({ 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:', / { console.error('FAIL', e); process.exit(1); }); diff --git a/tools/survey.js b/tools/survey.js new file mode 100644 index 0000000..e9058df --- /dev/null +++ b/tools/survey.js @@ -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}`); } + } diff --git a/wav.js b/wav.js new file mode 100644 index 0000000..d0dca72 --- /dev/null +++ b/wav.js @@ -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);