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:
zefieandClaude Opus 5.5 committed 2026-12-03 20:58:22 -05:00
commit 4bc15bb585
12 files changed
+3375

No files matched your search

+61
View File
@@ -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}`);
+79
View File
@@ -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`);
+111
View File
@@ -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); });
+51
View File
@@ -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}`); }
}