Files
JIANT/web/math_test.mjs
T
Claude 378f2c5da6 MATH tab: formulas of one's own sent to the device (MATH USER, JIANT FM V10.8.75)
The MATH tab compiles a formula of one's own to the device's bytecode and sends it to a track, now that the firmware
plays them (JIANT FM V10.8.75, codex/v66-clean: firmware/src/math_user.c, JIANT BYTE's formula machine).

- FVM (in the MATH section): a port of JIANT BYTE's compiler (its firmware/src/fvm.c, GPL-3.0, the owner's): its
  grammar (t w a n v; C's operators; sin cos tri saw sqr abs min max floor int fix rnd sat clip; a string as a table),
  its INT / FIX types, its folding, its instructions, serialized as math_user.c reads them (EDITOR_PROTOCOL.md "1.5").
  ph() lp() hp() eu() and FUNC's calls are BYTE's only: refused with that message. At most 64 bytes, a stack of 12.
  FVM.run is math_user.c's machine in JavaScript; FVM.pack7 / unpack7 the backup's groups.
- The tab: a text that is one of the firmware's 48 BYTE formulas is sent as its ALGO, as before; any other is MATH
  USER (the message says its size and INT -> BYTE or FIX -> FLOAT). Heard through the emulator's own machine (the
  wasm's FORMULA, track 1 at ALGO USER), the model when the wasm is older. Sent with FORMULA (100) to a device whose
  INFO has 'E' (45 02 64 12), read back and compared, then the eight values with ALGO -4 (USER) and WAVE 5 (INT) or 6
  (FIX). Read: a track at ALGO USER gives its bytes; their text comes back if it was sent from this browser (kept in
  localStorage by its bytes). An older device: not sendable, as before. The generator's formulas are MATH USER ones.
- The mock device answers FORMULA and says 'E' and 'C' 1.5 (before its 'D' / 'H').
- EDITOR_PROTOCOL.md: the proposal becomes "1.5: MATH USER, a formula of one's own (100; V10.8.75)": the command, the
  bytes (BYTE's FO_* numbers, the operand modes), the checks, what is not in JIANT FM, the project block, the presets;
  the version table and the frozen command numbers.

Tests:
- math_test.mjs: web/math_fvm_gold.json (142 texts compiled by BYTE's own fvm_compile from BYTE origin/main 1495526,
  serialized, run by its fvm_run): FVM gives BYTE's bytes for all 135 that fit (93 of BYTE's 96 factory formulas: B16 and F32 are over 64 bytes, F05 and F22 use ph(); and every operator),
  FVM.run BYTE's values for each (3 x 4160); the 7 refused refused; errors with their place; pack7; the generator's
  formulas fit. With EMU_WASM: B01's bytecode at ALGO USER plays B01's samples bit for bit; FORMULA reads back; a FIX
  formula on FLOAT sounds. Passes against a wasm built from the firmware's V10.8.75 commit (emsdk 6.0.11).
- editor_browser_test.mjs: on the firmware wasm, a formula of one's own compiled, sent to track 4 (FORMULA 4 0 gives
  the editor's bytes, ALGO -4), read back into the editor with its text; without a device, one's own heard through the
  emulator (the model without one), a FIX floatbeat recognised. Passes (with that wasm); test_web, test_backup,
  test_manual pass.

The public emulator (web/EMULATOR's pin) gets the VM when the pin moves to the firmware's V10.8.75 commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KMHk6yH4XbP1xxHYKCo9Mh
2026-11-30 11:13:55 +00:00

166 lines
13 KiB
JavaScript

// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Juan Ignacio Antonucci (Juan Jiant)
// (the formula editor) editor.html's MATH section (between MATH-BEGIN / MATH-END) against the firmware:
// node web/math_test.mjs
// - the VM: the grammar, its errors and where they are; every one of the firmware's 48 BYTE formulas (eng_lofi.c
// lofi_byte) bit for bit: their samples' hashes over 16000 (t, a) each, taken from the firmware's C compiled natively
// (V10.8.74); VAR's mutation (lofi_mut) and MOTION's speed (lofi_motion) the same way. FIRMWARE_SRC=.../eng_lofi.c and
// a C compiler: the hashes made again from that source
// - the proposed bytecode (EDITOR_PROTOCOL.md "a user formula"): the same samples as the VM, its size and stack
// - the generator: seeded (one seed, one formula), every formula valid and moving
// - (V10.8.75) MATH USER: FVM, the port of JIANT BYTE's compiler, against BYTE's own (web/math_fvm_gold.json: 142 texts
// compiled by BYTE's fvm_compile, serialized, run by its fvm_run): the same bytes for every one, the same values from
// FVM.run (JIANT FM's math_user.c) at three a's; the refused ones refused; pack7 both ways; the generator's formulas
// compile to at most 64 bytes; given EMU_WASM, a formula sent with FORMULA (100) to the emulator plays and reads back
// - EMU_WASM (default build/emu/felucca.wasm): the BYTE model against the emulator's own samples, formula by formula
// (the waveforms' correlation), and the eight values a send writes, read back
import fs from "fs";
import path from "path";
import { execFileSync } from "child_process";
const HERE = path.dirname(new URL(import.meta.url).pathname);
const html = fs.readFileSync(path.join(HERE, "editor.html"), "utf8");
const core = html.slice(html.indexOf("/*MATH-BEGIN*/"), html.indexOf("/*MATH-END*/"));
const X = new Function(core + "; return { MATH_BYTE, MATH_FLOAT, MathVM, FVM, mathMut, mathMotion, mathGenerate, mathScore, mathRenderByte, mathEmuRender, mathValues };")();
let fails = 0;
const ok = (c, what) => { console.log(`${what.padEnd(96)} ${c ? "ok" : "FAIL"}`); if (!c) fails++; };
const fnv = (h, x) => Math.imul(h ^ x, 16777619) >>> 0;
/* the samples the hashes cover: f, a 1 6 11 16, t 0..1999 x 37 then 2000 spread over 32 bits */
const SAMPLE_T = (i, f) => (i < 2000 ? i * 37 : (Math.imul(i, 2654435761) + f) >>> 0);
const BYTE_HASH = [242086445, 582409269, 2775287381, 947135173, 495738245, 2211565701, 2596376949, 438985765, 2282081181, 2549055893, 1457526661, 2061544245, 2633081133, 2898665829, 1122579133, 3002132165, 4187706811, 4262248330, 3341324481, 2218714499, 2476142609, 1061348845, 3915694821, 2047500439, 2253473162, 149204812, 1152284677, 1173597842, 2608852433, 1045119341, 3973695903, 2109218995, 488461709, 1212083197, 1237344109, 4232385389, 659021989, 1906829989, 2782905541, 1179991381, 2949286917, 2147962981, 225962673, 3708983153, 1322780669, 3252066965, 7766818, 2179502982];
const MUT_HASH = 3332514091;
/* ---- the grammar */
{
const V = X.MathVM;
const e1 = V.compile("t * (42 & t >> 10"), e2 = V.compile("t + x"), e3 = V.compile("t >> > 2"), e4 = V.compile("0x1FFFFFFFF");
ok(!e1.ok && e1.pos === 17 && !e2.ok && e2.pos === 4 && !e3.ok && e3.pos === 5 && !e4.ok, `VM: errors say what and where (${[e1, e2, e3, e4].map((e) => e.pos).join(" ")})`);
const c = V.compile("t * (42 & t >> 10)");
ok(c.ok && c.fn(1 << 13, 1) === ((Math.imul(1 << 13, 42 & (1 << 13) >>> 10) >>> 0) & 255) && c.stock === -1, "VM: a formula of one's own compiles and runs");
const p = V.compile("-t & 4095u ? t < 5 : !t || a == 3 && t % 0 == 0 ? t / 0 : 7");
ok(p.ok && p.fn(10, 3) === 0 && p.fn(4096, 3) === 0 && p.fn(4096, 2) === 7, "VM: unary, ?:, && || precedence, / and % by 0 (0), u suffix");
ok(V.compile("t*((t>>12|t>>8)&63&t>>4)").stock === 33 && V.compile(" ( t * ( (t >> 12 | t >> 8) & 63 & t >> 4 ) ) ").stock === 33,
"VM: one of the firmware's formulas recognised however it is spaced (B34: sendable)");
}
/* ---- the 48 BYTE formulas, bit for bit */
{
let src = null;
if (process.env.FIRMWARE_SRC) {
try {
const s = fs.readFileSync(process.env.FIRMWARE_SRC, "utf8");
const body = s.slice(s.indexOf("static __attribute__((noinline)) uint32_t lofi_byte("), s.indexOf("/* (JIANT 0.5.1; 0.5.6 a floatbeat"));
const c = `#include <stdint.h>\n#include <stdio.h>\n${body.replace("__attribute__((noinline))", "")}\nint main(void){for(uint32_t f=0;f<48;f++){uint32_t h=2166136261u;for(uint32_t a=1;a<=16;a+=5)for(uint32_t i=0;i<4000;i++){uint32_t t=i<2000?i*37u:i*2654435761u+f;h=(h^(lofi_byte(f,t,a)&255u))*16777619u;}printf("%u\\n",h);}return 0;}`;
const dir = fs.mkdtempSync(path.join(process.env.TMPDIR || "/tmp", "mathc-"));
fs.writeFileSync(path.join(dir, "lb.c"), c);
execFileSync("cc", ["-O1", "-w", "-o", path.join(dir, "lb"), path.join(dir, "lb.c")]);
src = execFileSync(path.join(dir, "lb"), { encoding: "utf8" }).trim().split("\n").map(Number);
} catch (e) { console.log("(FIRMWARE_SRC: not compiled: " + e.message.split("\n")[0] + ")"); }
}
const ref = src || BYTE_HASH, bad = [];
X.MATH_BYTE.forEach((f, k) => {
const c = X.MathVM.compile(f);
let h = 2166136261;
for (let a = 1; a <= 16; a += 5) for (let i = 0; i < 4000; i++) h = fnv(h, c.fn(SAMPLE_T(i, k), a));
if (!c.ok || c.stock !== k || h !== ref[k]) bad.push(k + 1);
});
ok(!bad.length, `VM: the 48 BYTE formulas == the firmware's lofi_byte, 768000 samples (${src ? "compiled from FIRMWARE_SRC" : "V10.8.74's hashes"})${bad.length ? " B" + bad : ""}`);
let h = 2166136261;
for (let v = 0; v < 128; v++) for (let i = 0; i < 500; i++) h = fnv(h, X.mathMut((Math.imul(i, 2654435761) + v) >>> 0, v));
for (let m = 0; m < 256; m++) h = fnv(h, X.mathMotion(m));
ok(h === MUT_HASH, "VM: VARIANT's mutation (lofi_mut, 64000 values) and MOTION's speed (lofi_motion) == the firmware's");
ok(X.MATH_FLOAT.length === 48 && X.MATH_FLOAT.every(([d, c]) => c.includes("return")), "the 48 FLOAT formulas listed with their source");
}
/* ---- the proposal's bytecode, the generator */
{
const gen = Array.from({ length: 40 }, (_, k) => X.mathGenerate(k + 1));
let bad = 0, maxLen = 0, maxSt = 0;
for (const f of X.MATH_BYTE.concat(gen)) {
const c = X.MathVM.compile(f), r = X.MathVM.rpn(f);
maxLen = Math.max(maxLen, r.code.length); maxSt = Math.max(maxSt, r.stack);
if (r.code.some((b) => b > 127)) bad++;
for (let i = 0; i < 2000; i++) for (const a of [1, 9, 16]) { const t = Math.imul(i, 2654435761) >>> 0; if (c.fn(t, a) !== X.MathVM.run(r.code, t, a)) bad++; }
}
ok(!bad, `bytecode (the proposal): 7-bit bytes, the same samples as the VM for 88 formulas (at most ${maxLen} bytes, stack ${maxSt})`);
ok(X.mathGenerate(7) === X.mathGenerate(7) && new Set(gen).size >= 36, `generator: a seed is one formula, 40 seeds ${new Set(gen).size} formulas`);
const moving = gen.filter((f) => { const c = X.MathVM.compile(f); return c.ok && X.mathScore(c.fn, 5) > 0; }).length;
ok(moving >= 36, `generator: every formula valid, ${moving} of 40 changing over time without being noise`);
console.log(" e.g. seed 1: " + gen[0] + "\n seed 2: " + gen[1]);
}
/* ---- (V10.8.75) MATH USER: the port of BYTE's compiler against BYTE's */
{
const G = JSON.parse(fs.readFileSync(path.join(HERE, "math_fvm_gold.json"), "utf8"));
let same = 0, bad = [], vals = 0, refused = 0;
for (const x of G) {
const c = X.FVM.compile(x.src);
if (!x.code || x.code.length > 64) { if (c.ok) bad.push(x.src); else refused++; continue; }
if (!c.ok || c.code.join() !== x.code.join()) { bad.push(x.src); continue; }
same++;
let k = 0;
for (; k < 3; k++) {
let h = 2166136261;
const a = [1, 7, 16][k];
for (let i = 0; i < 4160; i++) {
const t = i < 4096 ? Math.imul(i, k + 1) >>> 0 : X.FVM.hash((Math.imul(i, 7919) + k) >>> 0);
h = fnv(h, X.FVM.run(c.code, t, Math.imul(t, 2654435761) >>> 0, a));
}
if (h !== x.hash[k]) break;
}
if (k === 3) vals++;
}
ok(!bad.length && same >= 135, `FVM: JIANT BYTE's fvm_compile's bytes for ${same} formulas (93 of BYTE's 96 factory, every operator)${bad.length ? " NOT: " + bad.slice(0, 3).join(" | ") : ""}`);
ok(vals === same, `FVM.run: BYTE's fvm_run's values for all ${vals} (3 x 4160 each)`);
ok(refused >= 7, `FVM: BYTE's ph() lp() eu() and the ones over 64 bytes refused (${refused})`);
const e1 = X.FVM.compile("t * (42 & t >> 10"), e2 = X.FVM.compile("t + q"), e3 = X.FVM.compile("lp(sin(w), 0.5)");
ok(!e1.ok && e1.pos === 17 && !e2.ok && e2.pos === 4 && !e3.ok, `FVM: errors say what and where (${e1.error} ${e1.pos}, ${e2.error} ${e2.pos}, ${e3.error})`);
const p = Array.from({ length: 64 }, (_, i) => (i * 37 + 5) & 255);
ok(X.FVM.unpack7(X.FVM.pack7(p)).join() === p.join() && X.FVM.pack7(p).every((b) => b < 128), "pack7: 64 bytes there and back, every byte 7-bit");
const gen = Array.from({ length: 40 }, (_, k) => X.FVM.compile(X.mathGenerate(k + 1)));
ok(gen.every((c) => c.ok && c.code.length <= 64 && !c.fix), `generator: its 40 formulas are MATH USER formulas (INT, ${Math.max(...gen.map((c) => c.code.length))} B the longest)`);
}
/* ---- the model against the emulator */
const WASM = process.env.EMU_WASM || path.join(HERE, "..", "build", "emu", "felucca.wasm");
if (fs.existsSync(WASM)) {
const mod = await WebAssembly.compile(fs.readFileSync(WASM));
const fresh = async () => (await WebAssembly.instantiate(mod, {})).exports;
const corr = (a, b, lag) => { let ab = 0, aa = 0, bb = 0; for (let i = 11025; i < a.length - 500; i++) { const x = a[i], y = b[i + lag]; ab += x * y; aa += x * x; bb += y * y; } return { r: ab / Math.sqrt(aa * bb + 1e-12), e: bb / (a.length - 11525) }; };
for (const motion of [0, 64]) {
const rs = [];
let silent = 0;
for (let f = 0; f < 48; f++) {
const o = { f, note: 60, chip: 2, var: 0, motion, wave: 5, secs: 1.2, gate: 1.2, dry: true };
const w = X.mathEmuRender(await fresh(), o).l, js = X.mathRenderByte({ ...o, fn: X.MathVM.compile(X.MATH_BYTE[f]).fn });
let best = -1, en = 0;
for (let lag = -8; lag <= 8; lag++) { const c = corr(js, w, lag); if (c.r > best) best = c.r; en = c.e; }
if (en < 1e-6) { silent++; continue; }
rs.push(best);
}
rs.sort((a, b) => a - b);
const med = rs[rs.length >> 1];
ok(med > 0.85, `model vs emulator (C4, MOTION ${motion}, 8BIT, VAR 0, dry): ${rs.length} formulas sounding, correlation median ${med.toFixed(3)}, ` +
`${rs.filter((x) => x > 0.9).length} over 0.9, lowest ${rs[0].toFixed(2)}${silent ? ` (${silent} silent in their first second)` : ""}`);
}
const ex = await fresh(), o = { wave: 5, f: 47, chip: 1, var: 77, motion: 200, grit: 9, bend: 33, loop: 66, note: 48, secs: 0.5 };
const r = X.mathEmuRender(ex, o);
const back = (k) => { const q = [31, 0, 115 + k]; new Uint8Array(ex.memory.buffer, ex.web_ed_buf(), 3).set(q); const n = ex.web_ed(3); const a = new Uint8Array(ex.memory.buffer, ex.web_ed_reply(), n); return (a[2] | a[3] << 7) - 8192; };
const want = X.mathValues(o), got = want.map((_, k) => back(k));
ok(got.join() === want.join() && r.l.some((x) => Math.abs(x) > 1e-3), `the emulator takes a send's eight values (ALGO 188 = B48, MOTION 200: SYNC) and sounds: ${got.join(" ")}`);
{ /* (V10.8.75) a formula of one's own: FORMULA (100) to the emulator, ALGO USER: it plays; B01's text as USER: B01's samples */
const ex2 = await fresh(), b01 = X.FVM.compile(X.MATH_BYTE[0]).code;
const o2 = { wave: 5, f: 0, chip: 2, var: 0, motion: 0, note: 60, secs: 0.6, dry: true };
const u = X.mathEmuRender(ex2, { ...o2, user: true, code: b01 }), s0 = X.mathEmuRender(await fresh(), o2);
if (!u.formula) console.log("MATH USER on the emulator: its firmware has no FORMULA (before V10.8.75)".padEnd(96) + " skip");
else {
let d = 0; for (let i = 0; i < u.l.length; i++) d = Math.max(d, Math.abs(u.l[i] - s0.l[i]));
ok(d === 0, `MATH USER on the emulator: B01's bytecode at ALGO USER plays B01's samples, bit for bit (C4: under the 11 kHz cap)`);
const q = [100, 0, 0]; new Uint8Array(ex2.memory.buffer, ex2.web_ed_buf(), 3).set(q);
const n = ex2.web_ed(3), a = Array.from(new Uint8Array(ex2.memory.buffer, ex2.web_ed_reply(), n));
ok(a[1] === 0 && a[2] === b01.length && X.FVM.unpack7(a.slice(3)).slice(0, a[2]).join() === b01.join(), `FORMULA 0 0: the formula read back (${a[2]} B)`);
const f20 = X.FVM.compile(X.MATH_FLOAT[19][0] === "odd partials, built up" ? "(sin(w)+((t>>11&3)>0?sin(w*3)/3:0.)+((t>>11&3)>1?sin(w*5)/5:0.)+((t>>11&3)>2?sin(w*7)/7:0.))*3/4" : "sin(w)");
const uf = X.mathEmuRender(await fresh(), { ...o2, wave: 6, user: true, code: f20.code });
ok(f20.ok && f20.fix && uf.formula && uf.l.some((x) => Math.abs(x) > 1e-3), `MATH USER, FIX on WAVE FLOAT (F20's text in BYTE's FIX, ${f20.code && f20.code.length} B): it sounds`);
}
}
} else console.log(`model vs emulator: no ${WASM} (EMU_WASM=...)`.padEnd(96) + " skip");
console.log(fails ? `MATH TESTS FAILED (${fails})` : "math tests passed");
process.exit(fails ? 1 : 0);