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>
1141 lines
31 KiB
JavaScript
1141 lines
31 KiB
JavaScript
/*
|
|
* 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 = '<option value="">default input</option>';
|
|
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 = '<span class="dim">no frames yet</span>';
|
|
DrawWedges();
|
|
return;
|
|
}
|
|
let h = '<table><tr><th>line</th><th>time</th><th>A</th><th>B</th><th>q</th></tr>';
|
|
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 += `<tr class="${cls}" data-line="${f.start}"><td>${f.start}</td><td>${FormatTime(t)}</td>` +
|
|
`<td title="${APT.CHANNEL_DESC[f.chA] || ''}">${f.chA}</td><td title="${APT.CHANNEL_DESC[f.chB] || ''}">${f.chB}</td>` +
|
|
`<td>${f.quality.toFixed(2)}</td></tr>`;
|
|
if (f.complete)
|
|
prev = id;
|
|
}
|
|
el.innerHTML = h + '</table>';
|
|
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 = '<span class="dim">-</span>';
|
|
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)}<br>` +
|
|
`word ${word} ${reg ? reg.name + ' +' + (word - reg.start) : ''}<br>` +
|
|
`level ${(v * 100).toFixed(1)}% sync ${(l.sync * 100).toFixed(0)}%${l.locked ? '' : ' (free-run)'}` +
|
|
(fr ? `<br>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 = '<span class="dim">click the image to mark a line</span>';
|
|
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 = `<span>${m.label} line ${m.line}</span><span>${FormatTime(m.time)}${sample !== null ? ' #' + sample : ''}</span><span class="x" title="remove">x</span>`;
|
|
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);
|
|
})();
|