Files
skiff/webapp/installer/index.html
T

1278 lines
73 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!doctype html>
<!-- SPDX-License-Identifier: GPL-3.0-only
Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments -->
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Skiff</title>
<style>
:root { --bg: #fff; --fg: #000; --dim: #777; }
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) { --bg: #000; --fg: #fff; --dim: #888; }
}
:root[data-theme="dark"] { --bg: #000; --fg: #fff; --dim: #888; }
body { margin: 0; background: var(--bg); color: var(--fg);
font: 16px/1.6 -apple-system, BlinkMacSystemFont, "Helvetica Neue", Arial, sans-serif; }
main { max-width: 520px; margin: 0 auto; padding: 48px 16px; }
h1 { font-size: 24px; font-weight: 600; margin: 0 0 24px; }
.lang { float: right; font-size: 13px; color: var(--dim); cursor: pointer; text-decoration: underline; background: none; padding: 0; color: var(--dim); }
p { margin: 0 0 16px; }
button { font: inherit; background: var(--fg); color: var(--bg); border: 0; padding: 8px 20px; cursor: pointer; }
button:disabled { opacity: .3; cursor: default; }
#status { margin-top: 16px; min-height: 1.6em; }
.small { color: var(--dim); font-size: 13px; }
progress { width: 100%; height: 4px; margin-top: 16px; }
pre { color: var(--dim); font-size: 12px; white-space: pre-wrap; margin-top: 16px; }
</style>
</head>
<body>
<main>
<button class="lang" id="lang"></button>
<h1>Skiff</h1>
<p data-t="intro"></p>
<p data-t="warn"></p>
<p class="small" data-t="direct"></p>
<p class="small" data-t="beta"></p>
<p class="small"><span data-t="brick"></span>
<a href="https://github.com/kurogedelic/FM-1-transporter" target="_blank" rel="noopener" style="color:inherit">FM-1-transporter</a></p>
<p class="small"><span data-t="smk"></span>
<a href="https://github.com/illuminus5/skiff/blob/main/SMK37.md" target="_blank" rel="noopener" style="color:inherit">SMK37.md</a></p>
<p><button id="go" disabled data-t="install"></button></p>
<details style="margin-top:24px">
<summary data-t="stockTitle"></summary>
<p class="small" data-t="back"></p>
<p class="small"><a href="https://www.m-vave.com/download" target="_blank" rel="noopener" style="color:inherit">M-VAVE Downloads</a></p>
<p><label><span data-t="stockFile"></span><br><input id="stock-file" type="file" accept=".fwsc"></label></p>
<p><button id="stock-go" disabled data-t="stockGo"></button></p>
<p class="small" data-t="stockBackup"></p>
<p class="small"><label><input id="stock-recovery" type="checkbox"> <span data-t="stockRecovery"></span></label></p>
</details>
<progress id="bar" max="100" value="0"></progress>
<p id="status"></p>
<pre id="log"></pre>
<p><a href="../editor/" style="color:inherit" data-t="editor"></a></p>
<p><a href="../../learn/" style="color:inherit" data-t="learn"></a></p>
<p class="small">Skiff by illuminus5, built on Felucca by Leo Kuroshita (@kurogedelic), <a href="https://hugelton.com" target="_blank" rel="noopener" style="color:inherit">Hügelton Instruments</a>, with its CrispyZebra waveforms, drum voices, Sample Pack and Fukiai icons (MIT).<br>
SMK-37 support after genkigenki's SMK-37 layer (GPL-3.0). Font: Barlow Condensed (The Barlow Project Authors, SIL OFL 1.1). DRUM-X: JIANT FM by juanjiant-bit (GPL-3.0). Samples: Versilian Studios VSCO-2 Community Edition and VCSL (CC0 1.0).<br>
FM6 engine: msfa from Dexed (Google Inc., Pascal Gauthier, Apache-2.0). The package also holds three JieLi AC79 SDK files, uboot.boot, cfg_tool.bin and eq_cfg_hw.bin (JieLi Technology, Apache-2.0). <a href="../../firmware/LICENSING.md" style="color:inherit">Licences</a>: <a href="../../firmware/LICENSE" style="color:inherit">GPL-3.0</a>, <a href="../../firmware/LICENSES/Apache-2.0.txt" style="color:inherit">Apache-2.0</a>, <a href="../../firmware/LICENSES/" style="color:inherit">all</a>.<br>
M-VAVE, FM-1 and SMK-37 are trademarks of their respective owners.<br>
<span data-t="license"></span> <a href="https://github.com/illuminus5/skiff" target="_blank" rel="noopener" style="color:inherit">github.com/illuminus5/skiff</a></p>
</main>
<script type="module">
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments
//
// FM-1 (and SMK-37 Pro) .fwsc packages in the browser: the package identity and the image the
// device reads during an update.
const BLOCKS = 20, BLK = 0x30, KEEP = 0x2F, MAX_BLOCKS = 64;
const STOCK_V15_SHA256 = "db1642b2b6fa5c2cccb11ffd13878068bb28601678d3644049f99dc40e7edb8a";
const STOCK_APP_SIZE = 0x8DFBC;
const STOCK_V15_SIZE = 699956;
// (2.0.2, #64) the unmodified official FM-1 V16 (M-VAVE's FM-1.fwsc since 2026-10-21; FM-1_016): the way back of a unit
// that ran V16 (its head is V16's: Skiff's ota.c stages a package whose head is the unit's only)
const STOCK_V16_SHA256 = "d017fb65e70aca97ee29d944470c3515a74581df5c0576bf70de917c7b2b61d5";
const STOCK_V16_SIZE = 718196;
// each official FM-1 file's layout as pinned: identity, flash.bin's size, the app's offset and size
const FM1_STOCK = {
[STOCK_V15_SHA256]: { product: "FM-1_015", flash: 602112, appOff: 16672, app: STOCK_APP_SIZE },
[STOCK_V16_SHA256]: { product: "FM-1_016", flash: 692224, appOff: 16704, app: 0x91FA8 },
};
// the unmodified official SMK-37 Pro V016 (SMK-37_Pro_016.fwsc, 36 interleave blocks): the return of an SMK-37 Pro
// (the same pin as tools/fm1_install.py)
const STOCK_SMK016_SHA256 = "2d98ce72530e71d617384963423820536f094501299e2cfec0a8d3c3fb6bcfb0";
const STOCK_SMK016_SIZE = 705252;
const T = new Uint16Array(256);
for (let i = 0; i < 256; i++) {
let c = i << 8;
for (let k = 0; k < 8; k++) c = c & 0x8000 ? (c << 1) ^ 0x1021 : c << 1;
T[i] = c & 0xFFFF;
}
function crc16(d, crc = 0) {
for (let i = 0; i < d.length; i++) crc = ((crc << 8) & 0xFFFF) ^ T[((crc >> 8) ^ d[i]) & 0xFF];
return crc;
}
function enc(buf, off, size, key = 0xFFFF) {
for (let i = 0; i < size; i++) {
buf[off + i] ^= key & 0xFF;
key = ((key * 2) ^ (key & 0x8000 ? 0x1021 : 0)) & 0xFFFF;
}
}
function sfc(buf, off, size, base, key) {
for (let i = 0; i < size; i += 32) enc(buf, off + i, Math.min(size - i, 32), key ^ ((off + i - base) >> 2));
}
function chipkeyDecode(d) {
let sum = 0;
for (let i = 0; i < 16; i++) sum += d[i];
sum &= 0xFF;
sum = sum >= 0xE0 ? 0xAA : sum <= 0x10 ? 0x55 : sum;
let k = 0;
for (let i = 0; i < 16; i++) if ((d[16 + i] ^ d[15 - i]) < sum) k |= 1 << i;
return k;
}
const align32 = (v) => (v + 31) & ~31;
const u16 = (b, o) => b[o] | (b[o + 1] << 8);
const u32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0;
function w16(b, o, v) { b[o] = v & 0xFF; b[o + 1] = (v >> 8) & 0xFF; }
function w32(b, o, v) { w16(b, o, v & 0xFFFF); w16(b, o + 2, (v >>> 16) & 0xFFFF); }
class Entry { // JLFS head, 32 bytes
constructor(raw, off) {
this.hdrOff = off;
this.hcrc = u16(raw, off);
this.dcrc = u16(raw, off + 2);
this.offset = u32(raw, off + 4);
this.size = u32(raw, off + 8);
this.flags = raw[off + 12];
this.resvd = raw[off + 13];
this.index = u16(raw, off + 14);
this.rawName = raw.slice(off + 16, off + 32);
const z = this.rawName.indexOf(0);
this.name = String.fromCharCode(...this.rawName.slice(0, z < 0 ? 16 : z));
if (crc16(raw.subarray(off + 2, off + 32)) !== this.hcrc) throw new Error(`JLFS header CRC mismatch @${off.toString(16)}`);
}
packInto(buf) {
const o = this.hdrOff;
w16(buf, o + 2, this.dcrc); w32(buf, o + 4, this.offset); w32(buf, o + 8, this.size);
buf[o + 12] = this.flags; buf[o + 13] = this.resvd; w16(buf, o + 14, this.index);
buf.set(this.rawName, o + 16);
this.hcrc = crc16(buf.subarray(o + 2, o + 32));
w16(buf, o, this.hcrc);
}
}
class Package {
constructor(bytes) {
this.raw = new Uint8Array(bytes);
this.parseUfw();
this.flash = this.raw.slice(this.flashFileOff, this.flashFileOff + this.flashSize);
this.parseFlash();
}
get product() { return productOf(this.raw); }
setProduct(name) {
if (name.length > BLOCKS) throw new Error("product name too long");
for (let i = 0; i < BLOCKS; i++) {
const m = i < name.length ? (name.charCodeAt(i) + i + 1) & 0xFF : 0x7D;
if (i < name.length && m === 0x7D) throw new Error("product name encodes to the unused marker");
this.raw[i * BLK + KEEP] = m;
}
}
headerBytes() {
const h = new Uint8Array(BLOCKS * KEEP);
for (let i = 0; i < BLOCKS; i++) h.set(this.raw.subarray(i * BLK, i * BLK + KEEP), i * KEEP);
return h;
}
hdrFileOff(i) { return Math.floor(i / KEEP) * BLK + (i % KEEP); }
parseUfw() {
const h = this.headerBytes();
enc(h, 0, 0x40);
const hcrc = u16(h, 0), lcrc = u16(h, 2), nent = u16(h, 8);
if (crc16(h.subarray(2, 0x40)) !== hcrc) throw new Error("not an FM-1 .fwsc (UFW header CRC mismatch)");
this.skew = BLOCKS * BLK - h.length;
this.ufw = h;
this.nent = nent;
const hsize = 0x40 + nent * 0x50;
if (crc16(h.subarray(0x40, hsize)) !== lcrc) throw new Error("UFW entry list CRC mismatch");
this.entries = [];
for (let off = 0x40; off < hsize; off += 0x50) {
const e = h.slice(off, off + 0x50);
enc(e, 0, 0x50);
const z = e.subarray(0x40, 0x50).indexOf(0);
this.entries.push({ off, type: u16(e, 0), dcrc: u16(e, 4), dataOff: u32(e, 8), size: u32(e, 12),
name: String.fromCharCode(...e.subarray(0x40, z < 0 ? 0x50 : 0x40 + z)), plain: e });
}
const fl = this.entries.find((e) => e.type === 0);
if (!fl) throw new Error("no flash.bin in the package");
this.flashEntry = fl;
this.flashFileOff = fl.dataOff + this.skew;
this.flashSize = fl.size;
if (crc16(this.raw.subarray(this.flashFileOff, this.flashFileOff + fl.size)) !== fl.dcrc) throw new Error("flash.bin CRC mismatch");
}
parseFlash() {
const dec = this.flash.slice();
const h = dec.slice(0, 32);
enc(h, 0, 32);
if (crc16(h.subarray(2, 32)) !== u16(h, 0)) throw new Error("flash header CRC mismatch");
this.chipKey = null; this.appBase = null;
for (let off = 32; ; off += 32) {
enc(dec, off, 32);
const e = new Entry(dec, off);
if (e.name === "isd_config.ini") {
const blob = dec.subarray(e.offset, e.offset + 34);
if (crc16(blob.subarray(0, 32)) === u16(blob, 32)) this.chipKey = chipkeyDecode(blob.subarray(0, 32));
}
if (e.flags === 0x81 && e.name === "app_dir_head" && this.appBase === null) this.appBase = e.offset;
if (e.index) break;
}
if (this.chipKey === null || this.appBase === null) throw new Error("chip key or app_dir_head not found");
const b = this.appBase, k = this.chipKey, end = align32(b + 32);
sfc(dec, b, end - b, b, k);
const head = new Entry(dec, b);
const blkEnd = b + head.size;
if (blkEnd > end) sfc(dec, end, blkEnd - end, b, k);
this.sfcEnd = Math.max(end, blkEnd);
this.cfgLen = 0;
const probe = this.flash.slice(b, align32(blkEnd) + 32);
sfc(probe, 0, probe.length, 0, k);
try {
const cfg = new Entry(probe, blkEnd - b);
if (cfg.name === "cfg" && blkEnd + cfg.size <= this.flash.length) this.cfgLen = cfg.size;
} catch (_) { /* no cfg block */ }
if (this.cfgLen) {
const region = this.flash.slice(b, blkEnd + this.cfgLen);
sfc(region, 0, region.length, 0, k);
dec.set(region, b);
this.sfcEnd = blkEnd + this.cfgLen;
}
this.head = head;
this.app = null;
for (let off = b + 32; ; off += 32) {
const e = new Entry(dec, off);
if (e.flags === 0x82 && e.name === "app.bin") this.app = e;
if (e.index) break;
}
if (!this.app) throw new Error("app.bin not found in app area");
this.appOff = b + this.app.offset;
this.dec = dec;
}
// the new app, padded to the stock size (Felucca never changes the layout)
setApp(app) {
if (app.length > this.app.size) throw new Error(`app is ${app.length} B, the slot is ${this.app.size} B`);
const nw = new Uint8Array(this.app.size).fill(0xFF);
nw.set(app);
const a = this.app, h = this.head, b = this.appBase;
this.dec.set(nw, this.appOff);
a.dcrc = crc16(nw);
a.packInto(this.dec);
h.dcrc = crc16(this.dec.subarray(h.hdrOff + 32, h.hdrOff + h.size));
h.packInto(this.dec);
this.sfcEnd = Math.max(align32(b + 32), b + h.size + this.cfgLen);
const region = this.dec.slice(b, this.sfcEnd);
sfc(region, 0, region.length, 0, this.chipKey);
this.flash.set(region, b);
}
serialize() {
const out = this.raw.slice();
out.set(this.flash, this.flashFileOff);
const fl = this.flashEntry, e = fl.plain.slice();
w16(e, 4, crc16(this.flash));
enc(e, 0, 0x50);
const h = this.ufw.slice();
h.set(e, fl.off);
const hsize = 0x40 + this.nent * 0x50;
w16(h, 2, crc16(h.subarray(0x40, hsize)));
w16(h, 0, crc16(h.subarray(2, 0x40)));
enc(h, 0, 0x40);
for (let i = 0; i < hsize; i++) out[this.hdrFileOff(i)] = h[i];
return out;
}
}
// the package identity ("FM-1_904", "SMK-37 Pro_016"): one marker byte after each of the first 20 blocks
function productOf(fwsc) {
if (fwsc.length < BLOCKS * BLK) throw new Error("not an FM-1 package (too short)");
let s = "";
for (let i = 0; i < BLOCKS; i++) {
const m = fwsc[i * BLK + KEEP];
if (m !== 0x7D) s += String.fromCharCode((m - i - 1) & 0xFF);
}
return s;
}
// interleave blocks: 20, then more while the marker is the unused 0x7D (the stock SMK-37 Pro v016 has 36)
function blockCount(fwsc) {
let n = BLOCKS;
while (n < MAX_BLOCKS && (n + 1) * BLK <= fwsc.length && fwsc[n * BLK + KEEP] === 0x7D) n++;
return n;
}
function deinterleave(fwsc, blocks) {
const out = new Uint8Array(fwsc.length - blocks);
for (let i = 0; i < blocks; i++) out.set(fwsc.subarray(i * BLK, i * BLK + KEEP), i * KEEP);
out.set(fwsc.subarray(blocks * BLK), blocks * KEEP);
return out;
}
// the logical image's flash.bin (type 0) and ota.bin (type 100) match their CRCs (as fm1_install.py files_ok)
function filesOk(img) {
if (img.length < 0x40) return false;
const rd = (a, o, n) => a.slice(o, o + n).reduce((v, x, i) => v + x * 2 ** (8 * i), 0);
const h = Uint8Array.from(img.subarray(0, 0x40));
enc(h, 0, 0x40);
if (crc16(h.subarray(2, 0x40)) !== rd(h, 0, 2)) return false;
const count = rd(h, 8, 2);
if (count < 1 || count > 8 || img.length < 0x40 + 0x50 * count) return false;
for (let i = 0; i < count; i++) {
const e = Uint8Array.from(img.subarray(0x40 + i * 0x50, 0x90 + i * 0x50));
enc(e, 0, 0x50);
const typ = rd(e, 0, 2), off = rd(e, 8, 4), size = rd(e, 12, 4);
if (off + size > img.length) return false;
if ((typ === 0 || typ === 100) && crc16(img.subarray(off, off + size)) !== rd(e, 4, 2)) return false;
}
return true;
}
// where flash.bin (type 0) lies in a logical image: { off, size }, or null (no file list). For the write's
// progress (fm1ota.js WriteMeter), as tools/fm1_install.py flash_span
function flashSpan(img) {
if (img.length < 0x40) return null;
const rd = (a, o, n) => a.slice(o, o + n).reduce((v, x, i) => v + x * 2 ** (8 * i), 0);
const h = Uint8Array.from(img.subarray(0, 0x40));
enc(h, 0, 0x40);
const count = rd(h, 8, 2);
for (let i = 0; i < Math.min(count, 8) && 0x90 + i * 0x50 <= img.length; i++) {
const e = Uint8Array.from(img.subarray(0x40 + i * 0x50, 0x90 + i * 0x50));
enc(e, 0, 0x50);
const off = rd(e, 8, 4), size = rd(e, 12, 4);
if (rd(e, 0, 2) === 0 && size && off + size <= img.length) return { off, size };
}
return null;
}
// the image the device addresses during an update: the .fwsc without the marker bytes (20 blocks, or the
// detected count when the files' CRCs agree: a 20-block package can have 0x7D after block 20 by chance)
function logicalImage(fwsc) {
const n = blockCount(fwsc);
if (n !== BLOCKS) {
const img = deinterleave(fwsc, n);
if (filesOk(img) || !filesOk(deinterleave(fwsc, BLOCKS))) return img;
}
return deinterleave(fwsc, BLOCKS);
}
async function sha256hex(bytes) {
const d = await crypto.subtle.digest("SHA-256", bytes);
return [...new Uint8Array(d)].map((x) => x.toString(16).padStart(2, "0")).join("");
}
// Only the user's unmodified official firmware is accepted for a return to stock: FM-1 V15 or V16 (FM-1.fwsc) or
// SMK-37 Pro V016 (SMK-37_Pro_016.fwsc). The digest pins every file, loader and flash layout; filenames are
// not evidence. (On an SMK, Skiff stages its own loader for it: M-VAVE's must not run from Skiff's staging.)
async function validateStockPackage(bytes) {
const sha = await sha256hex(bytes);
if (bytes.length === STOCK_SMK016_SIZE && sha === STOCK_SMK016_SHA256) {
const image = logicalImage(bytes);
if (productOf(bytes) !== "SMK-37 Pro_016" || !filesOk(image))
throw new Error("The official firmware has an unsupported SMK-37 layout.");
return { product: "SMK-37 Pro_016", image, sha256: sha };
}
const L = FM1_STOCK[sha];
if (!L || bytes.length !== (L.product === "FM-1_016" ? STOCK_V16_SIZE : STOCK_V15_SIZE))
throw new Error("Select the unmodified official firmware: FM-1.fwsc (FM-1 V15 or V16) or SMK-37_Pro_016.fwsc (SMK-37 Pro V016).");
const pkg = new Package(bytes);
if (pkg.product !== L.product || pkg.flashFileOff !== 1044 || pkg.flashSize !== L.flash ||
pkg.appBase !== 16384 || pkg.appOff !== L.appOff || pkg.app.size !== L.app ||
!pkg.entries.some((e) => e.type === 100 && e.name === "ota.bin" && e.size === 19969))
throw new Error("The official firmware has an unsupported FM-1 layout.");
return { product: pkg.product, image: logicalImage(bytes), sha256: sha };
}
// official V15 + Felucca app -> installable package (Uint8Array)
async function buildFeluccaPackage(stockBytes, appBytes, product) {
const sha = await sha256hex(stockBytes);
if (sha !== STOCK_V15_SHA256) throw new Error("this is not the official FM-1 V15 firmware file (FM-1.fwsc)");
const pkg = new Package(stockBytes);
pkg.setApp(appBytes);
pkg.setProduct(product);
return pkg.serialize();
}
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments
//
// The FM-1 USB-MIDI update protocol over WebMIDI (after tools/fm1_install.py).
// Step 1: the running firmware (official
// or Felucca) reads parts of the package and stages the update loader. Step 2:
// the loader reads the whole image and writes it. Both steps are "the device
// asks, we answer": cmd 0x30 read requests on the logical image.
const HS_QUERY = [0xF0, 0x00, 0x32, 0x45, 0x00, 0x00, 0x00, 0x40, 0x7F, 0xF7];
const UPGRADE = [0xF0, 0x22, 0x24, 0x35, 0x7F, 0xF7];
const MAXDATA = 512;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const IS_OTA = (id) => /^ota-/i.test(id.model);
// two models ("ota-" aside) are exactly the same: a package installs only on its own model (the SMK-37 Pro,
// SMK-37 Elite and MKE-P37 builds each on their own model, never an FM-1 and an SMK)
const sameModel = (a, b) => a.replace(/^ota-/i, "") === b.replace(/^ota-/i, "");
// the site's package for a device's model, from [{ product, pkg }], or null (no build for that model)
const packageFor = (packages, model) => packages.find((p) => sameModel(model, p.product.split("_")[0])) || null;
// a stock SMK-37 Pro / Elite / MKE-P37 older than V016 (identity _011.._015) is updated with M-VAVE's tool first:
// the SMK port's install was verified from V016. FM-1s, Skiff (7xx), other ports (9xx) and recovery (000) pass
const SMK_MODELS = ["SMK-37 Pro", "SMK-37 Elite", "MKE-P37"];
const needsStockUpdate = (id) => SMK_MODELS.includes(id.model) && id.version > 0 && id.version < 16;
// (2.0.2, #64) why a running Skiff turned an official FM-1 file away, from where its reads stopped (firmware/src/ota.c
// ota_stage, the counts pinned by tests/ota_test.c): after the header's 2, flash.bin's size (V16's file, a Skiff before
// 2.0.2); within the boot area's 32 after the 3 before them, the head (the unit started on the other version). (2.0.3,
// #64) An SMK-37's head there is not V016's, the only SMK file the page takes: no version to name. The message's key
// (index_pkg.html), or null
function stockRefusal(product, e) {
const smk = SMK_MODELS.includes(product.split("_")[0]);
if (!e || e.code !== "stopped" || (!smk && !/^FM-1_/.test(product))) return null;
if (e.served === 2 && !smk) return "stockSkiffOld";
if (e.served >= 4 && e.served <= 35) return smk ? "stockSmkHead" : product === "FM-1_016" ? "stockNeedsV15" : "stockNeedsV16";
return null;
}
// step 2's percentage, forward only, from the flash.bin bytes served (as tools/fm1_install.py WriteMeter).
// Felucca's and Skiff's loaders read flash.bin twice, upward: a check pass, then the write pass without the
// 16 KiB head, the app's header sector last. M-VAVE's reads it once, downward. The first reads past the head
// tell which; until then it shows 0
class WriteMeter {
constructor(image) {
this.span = flashSpan(image); this.len = image.length;
this.done = 0; this.total = 0; this.pct = 0; this.seen = [];
}
add(addr, n) {
let p;
if (!this.span) p = Math.floor((addr + n) * 100 / this.len); // no file list: how far up the image
else {
const { off: lo, size } = this.span;
if (addr < lo || addr >= lo + size) return this.pct;
this.done += n;
const o = addr - lo;
if (!this.total && o >= 0x4000 && (!this.seen.length || o !== this.seen[this.seen.length - 1])) {
this.seen.push(o);
if (this.seen.length > 8) {
let up = 0;
for (let i = 1; i < this.seen.length; i++) if (this.seen[i] > this.seen[i - 1]) up++;
this.total = up * 2 > 8 ? 2 * size - 0x4000 : size;
}
}
p = this.total ? Math.floor(this.done * 100 / this.total) : 0;
}
this.pct = Math.max(this.pct, Math.min(99, p));
return this.pct;
}
}
// errors carry a code the pages translate: notfound, model, stopped, noloader, lost, noreturn,
// mismatch (detail: the identity the device reports), badreq
function fail(code, msg, detail = "") { const e = new Error(msg); e.code = code; e.detail = detail; return e; }
function pack7(data) {
const out = []; let acc = 0, nb = 0;
for (const b of data) {
acc |= b << nb; nb += 8;
while (nb >= 7) { out.push(acc & 0x7F); acc >>>= 7; nb -= 7; }
}
if (nb) out.push(acc & 0x7F);
return out;
}
function unpack7(s) {
const out = []; let acc = 0, nb = 0;
for (const b of s) {
acc |= (b & 0x7F) << nb; nb += 7;
while (nb >= 8) { out.push(acc & 0xFF); acc >>>= 8; nb -= 8; }
}
return out;
}
function response(addr, data, fl = 0) {
const len = data.length;
const body = [0x00, 0x59, 0x30, (len + 8) & 0xFF, ((len + 8) >> 8) & 0xFF, 0, fl,
addr & 0xFF, (addr >>> 8) & 0xFF, (addr >>> 16) & 0xFF, (addr >>> 24) & 0xFF,
len & 0xFF, (len >> 8) & 0xFF, 0, ...data];
let s = 0;
for (let i = 6; i < body.length; i++) s += body[i];
body.push(~s & 0xFF);
return [0xF0, ...pack7(body), 0xF7];
}
function parseRequest(pkt) {
if (pkt[0] !== 0xF0 || pkt[pkt.length - 1] !== 0xF7) return null;
const u = unpack7(pkt.slice(1, -1));
if (u.length !== 15 || u[0] !== 0 || u[1] !== 0x59 || u[2] !== 0x30) return null;
let s = 0;
for (let i = 6; i < 14; i++) s += u[i];
if ((~s & 0xFF) !== u[14]) return null;
return { fl: u[6], addr: (u[7] | (u[8] << 8) | (u[9] << 16) | (u[10] << 24)) >>> 0, len: u[11] | (u[12] << 8) | (u[13] << 16) };
}
function parseIdentity(pkt) {
const d = unpack7(pkt.slice(1, -1));
if (d.length !== 34 || d[0] !== 0 || d[1] !== 0x59 || d[2] !== 0x11) return null;
const txt = String.fromCharCode(...d.slice(6, 33)).replace(/\0+$/, "");
const m = /^([^_]+)_(\d+)$/.exec(txt);
return m ? { text: txt, model: m[1], version: parseInt(m[2], 10) } : null;
}
// one MIDI in/out pair with a SysEx queue
class Link {
constructor(input, output) {
this.input = input; this.output = output; this.q = []; this.waiter = null;
input.onmidimessage = (ev) => {
if (ev.data[0] !== 0xF0) return;
this.q.push(Array.from(ev.data));
if (this.waiter) { const w = this.waiter; this.waiter = null; w(); }
};
}
get lost() { return this.input.state === "disconnected" || this.output.state === "disconnected"; }
// false when the port is gone (unplugged): WebMIDI throws on a disconnected output
send(bytes) {
try { this.output.send(bytes); return true; } catch (_) { return false; }
}
drain() { this.q.length = 0; }
async read(ms) {
if (!this.q.length) {
let tm;
await Promise.race([new Promise((r) => { this.waiter = r; }), new Promise((r) => { tm = setTimeout(r, ms); })]);
clearTimeout(tm);
this.waiter = null;
}
return this.q.shift() || null;
}
close() { this.input.onmidimessage = null; }
}
async function handshake(link, tries = 3) {
link.drain();
for (let t = 0; t < tries; t++) {
if (!link.send(HS_QUERY)) return null;
const end = Date.now() + 1000;
while (Date.now() < end) {
const p = await link.read(end - Date.now());
if (!p) break;
const id = parseIdentity(p);
if (id) return id;
}
}
return null;
}
class Updater {
// opts.resumeWaitMs / opts.resumeMax: a write cut off (cable, power, a loader that resets or stalls) waits that
// long for the same model's loader to answer again, and is tried that many times in all
constructor(access, log, opts = {}) {
this.access = access;
this.log = log || (() => {});
this.resumeWaitMs = opts.resumeWaitMs ?? 120000;
this.resumeMax = opts.resumeMax ?? 5;
this.loaderWaitMs = opts.loaderWaitMs ?? 30000; // ((2.2) how long the update loader may take to appear)
this.seen = new Set(); // ((2.2, #83) the MIDI inputs a wait saw: said when nothing came)
}
// every in/out pair with the same port name that answers the handshake
async find(filter) {
const outs = [...this.access.outputs.values()];
for (const input of this.access.inputs.values()) {
this.seen.add(`${input.name || "?"}${input.state === "disconnected" ? " (disconnected)" : ""}`);
if (input.state === "disconnected") continue;
// never probe other gear ((2.5, #83) "FMini-1 Update": macOS's name for the SMK-37's update loader)
if (!/fm-1|fmini|smk|elite|mke-p37|starry|felucca|ota|composite|sinco|usb-midi/i.test(input.name || "")) continue;
const output = outs.find((o) => o.name === input.name && o.state !== "disconnected");
if (!output) continue;
try { await input.open(); await output.open(); } catch (_) { continue; }
const link = new Link(input, output);
const id = await handshake(link, 2);
if (id && (!filter || filter(id))) return { link, id, name: input.name };
link.close();
}
return null;
}
async waitFor(filter, ms) {
const end = Date.now() + ms;
this.seen = new Set();
while (Date.now() < end) {
const dev = await this.find(filter);
if (dev) return dev;
await sleep(1000);
}
return null;
}
// serve read requests until the device asks for one of the finish addresses; stops early
// when the port disappears (lost: true) instead of waiting out idleMs
async serve(link, image, finishAddr, idleMs, onProgress) {
let served = 0, last = Date.now();
for (;;) {
const pkt = await link.read(1000);
if (!pkt) {
if (link.lost) return { served, finished: false, lost: true };
if (Date.now() - last > idleMs) return { served, finished: false };
continue;
}
const r = parseRequest(pkt);
if (!r) continue;
last = Date.now();
if (r.addr === 0xE0000000 || r.addr === 0xF0000000) {
link.send(response(r.addr, [...new TextEncoder().encode("success"), 0]));
if (r.addr === finishAddr) return { served, finished: true };
continue;
}
if (r.len > MAXDATA || r.addr + r.len > image.length) throw fail("badreq", `bad request ${r.addr.toString(16)}+${r.len}`);
await sleep(10);
if (!link.send(response(r.addr, Array.from(image.subarray(r.addr, r.addr + r.len)), r.fl))) {
return { served, finished: false, lost: true };
}
served++;
if (onProgress) onProgress(served, r.addr, r.len);
}
}
// full install: running firmware -> loader -> new firmware
async install(image, product, onStep) {
const step = onStep || (() => {});
const [model] = product.split("_"); // the package's model first: an FM-1 and an SMK can share a computer
const dev = await this.find((id) => !IS_OTA(id) && sameModel(id.model, model)) || await this.find((id) => !IS_OTA(id));
if (!dev) throw fail("notfound", "FM-1 or SMK-37 not found (USB cable, and no other app using it?)");
if (!sameModel(dev.id.model, model)) { dev.link.close(); throw fail("model", `the device is ${dev.id.text}, the package is for ${product}`); }
step("start", dev.id.text);
dev.link.send(UPGRADE);
await sleep(2000);
const s1 = await this.serve(dev.link, image, 0xE0000000, 8000, (n) => step("verify", n));
dev.link.close();
if (!s1.finished) {
const e = fail(s1.lost ? "lost" : "stopped", `the device ${s1.lost ? "was disconnected" : "stopped"} after ${s1.served} requests: nothing was written`);
e.served = s1.served; // ((2.0.2) where it stopped: stockRefusal)
throw e;
}
step("loader");
await sleep(3000);
const ota = await this.waitFor((id) => id.model === "ota-" + model, this.loaderWaitMs);
if (!ota) { // ((2.2, #83) what the computer showed meanwhile, for a report)
const seen = this.seen.size ? ` (MIDI ports seen: ${[...this.seen].join(", ")})` : " (no MIDI ports seen)";
throw fail("noloader", "the update loader did not appear. Replug the USB cable and press Install again: the device stays in update mode until it is finished." + seen, seen);
}
const s2 = await this.writeResuming(ota, image, model, step);
if (!s2.finished) throw fail(s2.lost ? "lost" : "stopped", `the loader ${s2.lost ? "was disconnected" : "stopped"} after ${s2.served} requests. Replug and press Install again to resume.`);
step("reboot");
await sleep(3000);
const back = await this.waitFor((id) => !IS_OTA(id) && sameModel(id.model, model), 40000);
if (!back) throw fail("noreturn", "the device did not come back: power-cycle it");
back.link.close();
if (back.id.text !== product) throw fail("mismatch", `installed, but the device reports ${back.id.text}`, back.id.text);
step("done", back.id.text);
return back.id.text;
}
// step 2 with the loader found by find()/waitFor(); step("write", percent), forward only
async write(ota, image, step) {
ota.link.send(UPGRADE);
await sleep(2000);
const meter = new WriteMeter(image);
const s2 = await this.serve(ota.link, image, 0xF0000000, 180000, (n, addr, len) => step("write", meter.add(addr, len)));
ota.link.close();
return s2;
}
// step 2, resumed after a drop: the update record keeps the device in update mode and the loader writes the
// app's header last, so writing again once the same model's loader answers is always safe.
// step("dropped") while it waits, step("resume", try) when it goes on
async writeResuming(ota, image, model, step) {
let s = await this.write(ota, image, step);
for (let t = 2; !s.finished && t <= this.resumeMax; t++) {
step("dropped");
const back = await this.waitFor((id) => IS_OTA(id) && sameModel(id.model, model), this.resumeWaitMs);
if (!back) break;
step("resume", t);
s = await this.write(back, image, step);
}
return s;
}
// resume: the device is already in update mode (loader) -> true when the write finished. product: the
// package's identity; the loader's model must be exactly the package's (sameModel, as install()): an SMK's
// loader never gets an FM-1 image nor another model's, and without the identity nothing is written
async resume(image, onStep, product = "") {
const model = (product || "").split("_")[0];
const ota = await this.find(IS_OTA);
if (!ota) return false;
if (!product || !sameModel(ota.id.model, model)) {
ota.link.close();
throw fail("model", `the device is in the update mode of ${ota.id.text}, the package is for ${product || "an unknown model"}`, ota.id.text);
}
const step = onStep || (() => {});
const result = await this.writeResuming(ota, image, model, step);
if (!result.finished) return false;
if (product) {
step("reboot");
await sleep(3000);
const back = await this.waitFor((id) => !IS_OTA(id) && sameModel(id.model, model), 40000);
if (!back) throw fail("noreturn", "The device did not return after resuming the write.");
back.link.close();
if (back.id.text !== product) throw fail("mismatch", "The device reports a different firmware after resuming.", back.id.text);
step("done", back.id.text);
}
return true;
}
}
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments
// Local, complete musical archives. Requests name whitelisted objects, never flash addresses.
// 8: the FM6 patch bank of 1.0..1.0.2 (listed empty since 1.0.3: a restore of an older archive's bank moves its patches
// into the user presets restored before it); 9: the user presets' FM6 patches (1.0.3); 16..31: Skiff's pattern bank,
// a chunk of 4 patterns each (3552 bytes, 0 when all empty)
const BANK_IDS = Array.from({ length: 16 }, (_, i) => 16 + i);
const BACKUP_IDS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...BANK_IDS, 32, 33, 34];
const BACKUP_IDS_V3 = BACKUP_IDS.filter((id) => id < 16 || id >= 32); // Felucca 1.0.3.. (no bank), and its archives
const BACKUP_IDS_V2 = BACKUP_IDS_V3.filter((id) => id !== 9); // 1.0..1.0.2, and their archives
const BACKUP_IDS_V1 = BACKUP_IDS_V2.filter((id) => id !== 8); // firmware before FM6, and its archives
const idsOf = (n) => [BACKUP_IDS, BACKUP_IDS_V3, BACKUP_IDS_V2, BACKUP_IDS_V1].find((ids) => ids.length === n) || null;
const BACKUP_CMD = { LIST: 65, GET: 66, PUT: 67 };
const BACKUP_CHUNK = 256;
const bkU32 = (n) => Array.from({ length: 5 }, (_, i) => (n >>> (i * 7)) & (i === 4 ? 15 : 127));
const bkR32 = (a, off = 0) => {
if (a.length < off + 5 || a[off + 4] > 15) throw new Error("Invalid archive number");
return (a[off] | a[off + 1] << 7 | a[off + 2] << 14 | a[off + 3] << 21 | a[off + 4] << 28) >>> 0;
};
function bkPack(bytes) {
const a = [];
for (let off = 0; off < bytes.length; off += 7) {
const chunk = bytes.subarray(off, off + 7);
a.push(chunk.reduce((m, b, i) => m | (b >>> 7) << i, 0), ...chunk.map((b) => b & 127));
}
return a;
}
function bkUnpack(a, size) {
const out = new Uint8Array(size); let i = 0, j = 0;
while (j < size) {
const n = Math.min(7, size - j), mask = a[i++];
if (mask == null || mask >>> n) throw new Error("Invalid archive bytes");
for (let k = 0; k < n; k++) {
if (a[i] == null || a[i] > 127) throw new Error("Short archive chunk");
out[j++] = a[i++] | (mask >>> k & 1) << 7;
}
}
if (i !== a.length) throw new Error("Trailing archive bytes");
return out;
}
function bkCrc(bytes) {
let c = 0xffffffff;
for (const b of bytes) {
c ^= b;
for (let k = 0; k < 8; k++) c = c >>> 1 ^ (c & 1 ? 0xedb88320 : 0);
}
return (~c) >>> 0;
}
function bkCheck(rc) {
if (rc) throw new Error(({ 1: "Invalid archive object", 2: "Archive data failed validation", 3: "Stop playback first", 4: "Flash write failed", 5: "Start a fresh backup" })[rc] || `Archive error ${rc}`);
}
function bkManifest(a) {
if (a[0] !== 1) throw new Error("Unsupported archive protocol");
bkCheck(a[1]);
const ids = idsOf(a[2]);
if (!ids || a.length !== 3 + a[2] * 11) throw new Error("Incomplete archive manifest");
return ids.map((id, i) => {
const p = 3 + i * 11;
if (a[p] !== id) throw new Error("Unexpected archive object");
const size = bkR32(a, p + 1), crc = bkR32(a, p + 6);
if (size > (id >= 32 ? 81920 : 3840) || (!size && crc)) throw new Error("Archive object too large");
return { id, size, crc };
});
}
const bkBase64 = (bytes) => { let s = ""; for (const b of bytes) s += String.fromCharCode(b); return btoa(s); };
function readBackup(file) {
if (typeof file === "string") file = JSON.parse(file);
const ids = file && Array.isArray(file.objects) ? idsOf(file.objects.length) : null;
if (!file || file.format !== "felucca-backup" || file.version !== 1 || !ids)
throw new Error("Not a complete Felucca backup");
const objects = file.objects.map((o, i) => {
if (!o || o.id !== ids[i] || !Number.isInteger(o.size) || o.size < 0 || o.size > (o.id >= 32 ? 81920 : 3840) ||
!Number.isInteger(o.crc) || o.crc < 0 || o.crc > 0xffffffff || typeof o.data !== "string" ||
o.data.length !== 4 * Math.ceil(o.size / 3) || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(o.data))
throw new Error("Invalid backup object");
const bytes = Uint8Array.from(atob(o.data), (c) => c.charCodeAt(0));
if (bytes.length !== o.size || bkCrc(bytes) !== o.crc) throw new Error("Backup checksum mismatch");
if (o.id >= 32 && o.size) {
if (o.size < 512) throw new Error("Short sample backup");
const view = new DataView(bytes.buffer), length = view.getUint32(16, true), count = bytes[6];
if (view.getUint32(0, true) !== 0x504d5346 || view.getUint16(4, true) !== 1 || !count || count > 16 ||
length !== o.size - 512 || bkCrc(bytes.subarray(512)) !== view.getUint32(20, true)) throw new Error("Invalid sample backup");
for (let z = 0; z < count; z++) {
const off = 32 + z * 28, start = view.getUint32(off,true), n = view.getUint32(off+4,true),
ls = view.getUint32(off+8,true), le = view.getUint32(off+12,true), rate = view.getUint32(off+16,true);
if (!n || start > length || Math.ceil(n/2) > length - start || n > 163840 || ls > le || le >= n ||
!rate || rate > 262144 || bytes[off+24] > 88 || bytes[off+25] > bytes[off+26]) throw new Error("Invalid sample zone");
}
}
return { ...o, bytes };
});
if (!objects[0].size || !objects[1].size) throw new Error("Backup is missing the current music or settings");
return { ...file, objects };
}
async function captureBackup(request, firmware, onProgress = () => {}) {
const manifest = bkManifest(await request([BACKUP_CMD.LIST, []], { timeout: 3000, retries: 0 }));
const objects = [], total = manifest.reduce((n, o) => n + o.size, 0); let done = 0;
for (const o of manifest) {
const bytes = new Uint8Array(o.size);
for (let off = 0; off < o.size; off += BACKUP_CHUNK) {
const size = Math.min(BACKUP_CHUNK, o.size - off);
const a = await request([BACKUP_CMD.GET, [o.id, ...bkU32(off), size & 127, size >>> 7]], { timeout: 1000, retries: 1 });
bkCheck(a[1]);
if (a[0] !== o.id || bkR32(a, 2) !== off || (a[7] | a[8] << 7) !== size) throw new Error("Unexpected backup reply");
bytes.set(bkUnpack(a.slice(9), size), off);
done += size; onProgress(done, total);
}
if (bkCrc(bytes) !== o.crc) throw new Error("The device changed during backup. Try again while stopped.");
objects.push({ ...o, data: bkBase64(bytes) });
}
const file = { format: "felucca-backup", version: 1, firmware, created: new Date().toISOString(), objects };
readBackup(file); return file;
}
// (Skiff 2.0) only: the ids to write (the installer's write-back of converted objects, web/conv/conv.js); the others
// stay as the unit has them. In the same order.
async function restoreBackup(request, file, onProgress = () => {}, only = null) {
const archive = readBackup(file); // Validate every byte before the first destructive request.
const pick = (o) => !only || only.includes(o.id);
const total = archive.objects.filter(pick).reduce((n, o) => n + o.size, 0); let done = 0;
const ask = async (r, o = {}) => request(r, { timeout: 4000, retries: 0, ...o });
const put = async (args) => { const a = await ask([BACKUP_CMD.PUT, args]); bkCheck(a[2]); return a; };
// Restore live music last. Other objects commit individually; a disconnect can leave a partial restore.
for (const o of [...archive.objects.slice(2), archive.objects[1], archive.objects[0]].filter(pick)) {
if (o.id >= 32) {
const slot = o.id - 32;
const check = (a) => { if (a[0] !== slot) throw new Error("Unexpected sample reply"); bkCheck(a.at(-1)); };
if (!o.size) check(await ask([14, [slot]]));
else {
if (o.size < 512) throw new Error("Short sample backup");
check(await ask([11, [slot]]));
for (let off = 512; off < o.size; off += BACKUP_CHUNK) {
const chunk = o.bytes.subarray(off, off + BACKUP_CHUNK);
check(await ask([12, [slot, off & 127, off >>> 7 & 127, off >>> 14 & 127, ...bkPack(chunk)]]));
done += chunk.length; onProgress(done, total);
}
check(await ask([13, [slot, ...bkPack(o.bytes.subarray(0, 480))]]));
done += 512; onProgress(done, total);
}
} else {
if (o.id === 9 || BANK_IDS.includes(o.id)) { // firmware before 1.0.3 does not take id 9, firmware without Skiff's
// bank not 16..31 (rc 1 at begin, nothing written): skip them
const a = await ask([BACKUP_CMD.PUT, [0, o.id, ...bkU32(o.size), ...bkU32(o.crc)]]);
if (a[2] === 1) { done += o.size; onProgress(done, total); continue; }
bkCheck(a[2]);
} else await put([0, o.id, ...bkU32(o.size), ...bkU32(o.crc)]);
try {
for (let off = 0; off < o.size; off += BACKUP_CHUNK) {
const chunk = o.bytes.subarray(off, off + BACKUP_CHUNK);
await put([1, o.id, ...bkU32(off), ...bkPack(chunk)]);
done += chunk.length; onProgress(done, total);
}
await put([2, o.id]);
} catch (e) { await put([3, o.id]).catch(() => {}); throw e; }
}
}
return archive;
}
// Installer connection: no editor page or watcher owns this input simultaneously.
class BackupConnection {
constructor(input, output) {
this.input = input; this.output = output; this.pending = null;
input.onmidimessage = (e) => {
const d = e.data;
if (d.length < 6 || d[0] !== 240 || d[1] !== 125 || d[2] !== 70 || d[3] !== 76 || d.at(-1) !== 247) return;
if (this.pending?.cmd === d[4]) { const p = this.pending; this.pending = null; clearTimeout(p.timer); p.resolve(Array.from(d.slice(5, -1))); }
};
}
async request([cmd, args], opt = {}) {
if (this.pending || this.closed || this.input.state === "disconnected" || this.output.state === "disconnected") throw new Error("Backup connection closed or busy");
return new Promise((resolve, reject) => {
const timer = setTimeout(() => { this.pending = null; reject(Object.assign(new Error("Backup timed out. Keep the FM-1 connected and stopped."), { code: "timeout" })); }, opt.timeout || 1200);
this.pending = { cmd, timer, resolve, reject };
try { this.output.send([240, 125, 70, 76, cmd, ...args, 247]); }
catch (e) { clearTimeout(timer); this.pending = null; reject(e); }
});
}
close() {
this.closed = true; this.input.onmidimessage = null;
if (this.pending) { const p = this.pending; this.pending = null; clearTimeout(p.timer); p.reject(new Error("Backup connection closed")); }
}
}
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments
// (Skiff 2.0, Tier B: design/TIER_B.md 10) The converter in the page: an archive of before (web/fm1backup.js) into
// what 2.0 reads, by conv.wasm (web/conv/conv.c: the firmware's own code over a simulated flash).
// const conv = await loadConverter(wasmBytesOrUrl);
// const { archive, report, writeBack } = conv.convert(readBackup(file));
// archive: a complete 2.0 archive (29 objects); writeBack: the ids whose bytes changed, which 2.0 couldn't read as they
// were or the conversion filled (pattern chunks, the user presets' patches): the installer writes back only those;
// report: a line per object (what it was, what it is now, kept / converted / refused; note: what had no place in 2.0,
// felucca.c conv_note). Refused: damaged (the unit refuses it too: a restore leaves it out); "kept as it was: the
// patterns are full": an old project no free pattern could take, which a 2.0 unit keeps whole (OLD FORMAT) for later. An archive without the pattern bank is Felucca's (or Skiff's before it): its user presets of
// Felucca 1.2+ are mapped by name (conv_source).
const CONV_MAGICS = { 0x534B4634: "SKF4", 0x534B4633: "SKF3", 0x534B4632: "SKF2", 0x534B4631: "SKF1", 0x46554E41: "FUNA" };
for (let v = 1; v <= 9; v++) CONV_MAGICS[0x46554E30 + v] = `FUN${v}`;
const convU32 = (b, o) => (b[o] | b[o + 1] << 8 | b[o + 2] << 16 | b[o + 3] << 24) >>> 0;
/* what an object holds, in a word or two (the report) */
function convKind(id, b) {
if (!b || !b.length) return "empty";
if (id >= 32) return "samples";
if (id >= 16) return "patterns";
if (id === 0 || id <= 5 && id >= 2) return CONV_MAGICS[convU32(b, 0)] || "unknown";
if (id === 1) return { 0x534B5331: "SKS1", 0x50455234: "PER4" }[convU32(b, 0)] || "unknown";
if (id === 6 || id === 7) {
const v = {};
for (let i = 0; i < 16; i++) if (b[8 + i * 192] === 0xA5) { const k = `v${b[9 + i * 192]}`; v[k] = (v[k] || 0) + 1; }
return Object.keys(v).sort().map((k) => `${v[k]} ${k}`).join(", ") || "none used";
}
if (id === 8) return "FM6 bank (1.0-1.0.2)";
return id === 9 ? "FM6 patches" : "unknown";
}
const sameBytes = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
const convBase64 = (bytes) => { let s = ""; for (const x of bytes) s += String.fromCharCode(x); return btoa(s); };
async function loadConverter(src) {
const bytes = typeof src === "string" ? new Uint8Array(await (await fetch(src)).arrayBuffer()) : src;
const { instance } = await WebAssembly.instantiate(bytes, {});
const x = instance.exports;
x._initialize?.();
const buf = () => new Uint8Array(x.memory.buffer, x.conv_buf(), 81920);
return {
convert(archive) {
const input = new Map(archive.objects.map((o) => [o.id, o]));
const bytesOf = (id) => input.get(id)?.bytes || new Uint8Array(0);
const rc = new Map();
x.conv_reset();
x.conv_source(archive.objects.length < BACKUP_IDS.length ? 1 : 0);
for (const id of [...archive.objects.slice(2).map((o) => o.id), 1, 0]) { // (restoreBackup's order: the music last)
const b = bytesOf(id);
if (id >= 32 || !b.length) continue;
buf().set(b);
rc.set(id, x.conv_put(id, b.length));
}
x.conv_fix();
const objects = [], report = [], writeBack = [];
for (const id of BACKUP_IDS) {
const was = bytesOf(id);
let now = was, what = "kept";
if (id < 32) {
const conv = buf().slice(0, x.conv_get(id));
const left = !!x.conv_needs(id, conv.length); // (still a format of before: no pattern was free for its steps)
buf().set(was);
const needs = !!x.conv_needs(id, was.length), r = rc.get(id);
if (needs && (r === 4 || (r === 0 && left))) what = "kept as it was: the patterns are full";
else if (needs && r !== 0) what = "refused, kept as it was";
else if (needs || (id === 8 || id === 9 || id >= 16) && !sameBytes(conv, was)) { now = conv; what = was.length ? "converted" : "added"; }
}
if (now !== was) writeBack.push(id);
const n = x.conv_note(id), note = n ? String.fromCharCode(...buf().subarray(0, n)) : "";
report.push({ id, was: convKind(id, was), now: convKind(id, now), what, ...(note ? { note } : {}) });
const kept = now === was && input.get(id);
objects.push(kept ? { id, size: kept.size, crc: kept.crc, data: kept.data, bytes: was }
: { id, size: now.length, crc: bkCrc(now), data: convBase64(now), bytes: now });
}
return {
archive: { format: "felucca-backup", version: 1, firmware: archive.firmware, created: archive.created, objects },
report, writeBack,
};
},
};
}
const $ = (id) => document.getElementById(id);
const TEXT = {
ja: {
intro: "FM-1 または SMK-37 を USB で接続してください。(Chrome か Edge で使えます)",
warn: "書き込み中は USB を抜かず、電源も切らないでください。途中で切れても書き込みモードのまま残るので、挿し直す(電源を入れる)と続きから再開します。",
install: "インストール", other: "English",
editor: "エディタ(インストール後、パソコンから音色やシーケンスを編集)",
learn: "Learn Skiff(使い方ガイド。章ごとに解説動画つき・英語のみ)",
direct: "USB ケーブルはパソコンに直接つないでください。Probe や Transporter などの機材は不要です。",
brick: "FM-1 で万一インストールに失敗して起動しなくなった場合は、復旧に Transporter が必要です:",
smk: "SMK-37 Pro は Skiff に新しく対応した機種です。インストール前にバックアップと公式への戻し方をお読みください:",
beta: "Skiff はカスタムファームウェアです。不具合は GitHub で知らせてください。このカスタムファームウェアを使ったことで機器が壊れたり不具合が起きたりしても、作者は一切の責任を負いません。自己責任でお使いください。",
back: "M-VAVE から公式ファームウェア(FM-1 は Skiff の前に入っていた版で V15 か V16、SMK-37 Pro は V016)を取得し、未変更の FM-1.fwsc または SMK-37_Pro_016.fwsc を選んでください。M-VAVE のダウンロードページは現在 V16 です。V15 は M-VAVE の fm1_open リポジトリ(sdk/firmware/FM-1_015.fwsc)にあります。ファイルはこのブラウザ内で検証し、サーバーへ送りません。",
stockTitle: "公式ファームウェアに戻す", stockFile: "公式 FM-1.fwsc(V15 または V16)または SMK-37_Pro_016.fwsc", stockGo: "バックアップして公式ファームウェアへ戻す",
stockBackup: "現在の曲・保存曲・音色バンク・サンプル・設定を先に保存します。全体バックアップ非対応版は、Skiff を更新してから行ってください。復元は Skiff を再インストールしてエディタから行います。",
stockRecovery: "更新中断の再開:全体バックアップはすでにパソコンへ保存済み",
stockValid: "公式ファームウェアを確認しました: ", stockConfirm: "全体バックアップファイルをパソコンに保存できましたか? 続けると公式ファームウェアへ戻します。Skiff の曲は公式ファームウェアでは開けません。",
stockNeedBackup: "書き込みモードからはバックアップできません。保存済みバックアップがある場合だけ、更新中断の再開にチェックしてください。",
stockUnsupported: "このファームウェアは Skiff の全体バックアップを作れません。古い Skiff なら先に最新版をインストールしてください。他のファームウェアから戻すには M-VAVE のアップデーターを使ってください。",
stockIsStock: "この機器はすでにその公式ファームウェアです。",
stockNotSkiff: "この機器は Skiff ではないため、バックアップする Skiff の曲はありません。他のファームウェアから戻すには M-VAVE のアップデーターを使ってください。機器の報告: ",
saved20: "Skiff 2.0 は、それより前のファームウェアで保存したデータをそのままでは開けません。先にこの機器の全体バックアップをこのパソコンに保存しました(Skiff-backup-....json)。これが元に戻す方法です: 今のファームウェアを入れ直し、エディタで復元します。Skiff 2.0 をインストールしますか?",
converting: "前のファームウェアで保存したデータを 2.0 用に変換中 ",
converted: "完了。前のファームウェアで保存したデータを 2.0 用に変換しました(下に一覧)。",
asIs: "完了。この機器のデータはそのまま 2.0 で開けます。",
convertedPart: "完了しましたが、前のファームウェアで保存したデータの一部はそのままです(下に一覧)。本体では OLD FORMAT と表示されます。空きパターンが足りなかったプロジェクトは、SAVE > PATTERNS で空けてからエディタでバックアップし、それを復元すると変換されます。",
convertFailed: "インストールは完了しましたが、前のデータの変換に失敗しました。保存したバックアップをエディタで復元してください(復元時に変換されます)。",
stockWrongModel: "選んだファイルは、接続している機器とは別の機種用です。",
stockSkiffOld: "書き込みはしていません。この Skiff はその公式版にまだ対応していません。最新の Skiff をインストールしてから、公式ファームウェアに戻してください。",
stockNeedsV16: "書き込みはしていません。この FM-1 の起動部は V16 のものです(Skiff の前は V16 でした)。戻せるのは V16 です。M-VAVE の現在の FM-1.fwsc(V16)を選んでください。",
stockNeedsV15: "書き込みはしていません。この FM-1 の起動部は V15 のものです(Skiff の前は V15 でした)。戻せるのは V15 です。M-VAVE の fm1_open リポジトリ(sdk/firmware)の FM-1_015.fwsc を選んでください。その後 M-VAVE の M-UPGRADE で V16 にできます。",
stockSmkHead: "書き込みはしていません。Skiff はそのまま使えます。このキーボードの起動部は V016 のものではありません(別の版で出荷されたか、Skiff の前のファームウェアが書き換えました)。そのため V016 には戻せません。Skiff が動いている間は、M-VAVE のアップデーターでも同じ確認で止まります。Skiff の前に何が入っていたかを、Skiff の GitHub で教えてください。",
backup: "全体バックアップ保存中 ", stockError: "公式ファイルを確認できません: ",
nomidi: "このブラウザでは使えません。Chrome か Edge で開いてください。", loadfail: "読み込めませんでした: ",
start: "開始します", verify: "確認中", loader: "書き込みモードに切り替え中", write: "書き込み中",
reboot: "再起動中", done: "完了しました", stopped: "途中で止まりました。USB を挿し直してもう一度押してください。",
dropped: "接続が切れました。書き込みモードのまま残っています。USB を挿し直す(または電源を入れる)と続きから再開します。待機中…",
resume: "書き込みを再開しています。試行 ",
error: "エラー: ",
denied: "MIDI(SysEx)の使用が許可されませんでした。アドレスバーのサイト設定で MIDI を許可して、もう一度押してください。",
notfound: "FM-1 / SMK-37 が見つかりません。USB ケーブル(データ通信用か)を確かめ、MIDI を使う他のアプリを閉じてから、もう一度押してください。",
model: "接続されている機器は、このファイルの機種ではありません。",
nopkg: "この機器向けの Skiff はありません。機器の報告: ",
needV016: "この SMK-37 は V016 より古い M-VAVE 公式ファームウェアです。先に M-VAVE のアップデーター(M-UPGRADE)で V016 に更新してから、Skiff をインストールしてください。機器の報告: ",
lost: "USB の接続が切れました。挿し直してもう一度押してください。",
noloader: "書き込みモードの機器が見つかりません。USB をハブや USB 共有ソフトを通さずパソコンに直接挿し直して、もう一度押してください(終わるまで書き込みモードのままです)。",
noreturn: "機器が戻ってきません。電源を入れ直してください。",
mismatch: "書き込みは終わりましたが、機器が別のバージョンを報告しています: ",
badpkg: "インストールするファイルが壊れています。ページを再読み込みしてください。",
leave: "書き込み中です。ページを閉じないでください。",
license: "GPL-3.0、無保証。ソース:",
},
en: {
intro: "Connect the FM-1 or SMK-37 by USB. (Works in Chrome or Edge.)",
warn: "Keep it plugged in and switched on while it writes. If the cable or the power is cut, it stays in update mode: plug it back in (or switch it on) and the install carries on.",
install: "Install", other: "日本語",
editor: "Editor (after installing: edit sounds and sequences from the computer)",
learn: "Learn Skiff (the manual, with a video for every chapter)",
direct: "Connect the USB cable directly to the computer. No probe or Transporter is needed.",
brick: "If an install fails on an FM-1 and it no longer starts, recovering it needs a Transporter:",
smk: "The SMK-37 Pro is new to Skiff. Before installing, read about the backup and the way back to stock:",
beta: "Skiff is custom firmware; please report problems on GitHub. The author accepts no responsibility if your keyboard is damaged or misbehaves because of this custom firmware. Use it at your own risk.",
back: "Get the official firmware from M-VAVE (FM-1: the version it had before Skiff, V15 or V16; SMK-37 Pro: V016) and select the unmodified FM-1.fwsc or SMK-37_Pro_016.fwsc. M-VAVE's download page now has V16; V15 is in M-VAVE's fm1_open repository (sdk/firmware/FM-1_015.fwsc). The browser validates it locally; it is not sent to a server.",
stockTitle: "Return to the official firmware", stockFile: "Official FM-1.fwsc (V15 or V16) or SMK-37_Pro_016.fwsc", stockGo: "Back up and return to the official firmware",
stockBackup: "Current music, saved music, sound banks, samples and settings are saved first. Older firmware needs a Skiff update for complete backups. To restore an archive later, reinstall Skiff and use the editor.",
stockRecovery: "Resume an interrupted update: I already saved a complete backup to this computer",
stockValid: "Official firmware verified: ", stockConfirm: "Has the complete backup file been saved to this computer? Continue to return to the official firmware. The official firmware cannot open Skiff music.",
stockNeedBackup: "An update loader cannot export a backup. Only select resume if you already saved a complete backup.",
stockUnsupported: "This firmware cannot make a complete Skiff backup. An older Skiff: install the current Skiff first. Another firmware: return with M-VAVE's updater.",
stockIsStock: "This keyboard already runs that official firmware.",
stockNotSkiff: "This keyboard is not running Skiff, so there is no Skiff music to back up. To return from another firmware, use M-VAVE's updater. It reports: ",
saved20: "Skiff 2.0 opens nothing that firmware before it saves: a complete backup of this unit was saved to this computer first (Skiff-backup-....json). It is the way back: install your firmware of now, then restore it in the editor. Install Skiff 2.0?",
converting: "Converting what the firmware before saved, for 2.0 ",
converted: "Done. What the firmware before saved was converted for 2.0 (the list below).",
asIs: "Done. Everything this unit had opens in 2.0 as it is.",
convertedPart: "Done, but some of what the firmware before saved stays as it was (the list below): the unit shows it as OLD FORMAT. A project no free pattern could take converts once you free some (SAVE > PATTERNS), take a backup in the editor and restore it.",
convertFailed: "Installed, but converting what the firmware before saved failed: restore the saved backup in the editor, which converts it. ",
stockWrongModel: "The selected file is for another model than the connected keyboard.",
stockSkiffOld: "Nothing was written. This Skiff can't take that official version yet: install the current Skiff first, then return to the official firmware.",
stockNeedsV16: "Nothing was written. This FM-1's start-up part is V16's (it ran V16 before Skiff), so its way back is V16: select M-VAVE's current FM-1.fwsc (V16).",
stockNeedsV15: "Nothing was written. This FM-1's start-up part is V15's (it ran V15 before Skiff), so its way back is V15: select FM-1_015.fwsc from M-VAVE's fm1_open repository (sdk/firmware). M-VAVE's M-UPGRADE can take it to V16 afterwards.",
stockSmkHead: "Nothing was written, and Skiff runs as before. This keyboard's start-up part is not V016's (it came with another, or a firmware before Skiff rewrote it), so V016 can't go back on it; while Skiff runs, M-VAVE's own updaters stop at the same check. Please tell us on Skiff's GitHub what the keyboard ran before Skiff.",
backup: "Saving complete backup ", stockError: "Cannot validate official firmware: ",
nomidi: "This browser cannot do it. Open the page in Chrome or Edge.", loadfail: "Could not load: ",
start: "Starting", verify: "Verifying", loader: "Switching to update mode", write: "Writing",
reboot: "Restarting", done: "Done", stopped: "Stopped. Replug the USB cable and press Install again.",
dropped: "The connection dropped. The keyboard stays in update mode: plug the cable back in (or switch it back on) and the install carries on. Waiting…",
resume: "Resuming the write, try ",
error: "Error: ",
denied: "MIDI (SysEx) access was not allowed. Allow MIDI in the site settings (address bar) and press Install again.",
notfound: "No FM-1 or SMK-37 found. Check the USB cable (a data cable), close other apps that use MIDI, and press Install again.",
model: "The connected keyboard is not the model this file is for.",
nopkg: "There is no Skiff for this keyboard. It reports: ",
needV016: "This SMK-37 runs M-VAVE's firmware older than V016. Update it to V016 with M-VAVE's own updater (M-UPGRADE) first, then install Skiff. It reports: ",
lost: "The USB connection was lost. Replug it and press Install again.",
noloader: "The keyboard in update mode was not found. Replug the USB cable straight into the computer (not through a hub or USB-sharing software) and press Install again (it stays in update mode until it is finished).",
noreturn: "The keyboard did not come back. Power-cycle it.",
mismatch: "Written, but the keyboard reports another version: ",
badpkg: "The file to install is damaged. Reload the page.",
leave: "Writing. Do not close the page.",
license: "GPL-3.0, no warranty. Source:",
},
};
let lang = (navigator.language || "en").toLowerCase().startsWith("ja") ? "ja" : "en";
const t = (k) => TEXT[lang][k];
let lastKey = null, lastArg = "";
function applyLang() {
document.documentElement.lang = lang;
document.querySelectorAll("[data-t]").forEach((e) => { e.textContent = t(e.dataset.t); });
$("lang").textContent = t("other");
if (lastKey) $("status").textContent = t(lastKey) + lastArg;
}
$("lang").addEventListener("click", () => { lang = lang === "ja" ? "en" : "ja"; applyLang(); });
applyLang();
const sayK = (k, arg = "") => { lastKey = k; lastArg = arg; $("status").textContent = t(k) + arg; };
const say = (txt) => { lastKey = null; $("status").textContent = txt; };
const log = (t) => { $("log").textContent += t + "\n"; };
const meta = {"version": "2.5", "product": "FM-1_725", "pkg": "../../firmware/skiff-2.5.fwsc", "packages": [{"product": "FM-1_725", "pkg": "../../firmware/skiff-2.5.fwsc"}, {"product": "SMK-37 Pro_725", "pkg": "../../firmware/skiff-2.5-smk37.fwsc"}, {"product": "SMK-37 Elite_725", "pkg": "../../firmware/skiff-2.5-smk37-elite.fwsc"}, {"product": "MKE-P37_725", "pkg": "../../firmware/skiff-2.5-smk37-mke.fwsc"}]};
// one package per model ({ product, pkg }); a site made before the SMK builds carries only product + pkg
const packages = meta.packages || [{ product: meta.product, pkg: meta.pkg }];
const images = new Map(); // product -> logical image, loaded on first use
let writing = false, stock = null, stockFileEpoch = 0;
const lockInstaller = (on) => { writing = on; $("go").disabled = on || !navigator.requestMIDIAccess; $("stock-go").disabled = on || !stock; $("stock-file").disabled = on; $("stock-recovery").disabled = on; };
window.addEventListener("beforeunload", (e) => { if (writing) { e.preventDefault(); e.returnValue = t("leave"); } });
if (!navigator.requestMIDIAccess) sayK("nomidi");
else { say(`Skiff ${meta.version}`); $("go").disabled = false; }
async function imageFor(entry) {
if (images.has(entry.product)) return images.get(entry.product);
const r = await fetch(entry.pkg);
if (!r.ok) throw Object.assign(new Error(`${entry.pkg}: HTTP ${r.status}`), { code: "loadfail" });
const pkg = new Uint8Array(await r.arrayBuffer());
if (productOf(pkg) !== entry.product) throw Object.assign(new Error(entry.product), { code: "badpkg" });
const image = logicalImage(pkg);
images.set(entry.product, image);
return image;
}
// the bar: the running firmware's check takes the first 5 %, the loader's write (forward only) the rest
const stepper = () => (k, a) => {
log(`${k} ${a ?? ""}`);
if (k === "start") sayK("start");
if (k === "verify") { sayK("verify"); $("bar").value = Math.min(5, a * 5 / 80); }
if (k === "loader") sayK("loader");
if (k === "write") { if (lastKey !== "write") sayK("write"); $("bar").value = 5 + a * 0.95; }
if (k === "dropped") sayK("dropped");
if (k === "resume") sayK("resume", `${a}`);
if (k === "reboot") sayK("reboot");
if (k === "done") { $("bar").value = 100; sayK("done"); }
};
$("go").addEventListener("click", async () => {
if (writing) return;
lockInstaller(true);
let midi;
try { midi = await navigator.requestMIDIAccess({ sysex: true }); }
catch (e) { sayK("denied"); lockInstaller(false); return; }
try {
const up = new Updater(midi, log);
const dev = await up.find();
if (!dev) { sayK("notfound"); return; }
dev.link.close();
const entry = packageFor(packages, dev.id.model);
if (!entry) { sayK("nopkg", dev.id.text); return; }
if (!IS_OTA(dev.id) && needsStockUpdate(dev.id)) { sayK("needV016", dev.id.text); return; }
const image = await imageFor(entry);
const step = stepper();
if (IS_OTA(dev.id)) { sayK((await up.resume(image, step, entry.product)) ? "done" : "stopped"); return; }
const model = entry.product.split("_")[0];
const archive = await backupBefore(up, model); // ((2.0) over firmware before it: the backup first, the way back)
if (archive && !confirm(t("saved20"))) return;
await up.install(image, entry.product, step);
if (archive) await convertAfter(up, model, archive);
} catch (e) {
if (e && e.code && TEXT[lang][e.code]) sayK(e.code, e.detail || (e.code === "loadfail" ? e.message : ""));
else sayK("error", e && e.message);
log(String(e && e.stack || e));
} finally { lockInstaller(false); }
});
$("stock-file").addEventListener("change", async () => {
const epoch = ++stockFileEpoch, file = $("stock-file").files[0]; stock = null; lockInstaller(false);
if (!file) return;
try {
if (![STOCK_V15_SIZE, STOCK_V16_SIZE, STOCK_SMK016_SIZE].includes(file.size)) throw new Error("FM-1.fwsc / SMK-37_Pro_016.fwsc");
const verified = await validateStockPackage(new Uint8Array(await file.arrayBuffer()));
if (epoch !== stockFileEpoch) return;
stock = verified; sayK("stockValid", verified.product); lockInstaller(false);
} catch (e) { if (epoch === stockFileEpoch) sayK("stockError", e.message); }
});
function saveArchive(archive) {
const url = URL.createObjectURL(new Blob([JSON.stringify(archive)], {type:"application/json"}));
const a = document.createElement("a"); a.href = url; a.download = `Skiff-backup-${new Date().toISOString().slice(0,10)}.json`;
document.body.append(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000);
}
// ((Skiff 2.0, Tier B: design/TIER_B.md 10) installing 2.0 over firmware before it that answers complete backups (Skiff,
// Felucca 1.0.3 on): its backup taken and saved to this computer first (the way back; a failure stops before anything is
// written); after the install, what 2.0 can't read converted (web/conv/conv.js) and only that written back. Other
// firmware (stock, JIANT: nothing of Skiff's to convert) installs as before
const major = (v) => +(/(\d+)\.\d/.exec(v || "") || [0, 0])[1];
async function backupBefore(up, model) {
if (major(meta.version) < 2) return null;
const device = await up.find((id) => !IS_OTA(id) && sameModel(id.model, model));
if (!device) return null;
const input = device.link.input, output = device.link.output; device.link.close();
const link = new BackupConnection(input, output);
try {
let reply;
try { reply = await link.request([1, []]); }
catch (e) { if (e.code === "timeout") return null; throw e; }
const info = archiveInfo(reply);
if (!info.supported || major(info.version) >= 2) return null;
const archive = await captureBackup((r, o) => link.request(r, o), info.version,
(done, total) => sayK("backup", `${Math.round(done / Math.max(1, total) * 100)}%`));
saveArchive(archive);
return archive;
} finally { link.close(); }
}
async function convertAfter(up, model, archive) {
let link = null;
sayK("converting");
try {
const device = await up.waitFor((id) => !IS_OTA(id) && sameModel(id.model, model), 20000);
if (!device) throw new Error("the unit does not answer");
const input = device.link.input, output = device.link.output; device.link.close();
link = new BackupConnection(input, output);
const r = (await loadConverter("../editor/conv/conv.wasm")).convert(readBackup(archive));
if (r.writeBack.length)
await restoreBackup((q, o) => link.request(q, o), r.archive,
(done, total) => sayK("converting", `${Math.round(done / Math.max(1, total) * 100)}%`), r.writeBack);
for (const x of r.report)
if (x.what !== "kept" || x.note) log(`${x.id}: ${x.was} -> ${x.now} (${x.what})${x.note ? `: ${x.note}` : ""}`);
sayK(r.report.some((x) => /^(refused|kept as)/.test(x.what)) ? "convertedPart" : r.writeBack.length ? "converted" : "asIs");
} catch (e) { sayK("convertFailed", e.message); log(String(e.stack || e)); }
finally { if (link) link.close(); }
}
function archiveInfo(a) {
let pos = a.indexOf(0); if (pos < 0) throw new Error("Invalid INFO");
const version = String.fromCharCode(...a.slice(0,pos)); pos++;
const engines = a[pos]; pos += 5;
for (let i = 0; i < engines; i++) { const end = a.indexOf(0,pos); if (end < 0) throw new Error("Invalid INFO"); pos = end + 1; }
const ext = a.slice(pos + 1);
const supported = /^FELUCCA /i.test(version) && ext[0] === 16 && ext[1] === 0x55 && ext[2] === 1 &&
ext[4] === 0x4d && ext[5] === 1 && ext[8] === 0x42 && ext[9] === 1 && (ext[10] & 1);
return {version,supported};
}
$("stock-go").addEventListener("click", async () => {
if (!stock || writing) return;
const selected = stock, model = selected.product.split("_")[0]; lockInstaller(true);
let link = null;
try {
let midi;
try { midi = await navigator.requestMIDIAccess({sysex:true}); } catch (e) { sayK("denied"); return; }
const up = new Updater(midi, log);
const step = stepper();
const loader = await up.find(id => IS_OTA(id) && sameModel(id.model, model));
if (loader) {
loader.link.close();
if (!$("stock-recovery").checked) { sayK("stockNeedBackup"); return; }
if (!confirm(t("stockConfirm"))) return;
sayK(await up.resume(selected.image, step, selected.product) ? "done" : "stopped");
} else {
const device = await up.find(id => !IS_OTA(id) && sameModel(id.model, model)) || await up.find(id => !IS_OTA(id));
if (!device) { sayK("notfound"); return; }
const input = device.link.input, output = device.link.output; device.link.close();
if (!sameModel(device.id.model, model)) { sayK("stockWrongModel"); return; }
if (device.id.text === selected.product) { sayK("stockIsStock"); return; } // (#23: it is official already)
link = new BackupConnection(input, output);
let reply; // every Skiff answers INFO: no answer, no Skiff (#23 read "Backup timed out")
try { reply = await link.request([1,[]]); }
catch (e) { if (e.code !== "timeout") throw e; sayK("stockNotSkiff", device.id.text); return; }
const info = archiveInfo(reply);
if (!info.supported) { sayK("stockUnsupported"); return; }
const archive = await captureBackup((r,o) => link.request(r,o), info.version,
(done,total) => sayK("backup", `${Math.round(done / Math.max(1,total) * 100)}%`));
saveArchive(archive); link.close(); link = null;
if (!confirm(t("stockConfirm"))) return;
try { await up.install(selected.image, selected.product, step); }
catch (e) { // ((2.0.2, #64) the version this unit needs, or Skiff too old)
const k = stockRefusal(selected.product, e);
if (!k) throw e;
log(String(e.stack || e)); sayK(k);
}
}
} catch (e) {
if (e.code && TEXT[lang][e.code]) sayK(e.code,e.detail || ""); else sayK("error",e.message);
log(String(e.stack || e));
} finally { if (link) link.close(); lockInstaller(false); }
});
</script>
</body>
</html>