Files
skiff/web/editor.html
T
illuminus5 7641aeeed9 Skiff 1.3.1: a 320 MHz CPU CLOCK, and fixes from your comments
- CPU CLOCK (MENU > SYSTEM): 360 MHz, the default, or 320 MHz, the clock JieLi rates the chip
  for, from the next power-on; curist's fm1-clk320-probe switch (MIT) (#14)
- The web editor's step tables no longer draw over each other past 16 steps
- The low-pass and high-pass icons the right way round (the icon font's names are mirrored)
- README: the standard MIDI CCs; the editor's pictures from 1.3's editor
2026-10-17 09:55:16 -05:00

6090 lines
367 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 -->
<!-- Sample input recording and waveform trimming adapted from Andrea (@andreahaku), PR #29.
Skiff's web editor (after Felucca's). One file, no libraries. Protocol: EDITOR_PROTOCOL.md.
Add ?mock=1 to the URL to use a built-in simulated device. -->
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Skiff Editor</title>
<style>
/* Fukiai: Hügelton Instruments' icon font (MIT, FUKIAI-LICENSE.txt). Icons are text in .ic spans;
they stay hidden until the face has loaded (html.fk), so a missing font never shows boxes. */
@font-face { font-family: "Fukiai"; src: url("fukiai.ttf") format("truetype"); font-display: block; unicode-range: U+EA00-EB09; }
/* ((Skiff 1.0) the look is the unit's BLOCKS (design/editor_looks.png A, the user's pick): the night, tiles, white
values, Barlow Condensed (OFL, fonts/) for headings, labels and values, each track its colour, the sliders in the
selected track's (--trk: renderTrackbar). Once connected the tokens follow the unit's THEME (renderPreferences:
SKIFF and HI-CON dark, PAPER light, CRYPT NEON QUARK their own, each with its tracks' colours,
tools/gen_ui_palettes.py); before that, the system's. Colours only here, as tokens. ((Skiff W6) DIM 4.5:1 and more
on BG and TILE; LINE, an input's edge, 3:1 and more on TILE) */
@font-face { font-family: "Barlow Condensed"; src: url("fonts/BarlowCondensed-Medium.ttf") format("truetype"); font-weight: 500;
font-display: swap; }
@font-face { font-family: "Barlow Condensed"; src: url("fonts/BarlowCondensed-Bold.ttf") format("truetype"); font-weight: 700;
font-display: swap; }
:root { --t1: #ff5a36; --t2: #22c3b4; --t3: #ffbf00; --t4: #9580ff; --t5: #ff6fae; --t6: #a3e635; --trk: var(--t1);
--on-trk: #111111; --head: var(--fg);
--bg: #f4efe4; --tile: #e6dfd0; --raise: #d7cdb9; --hover: #c9bea7; --fg: #221e18; --dim: #5f574a; --line: #857a66;
--rec: #be1828; --txmix: 62%; color-scheme: light; }
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) { --bg: #0c0c0c; --tile: #1e1e1e; --raise: #2c2c2c; --hover: #3a3a3a; --fg: #ffffff;
--dim: #8c8c8c; --line: #6e6e6e; --rec: #ff4848; --txmix: 100%; color-scheme: dark; }
}
:root[data-theme="dark"] { --bg: #0c0c0c; --tile: #1e1e1e; --raise: #2c2c2c; --hover: #3a3a3a; --fg: #ffffff; --dim: #8c8c8c;
--line: #6e6e6e; --rec: #ff4848; --txmix: 100%; color-scheme: dark; }
/* (Skiff) the unit's THEME CRYPT: its dark and stone, bone text, amber headings */
:root[data-theme="crypt"] { --bg: #0a0705; --tile: #221810; --raise: #33251a; --hover: #45321f; --fg: #ecd6ac; --dim: #9a8868;
--line: #6e5a42; --rec: #e85842; --txmix: 100%; --head: #ffb020; color-scheme: dark;
--t1: #ec6e32; --t2: #f2b63c; --t3: #decea6; --t4: #e85842; --t5: #acac5c; --t6: #cc86b0; }
:root[data-theme="crypt"] h1, :root[data-theme="crypt"] h2 { font-family: ui-monospace, Consolas, Menlo, monospace; }
/* (Skiff) NEON: its night and glass, pink headings glowing */
:root[data-theme="neon"] { --bg: #0c041a; --tile: #1e0c32; --raise: #2e1650; --hover: #3e2068; --fg: #f4ecff; --dim: #a890cc;
--line: #7050a0; --rec: #ff4060; --txmix: 100%; --head: #ff58be; color-scheme: dark;
--t1: #ff40b0; --t2: #30e0ff; --t3: #ffde5a; --t4: #ff8038; --t5: #aa64ff; --t6: #50ffaa; }
:root[data-theme="neon"] h1, :root[data-theme="neon"] h2 { font-style: italic; text-shadow: 0 0 6px #ff58be88; }
/* (Skiff) QUARK: a detector's dark, cyan headings on a dotted rule, the colour charges */
:root[data-theme="quark"] { --bg: #03070c; --tile: #0a1520; --raise: #13243a; --hover: #1d3352; --fg: #d8f3ff; --dim: #7fa6bc;
--line: #3f6c8c; --rec: #ff5460; --txmix: 100%; --head: #4fd1ff; color-scheme: dark;
--t1: #ff5460; --t2: #46dc82; --t3: #5a8cff; --t4: #3cdcf0; --t5: #e660e6; --t6: #fadc50; }
:root[data-theme="quark"] h2 { border-bottom: 1px dotted var(--head); padding-bottom: 3px; }
html { color-scheme: light dark; }
body { margin: 0; background: var(--bg); color: var(--fg);
font: 13px/1.4 -apple-system, BlinkMacSystemFont, "Helvetica Neue", Arial, sans-serif;
font-variant-numeric: tabular-nums; }
main { max-width: 1100px; margin: 0 auto; padding: 16px; }
h1 { font-size: 18px; font-weight: 600; margin: 0 0 8px; }
h2 { font-size: 13px; font-weight: 600; margin: 0 0 4px; padding-bottom: 2px; border-bottom: 1px solid var(--fg); }
h3 { font-size: 11px; font-weight: 400; color: var(--dim); margin: 4px 0 0; }
a { color: inherit; }
.lang { float: right; font-size: 12px; color: var(--dim); text-decoration: underline; background: none; padding: 0; }
button { font: inherit; background: var(--fg); color: var(--bg); border: 0; padding: 2px 10px; cursor: pointer; }
button:disabled { opacity: .3; cursor: default; }
button.lang { color: var(--dim); background: none; }
select, input[type=text], input[type=number], input[type=search] {
font: inherit; color: var(--fg); background: var(--bg); border: 1px solid var(--line); padding: 1px 3px; border-radius: 0; }
input[type=range] { width: 100%; margin: 0; accent-color: var(--fg); }
input[type=checkbox] { accent-color: var(--fg); margin: 0; }
.bar { display: flex; flex-wrap: wrap; gap: 6px 12px; align-items: center; margin: 0 0 8px; }
.dim { color: var(--dim); }
#status { min-height: 1.4em; }
section { margin: 12px 0; }
.groups { columns: 250px; column-gap: 20px; }
.group { break-inside: avoid; margin: 0 0 12px; }
.row { display: grid; grid-template-columns: 66px 1fr 70px; gap: 6px; align-items: center; min-height: 22px; }
.row.kitrow { grid-template-columns: 52px 1fr 30px 1fr 30px; } /* ((Skiff W3) the DRUM-X kit: A beside B) */
.row .v { text-align: right; white-space: nowrap; }
.row select { width: 100%; }
.browser { display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-start; }
.browser select[size] { min-width: 150px; }
.slots { display: grid; grid-template-columns: auto auto auto auto; gap: 3px 8px; align-items: center; justify-content: start; }
.slots.named { grid-template-columns: auto auto auto auto auto; } /* ((Skiff W3) RENAME too) */
/* ((Skiff W3) the Song tab: an entry, a pattern: the one a track is on filled, the one staged dashed, the one picked
ringed; empty dim; a pattern nothing uses dashed and dim) */
.lists td { padding: 1px; }
.lists button, .pool button { min-width: 2.6em; padding: 1px 2px; background: var(--bg); color: var(--fg); border: 1px solid var(--line);
font-variant-numeric: tabular-nums; }
.lists button.on, .pool button.on { background: var(--fg); color: var(--bg); }
.lists button.next, .lists button.tog.next { outline: 2px dashed var(--fg); outline-offset: -4px; }
.lists button.pick, .pool button.pick { box-shadow: 0 0 0 2px var(--fg); }
.lists button.empty, .pool button.empty, .seg button.empty { color: var(--dim); }
.pool button.unused { color: var(--dim); border-style: dashed; }
.lists sub { font-size: 70%; }
.pool { display: grid; grid-template-columns: repeat(8, 2.8em); gap: 3px; }
.seg button.kept { font-weight: 700; }
table { border-collapse: collapse; }
th { font-weight: 400; color: var(--dim); text-align: left; padding: 0 6px 2px 0; }
td { padding: 1px 6px 1px 0; }
td.i { color: var(--dim); text-align: right; }
#steps input[type=text] { width: 120px; }
#steps input[type=number] { width: 48px; }
#steps .bad { outline: 1px solid var(--fg); text-decoration: underline wavy; }
.fm6ops { overflow-x: auto; }
.fm6ops td, .fm6ops th { padding: 0 2px; }
input.fm6n { width: 3.2em; }
#steps tr.off td { color: var(--dim); }
.stepcols { display: flex; flex-wrap: wrap; align-items: flex-start; gap: 16px 24px; } /* ((1.3.1) the 16-step tables
side by side where they fit, else one under another: CSS columns of
470 px overlapped tables grown to ~790 px with FLAM, COND, NUDGE) */
.stepcols table { flex: none; }
@media (max-width: 600px) {
.stepcols { overflow-x: auto; }
#steps input[type=text] { width: 84px; }
#steps input[type=number] { width: 42px; }
#steps th, #steps td { padding-right: 3px; }
}
.smp { margin: 0 0 14px; padding: 6px 0 0; border-top: 1px solid var(--line); }
.smp.over { outline: 1px solid var(--fg); outline-offset: 2px; }
.smp .head { display: flex; flex-wrap: wrap; gap: 4px 12px; align-items: center; }
.smp .head b { font-weight: 600; min-width: 40px; }
.smp canvas.trim { width: 100%; height: 56px; display: block; touch-action: none; cursor: ew-resize; }
.smp progress.rec { width: 120px; }
.smp progress { width: 160px; height: 6px; accent-color: var(--fg); }
.smp table { margin: 4px 0; }
.smp input.name { width: 80px; text-transform: uppercase; }
.smp input.root { width: 48px; }
.smp .bad { text-decoration: underline wavy; }
footer { margin-top: 24px; font-size: 11px; color: var(--dim); }
.row.pushed .v { font-weight: 600; }
.row.modrow { grid-template-columns: 16px 1fr 1fr 1fr 52px; }
/* librarian: local library and the device's user bank side by side, stacked on a phone */
.libcols { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 340px), 1fr)); gap: 8px 24px; margin-top: 6px; }
.libcols > div { min-width: 0; }
.libcols .bar input[type=search] { flex: 1 1 120px; min-width: 0; }
.list { height: 260px; overflow: auto; border: 1px solid var(--line); resize: vertical; }
.list table { width: 100%; table-layout: fixed; }
.list th { position: sticky; top: 0; background: var(--bg); padding: 1px 6px; }
.list td { padding: 1px 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.list tr[data-id], .list tr[data-slot] { cursor: pointer; }
.list tr.sel td { background: var(--fg); color: var(--bg); }
.list tr.empty td { color: var(--dim); }
.list tr.over td { outline: 1px dashed var(--fg); outline-offset: -1px; }
.list.over { outline: 1px solid var(--fg); }
.list .none { padding: 6px; color: var(--dim); }
.list col.n { width: 40px; } .list col.e { width: 72px; } .list col.d { width: 78px; }
.ic { font-family: "Fukiai"; font-style: normal; font-weight: 400; font-synthesis: none; line-height: 1; margin-right: .3em; }
html:not(.fk) .ic { display: none; }
/* wave choices: a page-drawn picker so the options can carry an icon (Chrome 135+); native menus get words only */
@supports (appearance: base-select) {
select.wave, select.wave::picker(select) { appearance: base-select; }
select.wave { padding: 1px 3px; min-block-size: 0; border: 1px solid var(--line); border-radius: 0; background: var(--bg); color: var(--fg); }
select.wave > button { font: inherit; background: none; color: inherit; padding: 0; text-align: start; }
select.wave::picker(select) { border: 1px solid var(--line); background: var(--bg); color: var(--fg); padding: 0; }
select.wave option { padding: 1px 6px; min-block-size: 0; }
select.wave option:checked { font-weight: 600; }
select.wave option:hover, select.wave option:focus-visible { background: var(--fg); color: var(--bg); }
select.wave option::checkmark { display: none; }
}
/* tabs: a wrapping row of plain buttons, the open one inverted; header stays at the top on wide screens */
.top { position: sticky; top: 0; z-index: 5; background: var(--bg); padding: 4px 0 0; }
@media (max-width: 600px) { .top { position: static; } }
.tabs { display: flex; flex-wrap: wrap; gap: 0; border-bottom: 1px solid var(--fg); margin: 6px 0 0; }
.tabs button { background: none; color: var(--dim); padding: 4px 10px; border: 1px solid transparent; border-bottom: 0; white-space: nowrap; }
.tabs button:hover { color: var(--fg); }
.tabs button[aria-selected="true"] { background: var(--fg); color: var(--bg); }
.trackbar { display: flex; flex-wrap: wrap; gap: 4px 8px; align-items: center; padding: 6px 0; border-bottom: 1px solid var(--line); }
.seg { display: inline-flex; flex-wrap: wrap; }
.seg button, button.tog { background: var(--bg); color: var(--fg); border: 1px solid var(--fg); padding: 1px 10px; }
.seg button + button { border-left: 0; }
.seg button[aria-pressed="true"], button.tog[aria-pressed="true"] { background: var(--fg); color: var(--bg); }
.panel { margin: 12px 0; }
.hint { margin: 16px 0; color: var(--dim); }
/* sequencer: a step grid over the selected track (16 per row, 8 on a phone) */
.grid { display: grid; grid-template-columns: repeat(16, minmax(0, 1fr)); gap: 2px; margin: 6px 0 12px; }
@media (max-width: 600px) { .grid { grid-template-columns: repeat(8, minmax(0, 1fr)); } }
.grid button { background: var(--bg); color: var(--fg); border: 1px solid var(--line); padding: 2px; min-width: 0; height: 52px;
display: flex; flex-direction: column; justify-content: flex-start; gap: 1px; text-align: left; overflow: hidden; font-size: 10px; line-height: 1.15; }
.grid button .n { color: var(--dim); }
.grid button .x { overflow: hidden; overflow-wrap: anywhere; flex: 1; }
.grid button.on { background: var(--fg); color: var(--bg); border-color: var(--fg); }
.grid button.on .n { color: inherit; opacity: .6; }
.grid button.acc .x { font-weight: 700; }
.grid button.tie { border-style: dashed; border-color: var(--fg); }
.grid button.beat { border-left-color: var(--fg); }
#steps tr.hl td { outline: 1px solid var(--fg); }
/* mixer: a channel strip per track (six; Skiff phase 6) as on the device's MIXER page */
.mixer { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 8px; max-width: 900px; margin: 6px 0; }
@media (max-width: 600px) { .mixer { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
.strip { border: 1px solid var(--line); padding: 6px 4px; display: flex; flex-direction: column; align-items: center; gap: 6px; min-width: 0; }
.strip.sel { border-color: var(--fg); box-shadow: inset 0 0 0 1px var(--fg); }
.strip .num { font-size: 18px; font-weight: 600; line-height: 1; }
.strip .snd { font-size: 11px; line-height: 1.3; width: 100%; text-align: center; overflow-wrap: anywhere; min-height: 2.6em; }
.strip .rec { font-size: 11px; color: var(--dim); }
.strip .rec.on { color: var(--fg); font-weight: 600; }
.strip .rec:not(.on) .ic { visibility: hidden; }
.strip input.fader { writing-mode: vertical-lr; direction: rtl; width: 28px; height: 150px; }
.strip .v { font-size: 11px; white-space: nowrap; }
.strip .pan { width: 100%; }
.strip.muted .fader, .strip.muted .lv { opacity: .35; }
.strip button { width: 100%; padding: 1px 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.strip button.selb:disabled { opacity: 1; background: none; color: var(--dim); }
#sysinfo th { padding-right: 16px; }
/* ((Skiff 1.0) BLOCKS over the rules above: tiles, Barlow Condensed, the tracks' colours (--s: the track's own) */
h1 { font: 700 26px "Barlow Condensed", sans-serif; letter-spacing: .02em; text-transform: uppercase; color: var(--head); }
h2 { font: 700 16px "Barlow Condensed", sans-serif; letter-spacing: .04em; text-transform: uppercase; border: 0; margin: 0 0 6px;
color: var(--head); }
h3 { font: 500 12px "Barlow Condensed", sans-serif; letter-spacing: .05em; text-transform: uppercase; }
.group { background: var(--tile); border-radius: 6px; padding: 10px 12px 8px; }
.row > span:first-child { font: 500 14px "Barlow Condensed", sans-serif; letter-spacing: .03em; }
.row .v { font: 700 15px "Barlow Condensed", sans-serif; }
button { background: var(--raise); color: var(--fg); border-radius: 4px; padding: 3px 10px; }
button:hover:not(:disabled) { background: var(--hover); }
button.lang, button.lang:hover:not(:disabled) { background: none; }
select, input[type=text], input[type=number], input[type=search] { background: var(--raise); border: 1px solid var(--line);
border-radius: 4px; padding: 2px 4px; }
input[type=range], input[type=checkbox], .smp progress { accent-color: var(--trk); }
.tabs { border-bottom: 2px solid var(--fg); gap: 2px; }
.tabs button { font: 700 15px "Barlow Condensed", sans-serif; letter-spacing: .04em; text-transform: uppercase; background: var(--tile);
color: var(--dim); border: 0; border-radius: 6px 6px 0 0; padding: 5px 12px; }
.tabs button:hover:not(:disabled) { background: var(--raise); color: var(--fg); }
.tabs button[aria-selected="true"], .tabs button[aria-selected="true"]:hover { background: var(--fg); color: var(--bg); }
.seg button, button.tog { background: var(--raise); border: 0; margin-right: 2px; border-radius: 4px; }
.seg button + button { border-left: 0; }
.seg button[aria-pressed="true"], button.tog[aria-pressed="true"] { background: var(--fg); color: var(--bg); }
#trackbtns button:nth-child(1), .mixer .strip:nth-child(1), .lists tbody tr:nth-child(1) { --s: var(--t1); }
#trackbtns button:nth-child(2), .mixer .strip:nth-child(2), .lists tbody tr:nth-child(2) { --s: var(--t2); }
#trackbtns button:nth-child(3), .mixer .strip:nth-child(3), .lists tbody tr:nth-child(3) { --s: var(--t3); }
#trackbtns button:nth-child(4), .mixer .strip:nth-child(4), .lists tbody tr:nth-child(4) { --s: var(--t4); }
#trackbtns button:nth-child(5), .mixer .strip:nth-child(5), .lists tbody tr:nth-child(5) { --s: var(--t5); }
#trackbtns button:nth-child(6), .mixer .strip:nth-child(6), .lists tbody tr:nth-child(6) { --s: var(--t6); }
#trackbtns button, .lists tbody th, .strip .num { color: color-mix(in srgb, var(--s) var(--txmix), var(--fg)); }
#trackbtns button { font: 700 16px "Barlow Condensed", sans-serif; min-width: 32px; }
#trackbtns button[aria-pressed="true"] { background: var(--s); color: var(--on-trk); }
.strip { background: var(--tile); border: 0; border-radius: 6px; }
.strip.sel { box-shadow: inset 0 0 0 2px var(--s); }
.strip .num { font: 700 26px "Barlow Condensed", sans-serif; background: none; }
.strip .num[aria-pressed="true"] { background: var(--s); color: var(--on-trk); } /* (selected: as the track bar's) */
.strip input[type=range] { accent-color: var(--s); }
.grid button.on { background: var(--trk); border-color: var(--trk); color: var(--on-trk); }
.lists tbody th { font: 700 15px "Barlow Condensed", sans-serif; }
.lists button, .pool button { background: var(--raise); border-color: var(--raise); border-radius: 3px; }
.lists button.empty, .pool button.empty { background: var(--tile); border-color: var(--tile); }
.lists button.on { background: var(--s); border-color: var(--s); color: var(--on-trk); }
.lists button.next { outline-color: var(--s); }
#trec[aria-pressed="true"] { background: var(--rec); color: var(--on-trk); }
.list tr.sel td { background: var(--trk); color: var(--on-trk); }
[hidden] { display: none !important; }
</style>
</head>
<body>
<main>
<button class="lang" id="lang"></button>
<h1>Skiff Editor</h1>
<p class="dim"><a href="../installer/" style="color:inherit" data-t="installer"></a></p>
<!-- always visible: connection, version, sync mode, the tabs and (Sound / Sequencer / Tracks) the track selector -->
<header class="top">
<div class="bar">
<button id="connect" data-t="connect" data-ic="port_usb_c"></button>
<span id="version" class="dim"></span>
<span id="live" class="dim"></span>
<span class="seg" id="transport" role="group" hidden><button id="tplay" data-t="play" data-ic="control_play_f"></button><button
id="tstop" data-t="stop" data-ic="control_stop_f"></button><button id="trec" data-t="rec" data-ic="control_rec_f"></button></span>
<span id="tstate" class="dim" hidden></span>
<span id="mock" class="dim" hidden data-t="mock"></span>
</div>
<div id="status" role="status" aria-live="polite"></div>
<nav class="tabs" id="tabs" role="tablist">
<button role="tab" data-tab="sound" data-t="sound" data-ic="symbol_audio"></button>
<button role="tab" data-tab="fm6" data-t="tabFm6" data-ic="ui_knob"></button>
<button role="tab" data-tab="sequencer" data-t="tabSeq" data-ic="symbol_grid"></button>
<button role="tab" data-tab="song" data-t="sgTab" data-ic="control_arrow_loop"></button>
<button role="tab" data-tab="tracks" data-t="tabTracks" data-ic="ui_slider_vertical"></button>
<button role="tab" data-tab="library" data-t="library" data-ic="symbol_books"></button>
<button role="tab" data-tab="samples" data-t="samples" data-ic="symbol_waves"></button>
<button role="tab" data-tab="projects" data-t="projects" data-ic="symbol_folder"></button>
<button role="tab" data-tab="settings" data-t="tabSettings" data-ic="symbol_cog"></button>
</nav>
<div class="trackbar" id="trackbar" hidden><span class="dim" data-t="track"></span><span class="seg" id="trackbtns" role="group"></span></div>
</header>
<p class="hint" id="hint" hidden></p>
<section class="panel" id="p-sound" data-tab="sound" data-dev hidden>
<div class="browser" id="browser">
<label><span data-t="engine"></span><br><select id="engine"></select></label>
<label><span data-t="presets"></span><br><select id="preset" size="8"></select></label>
<div>
<p class="bar"><button id="init" data-t="initSound"></button>
<button id="factlib" data-t="factoryToLib" data-ic="symbol_folder"></button></p>
<p class="bar"><button id="savefile" data-t="saveFile" data-ic="symbol_download"></button>
<button id="loadfile" data-t="loadFile" data-ic="symbol_upload"></button>
<input type="file" id="file" accept=".json,application/json" hidden></p>
</div>
</div>
<p class="dim" id="ctlhelp" data-t="ctlHelp"></p>
<div class="groups" id="groups"></div>
</section>
<section class="panel" id="p-fm6" data-tab="fm6" data-dev hidden>
<p class="dim" data-t="fm6Help"></p>
<div class="group">
<h2 data-t="fm6Source" data-ic="symbol_folder"></h2>
<p class="bar"><label><span data-t="track"></span> <select id="fm6trk"></select></label>
<button id="fm6read" data-t="fm6ReadBtn"></button> <button id="fm6send" data-t="fm6SendBtn"></button>
<label><input type="checkbox" id="fm6live"> <span data-t="fm6Live"></span></label></p>
<p class="bar"><button id="fm6import" data-t="fm6Import" data-ic="symbol_upload"></button>
<input type="file" id="fm6file" accept=".syx,.SYX,.bin,application/octet-stream" hidden>
<button id="fm6export" data-t="fm6Export" data-ic="symbol_download"></button>
<button id="fm6init" data-t="fm6Init"></button></p>
<div id="fm6imported"></div>
<p class="bar"><label><span data-t="fm6Factories"></span> <select id="fm6slot"></select></label>
<button id="fm6load" data-t="load"></button></p>
<p class="dim" id="fm6keep" data-t="fm6Keep"></p>
</div>
<div class="group">
<h2 data-t="fm6Voice" data-ic="ui_knob"></h2>
<div id="fm6voice"></div>
</div>
<div class="group">
<h2 data-t="fm6Ops" data-ic="function_env_adsr_exp"></h2>
<div id="fm6ops"></div>
</div>
</section>
<section class="panel" id="p-sequencer" data-tab="sequencer" data-dev hidden>
<div class="groups" id="seqgroups"></div>
<div id="steps">
<h2 data-t="steps" data-ic="note_eight"></h2>
<p class="bar"><button id="reloadsteps" data-t="reload" data-ic="control_arrow_loop"></button>
<button id="clearseq" data-t="clearSeq" data-ic="symbol_trash"></button>
<span class="dim" id="noteshelp"></span></p>
<div class="grid" id="stepgrid"></div>
<div class="stepcols" id="steptables"></div>
</div>
<div id="motion-panel" hidden style="margin-top:16px">
<h2 data-t="motion"></h2>
<p class="bar"><label><input id="motion-on" type="checkbox"> <span data-t="motionOn"></span></label>
<button id="motion-clear" data-t="motionClear"></button><span id="motion-count" class="dim"></span></p>
<table id="motion-rows"></table>
</div>
</section>
<section class="panel" id="p-song" data-tab="song" data-dev hidden>
<p class="dim" data-t="sgHelp"></p>
<div class="group" id="sg-lists" hidden>
<h2 data-t="sgLists" data-ic="control_arrow_loop"></h2>
<p class="bar"><label><input type="checkbox" id="sgsong"> <span data-t="sgSong"></span></label>
<label><span data-t="sgLaunch"></span> <select id="sglaunch"><option value="0">LOOP</option><option value="1">BAR</option>
<option value="2">BEAT</option><option value="3">NOW</option></select></label>
<button id="sgcancel" data-t="sgCancel"></button></p>
<div id="sglists"></div>
<p class="bar" id="sgentry"></p>
</div>
<div class="group" id="sg-scenes" hidden>
<h2 data-t="sgScenes"></h2>
<p class="bar"><span class="seg" id="sgscenes" role="group"></span>
<label><input type="checkbox" id="sgstore"> <span data-t="sgStore"></span></label></p>
</div>
<div class="group" id="sg-pool" hidden>
<h2 data-t="sgPool" data-ic="symbol_folder"></h2>
<p class="dim" data-t="sgPoolHelp"></p>
<div id="sgpool" class="pool"></div>
<p class="bar" id="sgpoolpick"></p>
</div>
</section>
<section class="panel" id="p-tracks" data-tab="tracks" data-dev hidden>
<h2 data-t="mixer" data-ic="ui_slider_vertical"></h2>
<div class="mixer" id="mixer"></div>
<p class="dim" data-t="mixHelp"></p>
</section>
<!-- works without a device too (the device bank shows while connected) -->
<section class="panel" id="p-library" data-tab="library" hidden>
<div class="group" id="device-presets" hidden>
<h2 data-t="devicePresets"></h2>
<p class="dim" data-t="deviceFavHelp"></p>
<label><span data-t="deviceList"></span> <select id="device-filter"></select></label>
<div class="list" id="device-preset-list" style="margin-top:8px"></div>
</div>
<div class="libcols" id="libsec">
<div id="libpane">
<h2 data-t="library" data-ic="symbol_books"></h2>
<div class="bar">
<input type="search" id="libq" spellcheck="false">
<select id="libeng"></select>
<select id="libtag"></select>
<select id="libsort"></select>
</div>
<div class="list" id="liblist"></div>
<p class="bar" style="margin-top:6px">
<button id="libaud" data-t="audition" data-ic="symbol_audio"></button>
<button id="libput" data-t="toSlot" data-ic="symbol_upload"></button>
<button id="libren" data-t="rename"></button>
<button id="libtags" data-t="tags"></button>
<button id="libdup" data-t="duplicate"></button>
<button id="libdel" data-t="delete" data-ic="symbol_trash"></button>
<button id="libexp1" data-t="exportPatch" data-ic="symbol_download"></button>
</p>
<p class="bar">
<button id="libsave" data-t="saveToLib" data-ic="port_disk"></button>
<button id="libimport" data-t="import" data-ic="symbol_upload"></button>
<button id="libexport" data-t="exportLib" data-ic="symbol_download"></button>
<input type="file" id="libfile" accept=".json,application/json" multiple hidden>
<span class="dim" id="libcount"></span>
</p>
</div>
<div>
<h2 data-t="bank" data-ic="port_disk"></h2>
<p class="dim" id="bankhint"></p>
<div id="bankpane" hidden>
<div class="bar"><b id="bankhead"></b></div>
<div class="list" id="banklist"></div>
<p class="bar" style="margin-top:6px">
<button id="bkload" data-t="bankLoad" data-ic="symbol_folder_open"></button>
<button id="bkstore" data-t="bankStore" data-ic="port_disk"></button>
<button id="bkget" data-t="bankGet" data-ic="symbol_download"></button>
<button id="bkerase" data-t="erase" data-ic="symbol_trash"></button>
</p>
<p class="bar">
<button id="bkrefresh" data-t="reload" data-ic="control_arrow_loop"></button>
<button id="bkexport" data-t="exportBank" data-ic="symbol_download"></button>
<span class="dim" data-t="dndHelp"></span>
</p>
</div>
</div>
</div>
</section>
<section class="panel" id="p-samples" data-tab="samples" data-dev hidden>
<h2 data-t="samples" data-ic="symbol_waves"></h2>
<p class="dim" data-t="smpHelp"></p>
<div id="smpslots"></div>
</section>
<section class="panel" id="p-projects" data-tab="projects" data-dev hidden>
<h2 data-t="projects" data-ic="symbol_folder"></h2>
<p class="dim" data-t="projHelp"></p>
<p id="projnow" hidden></p>
<p class="bar" id="projnamebar" hidden><label><span data-t="projName"></span> <input id="projname" maxlength="12"
spellcheck="false" autocomplete="off" style="text-transform: uppercase"></label></p>
<div class="slots" id="slots"></div>
<div id="backup-panel" style="margin-top:16px">
<h2 data-t="backupTitle"></h2>
<p class="bar"><button id="backup-export" data-t="backupExport"></button>
<button id="backup-import" data-t="backupImport"></button><input id="backup-file" type="file" accept=".json,application/json" hidden></p>
<p class="dim" id="backup-help"></p>
</div>
</section>
<section class="panel" id="p-settings" data-tab="settings" data-dev hidden>
<div class="groups" id="setgroups"></div>
<div class="group" id="device-display" hidden style="margin-top:12px">
<h2 data-t="deviceDisplay"></h2>
<p class="dim" data-t="deviceDisplayHelp"></p>
<div id="device-display-controls"></div>
</div>
<div class="group" id="device-menu" hidden style="margin-top:12px">
<h2 data-t="deviceMenu"></h2>
<p class="dim" data-t="deviceMenuHelp"></p>
<div id="device-menu-controls"></div>
</div>
<div class="group" style="margin-top:12px">
<h2 data-t="system" data-ic="symbol_cog"></h2>
<table id="sysinfo"></table>
</div>
</section>
<footer>Skiff by illuminus5 (<a href="https://github.com/illuminus5/skiff" target="_blank" rel="noopener">github.com/illuminus5/skiff</a>), built on Felucca by Leo Kuroshita (@kurogedelic), <a href="https://hugelton.com" target="_blank" rel="noopener">Hügelton Instruments</a>. GPL-3.0.<br>
<span data-t="foot"></span> M-VAVE and FM-1 are trademarks of their respective owners.<br>
<a href="FUKIAI-LICENSE.txt" data-t="iconsCredit"></a></footer>
</main>
<script>
"use strict";
/*PROTO-BEGIN*/
/* ---------------------------------------------------------------- protocol --- */
const HDR = [0x7D, 0x46, 0x4C];
const CMD = { INFO: 1, GET: 2, SET: 3, DUMP: 4, DESC: 5, STEP_GET: 6, STEP_SET: 7, PRESET: 8, PROJECT: 9, NAMES: 10,
SMP_BEGIN: 11, SMP_WRITE: 12, SMP_END: 13, SMP_ERASE: 14, SMP_INFO: 15,
UP_LIST: 16, UP_GET: 17, UP_PUT: 18, UP_STORE: 19, UP_LOAD: 20, UP_ERASE: 21,
WATCH: 22, CHANGED: 23, RELOAD: 24, PING: 25, STEP_CHANGED: 26,
TRACK: 27, TRACK_MIX: 28, TRACK_DUMP: 29, TRACK_STEP: 30,
TRACK_PARAM: 31, TRACK_CHANGED: 32, SONG: 33,
UI_STATE: 34, UI_SET: 35, UI_PALETTES: 36, FAV_GET: 37, FAV_SET: 38,
MOTION: 64, BACKUP_LIST: 65, BACKUP_GET: 66, BACKUP_PUT: 67,
FM6_GET: 68, FM6_PUT: 69, FM6_LIST: 70, FM6_ERASE: 71, MENU_DESC: 72, MENU_SET: 73, KIT_GET: 74, KIT_PUT: 75, TRANSPORT: 76, PROJ_NAME: 77, POOL: 78, LIST: 79, PERFORM: 80 };
/* frames the device sends on its own (while WATCH is on); never replies */
const PUSH = new Set([CMD.CHANGED, CMD.RELOAD, CMD.STEP_CHANGED, CMD.TRACK_CHANGED]);
/* user preset bank: name 1..12 printable ASCII, a 16-step pattern of (note, flags 1 acc 2 slide 4 tie) */
const UP = { NAME_MAX: 12, PAT: 16, LIST_MAX: 16 };
const F = { INT: 0, PCT: 1, BIPCT: 2, TIME: 3, LFOHZ: 4, CUTOFF: 5, DB: 6, SEMI: 7, ENUM: 8, BPM: 9, NOTE: 10, ONOFF: 11, OCT: 12, STEPS: 13, ST16: 14 };
const v14enc = (v) => { const u = Math.max(-8192, Math.min(8191, Math.round(v))) + 8192; return [u & 0x7F, (u >> 7) & 0x7F]; };
const v14dec = (lo, hi) => (lo | (hi << 7)) - 8192;
function strEnc(s) { const a = []; for (const c of String(s)) a.push(c.charCodeAt(0) & 0x7F); a.push(0); return a; }
/* only ever builds F0 7D 46 4C ... F7 */
function frame(cmd, args = []) {
for (const b of args) if (!(Number.isInteger(b) && b >= 0 && b <= 0x7F)) throw new Error("bad data byte " + b);
return [0xF0, ...HDR, cmd & 0x7F, ...args, 0xF7];
}
/* -> {cmd, a} or null when it is not an editor frame */
function unframe(d) {
if (!d || d.length < 6 || d[0] !== 0xF0 || d[d.length - 1] !== 0xF7) return null;
if (d[1] !== HDR[0] || d[2] !== HDR[1] || d[3] !== HDR[2]) return null;
return { cmd: d[4], a: Array.from(d.slice(5, d.length - 1)) };
}
/* the DRUM grid (firmware v5): a step's lane hits and their accents, bit l = lane l. Each lane plays its GM note
(eng_drum.c DRUM_LANE_NOTE) on any engine; LANE_OF: the lane a GM note 35..81 strikes (drum_lane; others fold
to their octave of 36..47) */
const LANES = ["KICK", "SNARE", "CLAP", "HATCL", "HATOP", "TOM", "RIM", "BELL"];
const LANE_NOTE = [36, 38, 39, 42, 46, 45, 37, 56];
const LANE_OF = "00612153535455757773777675555555773366336665577";
const LANE_ALIAS = { CONGA: 5, CLAVE: 6, CYM: 7, BD: 0, SD: 1, CP: 2, CH: 3, OH: 4 };
const drumLane = (n) => +LANE_OF[(n >= 35 && n <= 81 ? n : 36 + ((n + 120 - 36) % 12)) - 35];
/* the lanes a step strikes (its hits, its notes on their lanes) and which are accented (step_lanes / step_accents) */
const stepLanes = (s) => (s.time !== 0 ? 0 : s.notes.slice(0, s.n).reduce((m, n) => m | (1 << drumLane(n)), s.hit | 0));
const stepAccents = (s) => (s.flags & 1 ? stepLanes(s) : (s.acc | 0) & stepLanes(s));
/* hits as text, an accent marked ">" ("KICK >SNARE HATCL"), and back: null when a word is not a lane */
const hitsText = (hit, acc) => LANES.map((nm, l) => (hit >> l & 1 ? (acc >> l & 1 ? ">" : "") + nm : "")).filter(Boolean).join(" ");
function parseHits(text) {
let hit = 0, acc = 0;
for (const w of String(text).toUpperCase().split(/[\s,]+/).filter(Boolean)) {
const a = w.startsWith(">"), nm = a ? w.slice(1) : w, l = LANES.includes(nm) ? LANES.indexOf(nm) : LANE_ALIAS[nm];
if (l == null) return null;
hit |= 1 << l;
if (a) acc |= 1 << l;
}
return { hit, acc };
}
/* the 3 bytes after a step (v5): hit & 127, acc & 127, bit 7 of each; an older firmware's step has none (0) */
const hitsEnc = (hit, acc) => [hit & 0x7F, acc & 0x7F, (hit >> 7 & 1) | (acc >> 7 & 1) << 1];
/* (Skiff W3) the mock device's MENU settings, as Skiff's firmware has them (menu_items.c; test_web.mjs checks them against
tests/editor_test.c's menu.json): id, name, value names (THEME: the palettes), default, the device's tab */
const MENU_TABS = ["DISPLAY", "CONTROL", "AUDIO", "SYSTEM"];
const MENU = [
{ id: 0, name: "THEME", names: null, def: 0, tab: 0 }, { id: 2, name: "LARGE", names: ["OFF", "ON"], def: 0, tab: 0 },
{ id: 3, name: "ANIM", names: ["ON", "OFF"], def: 0, tab: 0 }, { id: 4, name: "LEDS", names: ["OFF", "DIM LO", "DIM HI", "INV"], def: 2, tab: 0 },
{ id: 5, name: "HOLD", names: ["0.3 s", "0.4 s", "0.5 s", "0.6 s"], def: 1, tab: 1 }, { id: 6, name: "KNOB ACCEL", names: ["OFF", "ON"], def: 0, tab: 1 },
{ id: 8, name: "BPM LOCK", names: ["OFF", "ON"], def: 0, tab: 1 }, { id: 9, name: "SPEAKER EQ", names: ["FLAT", "LOWCUT", "BASS+"], def: 0, tab: 2 },
{ id: 10, name: "USB LEVEL", names: ["MASTER", "FIXED"], def: 0, tab: 2 }, { id: 11, name: "USB SERIAL", names: ["ON", "OFF"], def: 0, tab: 3 },
{ id: 12, name: "CLICK", names: ["OFF", "REC", "ON"], def: 0, tab: 2 }, { id: 13, name: "CLICK LEVEL", names: ["LOW", "MID", "HIGH"], def: 1, tab: 2 },
{ id: 14, name: "COUNT-IN", names: ["OFF", "1 BAR", "2 BARS"], def: 0, tab: 2 }, { id: 15, name: "RESTORE LAST", names: ["ON", "OFF"], def: 0, tab: 3 },
{ id: 16, name: "SCALE LEDS", names: ["OFF", "ON"], def: 0, tab: 1 },
{ id: 17, name: "SCREEN OFF", names: ["NEVER", "5 MIN", "15 MIN", "30 MIN", "60 MIN"], def: 3, tab: 0 }];
/* (Skiff W1) a step's trig condition (core.h TC_NAME; INFO 43 01 says how many) */
const TC_NAMES = ["--", "FILL", "!FILL", "1:2", "2:2", "1:3", "2:3", "3:3", "1:4", "2:4", "3:4", "4:4"];
/* (Skiff W3) the DRUM-X kit: the factory's (drumx_voice.c DX_KIT_INIT: {mode, A, B}, A and B PITCH P MOD DECAY NOISE
COLOR; test_web.mjs checks it against the firmware's), its lanes, the mode's names (ui_dx.c), its values */
const DX_KIT_DEF = [[16, [9, 70, 72, 4, 20], [14, 100, 88, 10, 60]], [5, [40, 30, 52, 80, 90], [46, 18, 64, 104, 70]],
[4, [60, 0, 46, 127, 84], [54, 0, 58, 127, 76]], [10, [100, 0, 22, 96, 116], [108, 0, 14, 112, 122]],
[10, [100, 0, 62, 96, 112], [108, 0, 74, 112, 118]], [16, [30, 40, 66, 10, 30], [36, 60, 76, 20, 50]],
[27, [63, 10, 14, 16, 46], [70, 24, 20, 30, 60]], [6, [69, 0, 72, 0, 40], [74, 0, 84, 12, 56]]];
/* (Skiff phase 9) the factory kits a DRUM-X preset loads as the project's kit (eng_drumx.c DX_KITS: 0 the factory's,
then the kits of FACTORY KIT on) and each preset's kit + 1 (DRUMX_PKIT; 0 keeps the kit); test_web.mjs checks both */
const DX_KITS = [DX_KIT_DEF,
[[48, [6, 60, 84, 2, 10], [10, 80, 92, 4, 30]], [4, [36, 20, 60, 90, 60], [40, 28, 70, 100, 70]], [4, [56, 0, 52, 127, 70], [52, 0, 64, 127, 64]], [10, [92, 0, 18, 100, 104], [96, 0, 24, 110, 110]], [10, [92, 0, 70, 100, 100], [96, 0, 84, 110, 106]], [48, [22, 50, 80, 6, 20], [28, 70, 92, 10, 40]], [27, [58, 8, 16, 10, 40], [62, 16, 22, 20, 50]], [6, [64, 0, 80, 0, 36], [70, 0, 92, 10, 48]]],
[[16, [16, 100, 60, 10, 40], [20, 120, 68, 20, 70]], [9, [60, 10, 40, 70, 110], [66, 0, 46, 90, 120]], [8, [70, 0, 30, 127, 100], [66, 0, 40, 127, 96]], [10, [116, 0, 8, 60, 124], [120, 0, 12, 80, 127]], [10, [116, 0, 40, 60, 120], [120, 0, 50, 80, 124]], [17, [40, 60, 36, 0, 50], [46, 80, 44, 0, 70]], [27, [80, 20, 8, 0, 60], [86, 30, 10, 10, 80]], [5, [88, 0, 30, 0, 80], [92, 0, 40, 0, 90]]],
[[145, [10, 90, 70, 20, 70], [14, 110, 80, 30, 100]], [134, [44, 30, 50, 100, 80], [50, 40, 60, 110, 90]], [6, [64, 0, 46, 120, 90], [60, 0, 56, 124, 84]], [138, [104, 0, 20, 110, 116], [110, 0, 28, 120, 122]], [10, [104, 0, 72, 110, 112], [110, 0, 84, 120, 118]], [18, [28, 50, 60, 20, 60], [34, 70, 72, 30, 80]], [151, [70, 20, 20, 30, 70], [76, 30, 26, 40, 90]], [7, [60, 10, 90, 10, 60], [66, 20, 94, 20, 74]]],
[[16, [12, 40, 76, 0, 4], [14, 54, 86, 2, 14]], [0, [42, 10, 46, 60, 50], [44, 16, 56, 70, 56]], [0, [60, 0, 40, 127, 60], [58, 0, 50, 127, 56]], [6, [90, 0, 16, 100, 90], [94, 0, 22, 110, 96]], [6, [90, 0, 60, 100, 86], [94, 0, 70, 110, 92]], [16, [32, 20, 60, 4, 10], [36, 30, 70, 8, 20]], [20, [66, 4, 12, 20, 40], [70, 8, 16, 30, 50]], [4, [78, 0, 60, 0, 20], [80, 0, 72, 4, 30]]],
[[81, [12, 80, 56, 10, 60], [18, 110, 64, 20, 90]], [69, [50, 60, 40, 90, 100], [58, 80, 48, 100, 110]], [10, [76, 20, 30, 110, 110], [70, 30, 40, 120, 104]], [74, [110, 30, 10, 80, 120], [118, 50, 14, 90, 126]], [11, [108, 20, 44, 80, 116], [114, 30, 52, 90, 122]], [65, [36, 90, 40, 10, 80], [44, 110, 48, 20, 100]], [91, [84, 40, 10, 30, 80], [90, 60, 14, 40, 100]], [101, [72, 50, 50, 0, 90], [80, 70, 60, 10, 100]]],
[[48, [14, 50, 80, 0, 20], [18, 64, 90, 4, 30]], [20, [46, 40, 50, 40, 50], [50, 50, 58, 50, 60]], [4, [58, 0, 40, 127, 72], [54, 0, 48, 127, 66]], [6, [96, 0, 14, 110, 100], [100, 0, 18, 120, 106]], [6, [96, 0, 40, 110, 96], [100, 0, 50, 120, 102]], [48, [30, 60, 70, 4, 24], [36, 80, 80, 8, 34]], [23, [74, 10, 18, 4, 50], [78, 16, 22, 10, 60]], [7, [76, 0, 70, 0, 40], [80, 0, 80, 4, 50]]],
[[16, [10, 110, 70, 0, 30], [14, 127, 80, 6, 50]], [101, [50, 70, 50, 80, 90], [56, 90, 60, 90, 100]], [4, [62, 0, 44, 127, 86], [58, 0, 54, 127, 80]], [10, [106, 0, 14, 90, 120], [110, 0, 18, 100, 124]], [10, [106, 0, 56, 90, 116], [110, 0, 64, 100, 120]], [112, [40, 100, 60, 0, 40], [48, 120, 70, 0, 60]], [121, [90, 90, 20, 0, 80], [96, 110, 26, 0, 100]], [96, [70, 127, 50, 0, 40], [80, 127, 60, 0, 60]]]];
const DRUMX_PKIT = [0, 0, 1, 2, 3, 4, 5, 6, 7, 8];
const DX = { lanes: ["KICK", "SNARE", "CLAP", "CL HAT", "OP HAT", "TOM", "RIM", "BELL"], waves: ["SINE", "FM", "METAL", "BELL"],
filters: ["LP", "BP", "HP"], shapes: ["DECAY", "LONG", "NOISE", "SINE"], values: ["PITCH", "P MOD", "DECAY", "NOISE", "COLOR"] };
function readHits(r, o) {
o.hit = 0; o.acc = 0;
if (r.i + 3 <= r.a.length) { const h = r.b(), c = r.b(), x = r.b(); o.hit = h | (x & 1) << 7; o.acc = (c | (x & 2) << 6) & o.hit; }
o.chance = r.i < r.a.length ? r.b() : 100;
if (o.chance > 100) throw new Error("Invalid step chance");
o.ratchet = r.i < r.a.length ? r.b() : 1; /* RATCH (INFO 52 01): the step's hits 1..4; older firmware: 1 */
if (o.ratchet < 1 || o.ratchet > 4) throw new Error("Invalid step ratchet");
o.flam = r.i < r.a.length ? r.b() : 0; /* (Skiff W1, INFO 43 01) FLAM, COND, NUDGE + 32; older firmware: none */
o.cond = r.i < r.a.length ? r.b() : 0;
o.nudge = (r.i < r.a.length ? r.b() : 32) - 32;
if (o.flam > 1 || o.cond >= TC_NAMES.length || o.nudge > 31) throw new Error("Invalid step extras");
return o;
}
class Reader {
constructor(a) { this.a = a; this.i = 0; }
b() { if (this.i >= this.a.length) throw new Error("short reply"); return this.a[this.i++]; }
v() { const lo = this.b(); return v14dec(lo, this.b()); }
s() { let s = ""; for (;;) { const c = this.b(); if (!c) return s; s += String.fromCharCode(c); } }
}
const parse = {
[CMD.INFO](a) {
const r = new Reader(a);
const o = { version: r.s(), nengines: r.b(), pcount: r.b(), gcount: r.b(), nstep: r.b(), pe0: r.b(), engines: [] };
for (let i = 0; i < o.nengines; i++) o.engines.push(r.s());
o.chainRows = 0;
o.ntrk = r.i < a.length ? r.b() : 0; /* v3: tracks (0 = older firmware, one instrument) */
o.uiCaps = 0;
const trailer = a.slice(r.i);
if (trailer[0] === 16) o.chainRows = 16; /* existing v6 SONG capability */
if (trailer.length >= 4 && trailer[0] === 16 && trailer[1] === 0x55 && trailer[2] === 1)
o.uiCaps = trailer[3] & 15; /* tagged preferences; never interpret old PR bytes as SONG */
o.motionMax = 0; o.chance = false; o.backupCaps = 0;
if (o.uiCaps && trailer[4] === 0x4d && trailer[5] === 1 && trailer[6] === 64) {
o.motionMax = 64; o.chance = trailer[7] === 1;
if (trailer[8] === 0x42 && trailer[9] === 1) o.backupCaps = trailer[10] & 3;
}
o.fm6 = null; /* FM6 patches (cmds 68..71): the factory and bank slot counts */
o.syncCaps = 0; /* live sync: bit 0 WATCH while on keeps pending pushes, bit 1 no RELOAD */
o.ratchet = 0; /* a step's ratchet (STEP_SET's byte after the chance), 0 = none */
o.stepx = 0; /* (Skiff W1) a step's FLAM, COND, NUDGE after it: the COND count, 0 = none */
o.locks = false; /* (1.1, INFO 4C 01) MOTION ops 5..7: locks, their kinds */
o.menuCount = 0; /* (1.0.4, INFO 4E 01 count) the MENU settings MENU_DESC offers */
o.kitLanes = 0; /* (Skiff W3, INFO 4B 01 8) KIT_GET / KIT_PUT: the DRUM-X kit's lanes */
o.skiff = 0; /* (Skiff W3, INFO 57 01 caps) bits: 0 TRANSPORT, 1 PROJ_NAME, 2 POOL, 3 LIST,
4 PERFORM */
for (const p of [8, 11]) if (o.motionMax && trailer[p] === 0x46 && trailer[p + 1] === 1) { /* for the editor's */
o.fm6 = { factory: trailer[p + 2], bank: trailer[p + 3], caps: 0 }; /* PRESET / G_ENGSEL */
if (trailer[p + 4] === 0x53 && trailer[p + 5] === 1) o.syncCaps = trailer[p + 6] & 3;
/* FM6 v2 (1.0.3): bit 0 no bank (SLOT F1..F8, 8 = OWN), bit 1 the user presets carry their patch (target 3) */
if (trailer[p + 7] === 0x50 && trailer[p + 8] === 1) o.fm6.caps = trailer[p + 9] & 3;
let r = trailer[p + 7] === 0x50 ? p + 10 : p + 7; /* RATCH after FM6 v2 */
if (trailer[r] === 0x4E && trailer[r + 1] === 1) { o.menuCount = trailer[r + 2]; r += 3; } /* and the MENU settings (1.0.4) */
if (o.syncCaps && trailer[r] === 0x52 && trailer[r + 1] === 1) o.ratchet = trailer[r + 2]; /* RATCH: max hits */
if (trailer[r] === 0x52 && trailer[r + 1] === 1) r += 3;
if (trailer[r] === 0x4C && trailer[r + 1] === 1) { o.locks = true; r += 3; } /* parameter locks (1.1) */
if (trailer[r] === 0x54 && trailer[r + 1] === 1) { /* (Skiff phase 6) the light */
o.light = { tracks: trailer[r + 2], engines: trailer[r + 3] | trailer[r + 4] << 7 | trailer[r + 5] << 14 }; /* tracks */
r += 6;
}
if (trailer[r] === 0x43 && trailer[r + 1] === 1) { o.stepx = trailer[r + 2]; r += 3; } /* (Skiff W1) FLAM COND NUDGE */
if (trailer[r] === 0x4B && trailer[r + 1] === 1) { o.kitLanes = trailer[r + 2]; r += 3; } /* (Skiff W3) the DRUM-X kit */
if (trailer[r] === 0x57 && trailer[r + 1] === 1) { o.skiff = trailer[r + 2] & 31; r += 3; } /* (Skiff W3) TRANSPORT .. PERFORM */
if (trailer[r] === 0x49 && trailer[r + 1] === 1) { /* (Skiff 1.3) wide ids: */
o.pcount = trailer[r + 2] | trailer[r + 3] << 7; /* P_COUNT and P_E0 whole */
o.pe0 = trailer[r + 4] | trailer[r + 5] << 7;
}
}
o.light = o.light || { tracks: 0, engines: 0 }; /* the tracks that may not play some engines, and those engines */
return o;
},
[CMD.UI_STATE](a) {
const r = new Reader(a), o = { caps: r.b(), palette: r.b(), font: r.b(), monitor: r.b(), filter: r.b() };
const u28 = () => r.b() | r.b() << 7 | r.b() << 14 | r.b() << 21;
o.favoriteSig = u28(); o.bankSig = u28(); return o;
},
[CMD.UI_SET](a) { const r = new Reader(a); return { rc: r.b(), id: r.b(), value: r.b(), ...parse[CMD.UI_STATE](a.slice(3)) }; },
[CMD.UI_PALETTES](a) { const r = new Reader(a), n = r.b(); return Array.from({ length: n }, () => r.s()); },
[CMD.FAV_GET](a) {
const r = new Reader(a), rc = r.b(); if (rc) return { rc };
const o = { rc, engine: r.b(), start: r.v(), count: r.b() };
o.values = Array.from({ length: o.count }, () => !!r.b()); return o;
},
[CMD.FAV_SET](a) {
const r = new Reader(a), rc = r.b();
return rc === 0 || rc === 3 || rc === 4 ? { rc, engine: r.b(), preset: r.v(), on: !!r.b() } : { rc };
},
[CMD.GET](a) { const r = new Reader(a); return { ...widIn(r.b(), r.b()), value: r.v() }; },
[CMD.SET](a) { return parse[CMD.GET](a); },
/* needs the counts from INFO */
[CMD.DUMP](a, info) {
const r = new Reader(a);
const o = { engine: r.b(), preset: r.b(), p: [], g: [] };
for (let i = 0; i < info.pcount; i++) o.p.push(r.v());
for (let i = 0; i < info.gcount; i++) o.g.push(r.v());
return o;
},
[CMD.DESC](a) {
const r = new Reader(a);
const o = { ...widIn(r.b(), r.b()), fmt: r.b(), min: r.v(), max: r.v(), def: r.v(), label: r.s(), unit: r.s(), names: [] };
if (o.fmt === F.ENUM) for (let i = 0; i <= o.max - o.min && i < 24; i++) o.names.push(r.s());
return o;
},
[CMD.STEP_GET](a) {
const r = new Reader(a);
const o = { index: r.b(), n: r.b(), notes: [r.b(), r.b(), r.b(), r.b()], time: r.b(), flags: r.b(), vel: r.b() };
return readHits(r, o);
},
[CMD.STEP_SET](a) { return parse[CMD.STEP_GET](a); },
[CMD.PRESET](a) { const r = new Reader(a); return { engine: r.b(), preset: r.b() }; },
/* (Skiff W3) MENU_DESC: index, id (127: past the list), kind (0 names, 1 a number), value, min, max, name, the names (0)
or a unit (1); (1.0.5) the device's tab and its name (older: tab -1) */
[CMD.MENU_DESC](a) {
const r = new Reader(a), o = { index: r.b(), id: r.b() };
if (o.id === 127) return o;
Object.assign(o, { kind: r.b(), value: r.v(), min: r.v(), max: r.v(), name: r.s(), names: null, unit: "", tab: -1, tabName: "" });
if (o.kind === 0) { o.names = []; for (let i = 0; i <= o.max - o.min; i++) o.names.push(r.s()); }
else o.unit = r.s();
if (r.i < a.length) { o.tab = r.b(); o.tabName = r.s(); }
return o;
},
[CMD.MENU_SET](a) { const r = new Reader(a); return { rc: r.b(), id: r.b(), value: r.v() }; },
/* (Skiff W3) a DRUM-X kit lane: lane, wave, filter, snap, pitch mod (shape), drive, A's five values, B's five */
[CMD.KIT_GET](a) {
const r = new Reader(a), o = { lane: r.b(), wave: r.b(), filt: r.b(), snap: !!r.b(), pmod: r.b(), drive: !!r.b() };
o.a = [0, 1, 2, 3, 4].map(() => r.b()); o.b = [0, 1, 2, 3, 4].map(() => r.b());
return o;
},
[CMD.KIT_PUT](a) { return parse[CMD.KIT_GET](a); },
/* (Skiff W3) TRANSPORT: rc, playing, counting in, the request the audio has yet to take (1 start, 2 stop, 3 restart),
the armed tracks (a bit each), the selected track */
[CMD.TRANSPORT](a) {
const r = new Reader(a);
return { rc: r.b(), playing: !!r.b(), counting: !!r.b(), pending: r.b(), rec: r.b(), sel: r.b() };
},
/* (Skiff W3) PROJ_NAME: op, rc (0 done, 1 refused, 2 failed), the music's slot (-1: none), changed since, its name,
each slot: used, its name */
[CMD.PROJ_NAME](a) {
const r = new Reader(a), o = { op: r.b(), rc: r.b(), cur: r.b(), changed: !!r.b(), name: r.s() };
if (o.cur === 127) o.cur = -1;
o.slots = [0, 1, 2, 3].map(() => ({ used: !!r.b(), name: r.s() }));
return o;
},
/* (Skiff W3) POOL: op, rc (0 cleared, 1 nothing to clear, 2 in use, 3 playing, 4 failed), each pattern: LEN (0 empty),
what uses it */
[CMD.POOL](a) {
const r = new Reader(a), o = { op: r.b(), rc: r.b(), pats: [] };
for (let i = 0; i < 64; i++) o.pats.push({ len: r.b(), refs: r.b() });
return o;
},
/* (Skiff W3) LIST: op, rc (0 done, 1 empty, 2 without its automation, 3 playing, 4 PATTERNS FULL, 5 failed), SONG, each
track: the entry it is on, the one staged (-1: none), its pattern (0..63, -1 none), its 16 entries (pattern 1..64,
0 empty; REPS 1..16) */
[CMD.LIST](a) {
const r = new Reader(a), o = { op: r.b(), rc: r.b(), song: !!r.b(), tracks: [] }, n = (v) => (v === 127 ? -1 : v);
while (r.i < a.length) {
const x = { cur: n(r.b()), next: n(r.b()), pat: n(r.b()), ent: [] };
for (let e = 0; e < 16; e++) x.ent.push({ pat: r.b(), reps: r.b() + 1 });
o.tracks.push(x);
}
return o;
},
/* (Skiff W3) PERFORM: op, rc, LAUNCH (0 LOOP .. 3 NOW), the scene last recalled or stored (-1 none), the scenes kept
(a bit each), each track: muted, its mute staged (0 none, 1 to unmute, 2 to mute) */
[CMD.PERFORM](a) {
const r = new Reader(a), o = { op: r.b(), rc: r.b(), launch: r.b(), last: r.b(), scenes: 0, tracks: [] };
if (o.last === 127) o.last = -1;
o.scenes = r.b() | r.b() << 7 | r.b() << 14;
while (r.i < a.length) o.tracks.push({ muted: !!r.b(), staged: r.b() });
return o;
},
[CMD.PROJECT](a) { const r = new Reader(a); return { op: r.b(), slot: r.b(), used: r.b() }; },
[CMD.SONG](a) {
const r = new Reader(a);
const o = { op: r.b(), rc: r.b(), count: r.b(), playing: r.b(), row: r.b(), remaining: r.b(), rows: [] };
for (let i = 0; i < o.count; i++) o.rows.push({ slot: r.b(), repeat: r.b() });
return o;
},
[CMD.MOTION](a) {
const r = new Reader(a), o = { track: r.b(), rc: r.b(), on: !!r.b(), count: r.b(), max: r.b(), events: [] };
const kinds = o.count > 0 && a.length === 5 + o.count * 5; /* (1.1: after ops 5..7, a kind per record: 0 automation, 1 lock;
* none to say with none) */
if (o.count > o.max || o.max !== 64 || (a.length !== 5 + o.count * 4 && !kinds)) throw new Error("Invalid motion reply");
for (let i = 0; i < o.count; i++) { const s = r.b(); o.events.push({ step: s & 63, param: r.b() | (s >> 6 & 1) << 7, value: r.v() }); } /* ((1.3) bit 6:
the id's bit 7) */
o.kinds = kinds;
if (kinds) o.events.forEach((e) => { e.lock = r.b() === 1; });
return o;
},
[CMD.NAMES](a) {
const r = new Reader(a);
const o = { engine: r.b(), names: [] };
const n = r.b();
for (let i = 0; i < n; i++) o.names.push(r.s());
o.titles = [];
try { o.titles.push(r.s(), r.s()); } catch (e) { o.titles = []; } /* older firmware: no page titles */
return o;
},
[CMD.SMP_BEGIN](a) { const r = new Reader(a); return { slot: r.b(), rc: r.b() }; },
[CMD.SMP_WRITE](a) { const r = new Reader(a); return { slot: r.b(), offset: r.b() | (r.b() << 7) | (r.b() << 14), rc: r.b() }; },
[CMD.SMP_END](a) { return parse[CMD.SMP_BEGIN](a); },
[CMD.SMP_ERASE](a) { return parse[CMD.SMP_BEGIN](a); },
[CMD.SMP_INFO](a) {
const r = new Reader(a);
const o = { nslots: r.b(), slotKiB: r.b(), slots: [] };
for (let i = 0; i < o.nslots; i++) o.slots.push({ zones: r.b(), name: r.s(), kib: r.b() });
return o;
},
[CMD.UP_LIST](a) {
const r = new Reader(a);
const o = { start: r.b(), count: r.b(), total: r.b(), slots: [] };
for (let i = 0; i < o.count; i++) o.slots.push({ slot: o.start + i, used: r.b(), engine: r.b(), name: r.s() });
return o;
},
/* needs P_COUNT from INFO */
[CMD.UP_GET](a, info) {
const r = new Reader(a);
const o = { slot: r.b(), used: r.b(), engine: r.b(), name: r.s(), p: [], pattern: [] };
for (let i = 0; i < info.pcount; i++) o.p.push(r.v());
for (let i = 0; i < UP.PAT; i++) o.pattern.push([r.b(), r.b()]);
o.grid = null; /* v5: kind 1 = a drum grid (the pairs its low 7 bits), 16 x hi */
if (r.i < a.length && r.b() === 1 && r.i + UP.PAT <= a.length) {
o.grid = o.pattern.map(([h, c]) => { const x = r.b(), hit = h | (x & 1) << 7; return [hit, (c | (x & 2) << 6) & hit]; });
o.pattern = null;
}
return o;
},
[CMD.UP_PUT](a) { return parse[CMD.SMP_BEGIN](a); },
[CMD.UP_STORE](a) { return parse[CMD.SMP_BEGIN](a); },
[CMD.UP_LOAD](a) { return parse[CMD.SMP_BEGIN](a); },
[CMD.UP_ERASE](a) { return parse[CMD.SMP_BEGIN](a); },
[CMD.WATCH](a) { return { on: new Reader(a).b() }; },
[CMD.CHANGED](a) { return parse[CMD.GET](a); },
[CMD.RELOAD](a) { const r = new Reader(a); return { engine: r.b(), preset: r.b(), track: r.i < a.length ? r.b() : 0 }; },
[CMD.PING](a) { return {}; },
[CMD.STEP_CHANGED](a) { const r = new Reader(a); return { index: r.b(), track: r.i < a.length ? r.b() : 0 }; },
/* v3: tracks (1.0: four synth parts; earlier firmware: track 4 the drum part, engine byte NENGINES) */
[CMD.TRACK](a) {
const r = new Reader(a);
const o = { sel: r.b(), ntrk: r.b(), tracks: [] };
for (let i = 0; i < o.ntrk; i++) o.tracks.push({ engine: r.b(), preset: r.b(), level: r.v(), mute: r.b(), armed: r.b() });
return o;
},
[CMD.TRACK_MIX](a) { const r = new Reader(a); return { track: r.b(), level: r.v(), mute: r.b() }; },
[CMD.TRACK_DUMP](a, info) {
const r = new Reader(a);
const o = { track: r.b(), engine: r.b(), preset: r.b(), p: [] };
for (let i = 0; i < info.pcount; i++) o.p.push(r.v());
return o;
},
[CMD.TRACK_STEP](a) {
const r = new Reader(a);
return readHits(r, { track: r.b(), index: r.b(), n: r.b(), notes: [r.b(), r.b(), r.b(), r.b()], time: r.b(), flags: r.b(), vel: r.b() });
},
/* v4: a parameter of any track (the selection stays), and its push for a track that is not selected */
[CMD.TRACK_PARAM](a) { const r = new Reader(a), t = r.b(); return { track: t & 63, id: r.b() | (t >> 6 & 1) << 7, value: r.v() }; }, /* ((1.3)
bit 6 of the track byte: the id's bit 7) */
[CMD.TRACK_CHANGED](a) { return parse[CMD.TRACK_PARAM](a); },
/* FM6 patches: target 0 a track, 1 the bank (retired in 1.0.3: rc 3), 2 a factory patch, 3 a user preset's patch
(INFO fm6.caps bit 1); packed: the 128-byte record */
[CMD.FM6_GET](a) { return { target: a[0], index: a[1], rc: a[2], packed: a[2] ? null : a.slice(3, 3 + 128) }; },
[CMD.FM6_PUT](a) { return { target: a[0], index: a[1], rc: a[2] }; },
[CMD.FM6_LIST](a) {
const r = new Reader(a), o = { factory: r.b(), bank: r.b(), slots: [] };
for (let i = 0; i < o.factory + o.bank; i++) { const used = r.b(); o.slots.push({ used: !!used, name: r.s() }); }
return o;
},
[CMD.FM6_ERASE](a) { return { index: a[0], rc: a[1] }; },
};
/* a name the device accepts: printable ASCII, 1..12 characters */
/* (Skiff W3) a project's name as the device keeps it: upper case, printable ASCII, 12 at most ("" = none) */
function cleanProjName(s) { return String(s ?? "").toUpperCase().replace(/[^\x20-\x7E]/g, "").trim().slice(0, 12); }
function upName(s) { return String(s ?? "").replace(/[^\x20-\x7E]/g, "").trim().slice(0, UP.NAME_MAX) || "PATCH"; }
/* (Skiff 1.3, EDITOR_PROTOCOL.md "Wide ids") a track parameter from 128 on goes out as scope 2, id - 128, and comes back
so: the editor keeps scope 0 and the whole id */
const widOut = (scope, id) => (scope === 0 && id >= 128 ? [2, id - 128] : [scope, id]);
const widIn = (scope, id) => (scope === 2 ? { scope: 0, id: id + 128 } : { scope, id });
const req = {
uiState: () => [CMD.UI_STATE, []],
uiSet: (id, value) => [CMD.UI_SET, [id, value]],
uiPalettes: () => [CMD.UI_PALETTES, []],
favGet: (engine, start, count) => [CMD.FAV_GET, [engine, ...v14enc(start), count]],
favSet: (engine, preset, on) => [CMD.FAV_SET, [engine, ...v14enc(preset), on ? 1 : 0]],
info: () => [CMD.INFO, []],
get: (scope, id) => [CMD.GET, widOut(scope, id)],
set: (scope, id, v) => [CMD.SET, [...widOut(scope, id), ...v14enc(v)]],
dump: () => [CMD.DUMP, []],
desc: (scope, id) => [CMD.DESC, widOut(scope, id)],
stepGet: (i) => [CMD.STEP_GET, [i]],
stepSet: (i, st) => {
const n = Math.max(0, Math.min(4, st.n | 0));
const notes = [0, 1, 2, 3].map((k) => (st.notes[k] | 0) & 0x7F);
return [CMD.STEP_SET, [i, n, ...notes, Math.max(0, Math.min(2, st.time | 0)), st.flags & 3, (st.vel | 0) & 0x7F,
...(st.hit == null && st.chance == null ? [] : hitsEnc(st.hit | 0, st.acc | 0)),
...(st.chance == null ? [] : [Math.max(0, Math.min(100, st.chance | 0))]),
...(st.chance == null || st.ratchet == null ? [] : [Math.max(1, Math.min(4, st.ratchet | 0))]), /* (only after the chance) */
...(st.chance == null || st.ratchet == null || st.cond == null ? [] : /* (Skiff W1) FLAM, COND, */
[st.flam ? 1 : 0, Math.max(0, Math.min(TC_NAMES.length - 1, st.cond | 0)), Math.max(0, Math.min(63, (st.nudge | 0) + 32))])]]; /* NUDGE */
},
preset: (e, p) => [CMD.PRESET, [e & 0x7F, p & 0x7F]],
project: (op, slot) => { if (![0, 1, 2].includes(op)) throw new Error("bad PROJECT op"); return [CMD.PROJECT, [op, slot & 3]]; }, /* 0 load, 1 save, 2 query */
song: (op = 0, rows = []) => {
if (![0, 1, 2, 3].includes(op) || rows.length > 16 || rows.some((r) => !Number.isInteger(r.slot) || r.slot < 0 || r.slot > 3 || !Number.isInteger(r.repeat) || r.repeat < 1 || r.repeat > 16)) throw new Error("bad SONG rows");
return [CMD.SONG, op === 1 ? [op, rows.length, ...rows.flatMap((r) => [r.slot, r.repeat])] : [op]];
},
motion: (track, op = 0, arg = {}, ntrk = 1) => { /* ntrk: INFO's (the device's tracks) */
if (!Number.isInteger(track) || track < 0 || track >= ntrk || ![0, 1, 2, 3, 4, 5, 6, 7].includes(op)) throw new Error("Invalid motion request");
return [CMD.MOTION, [track, ...(op === 0 ? [] : op === 1 ? [op, arg.on ? 1 : 0] : op === 2 || op === 7 ? [op] :
op === 6 ? [op, arg.step === 127 ? 127 : arg.step & 63] : /* (1.1: 5 a lock, 6 a step's locks, 7 the query with the kinds) */
[op, (arg.step & 63) | (arg.param >> 7 & 1) << 6, arg.param & 127, ...(op === 3 || op === 5 ? v14enc(arg.value) : [])])]];
},
names: (e) => [CMD.NAMES, [e & 0x7F]],
smpBegin: (s) => [CMD.SMP_BEGIN, [s & 0x7F]],
smpWrite: (s, off, bytes) => [CMD.SMP_WRITE, [s & 0x7F, off & 0x7F, (off >> 7) & 0x7F, (off >> 14) & 0x7F, ...pack7(bytes)]],
smpEnd: (s, hdr) => [CMD.SMP_END, [s & 0x7F, ...pack7(hdr)]],
smpErase: (s) => [CMD.SMP_ERASE, [s & 0x7F]],
smpInfo: () => [CMD.SMP_INFO, []],
upList: (start, count) => [CMD.UP_LIST, [start & 0x7F, Math.max(1, Math.min(UP.LIST_MAX, count | 0))]],
upGet: (s) => [CMD.UP_GET, [s & 0x7F]],
/* patch: {engine, name, p: P_COUNT values, pattern: 16 x [note, flags] or grid: 16 x [hit, acc] (v5: kind 1)} */
upPut: (s, pt) => [CMD.UP_PUT, [s & 0x7F, pt.engine & 0x7F, ...strEnc(upName(pt.name)), ...pt.p.flatMap((v) => v14enc(v ?? 0)),
...(pt.grid
? [...Array.from({ length: UP.PAT }, (_, i) => hitsEnc(...(pt.grid[i] || [0, 0])).slice(0, 2)).flat(), 1,
...Array.from({ length: UP.PAT }, (_, i) => hitsEnc(...(pt.grid[i] || [0, 0]))[2])]
: Array.from({ length: UP.PAT }, (_, i) => { const x = (pt.pattern || [])[i] || [0, 0]; return [x[0] & 0x7F, x[1] & 7]; }).flat())]],
upStore: (s, name) => [CMD.UP_STORE, [s & 0x7F, ...strEnc(name ? upName(name) : "")]], /* "": the device names it ("ANALOG 07") */
upLoad: (s) => [CMD.UP_LOAD, [s & 0x7F]],
upErase: (s) => [CMD.UP_ERASE, [s & 0x7F]],
/* on: 1 = pushes; 3 = also TRACK_CHANGED (v4 firmware answers 3, older firmware 1) */
watch: (on) => [CMD.WATCH, [on === 3 ? 3 : on ? 1 : 0]],
ping: () => [CMD.PING, []],
/* v3: tracks 0..3 */
track: (sel) => [CMD.TRACK, sel == null ? [] : [sel & 0x7F]],
trackMix: (tr, level, mute) => [CMD.TRACK_MIX, level == null ? [tr & 0x7F] : [tr & 0x7F, ...v14enc(level), mute ? 1 : 0]],
trackDump: (tr) => [CMD.TRACK_DUMP, [tr & 0x7F]],
trackStep: (tr, i, st) => [CMD.TRACK_STEP, st ? [tr & 0x7F, ...req.stepSet(i, st)[1]] : [tr & 0x7F, i & 0x7F]],
/* v4: get (v == null) or set parameter id (P_*) of track tr, clamped as SET */
trackParam: (tr, id, v) => [CMD.TRACK_PARAM, [(tr & 63) | (id >> 7 & 1) << 6, id & 0x7F, ...(v == null ? [] : v14enc(v))]],
/* FM6 patches (firmware with info.fm6) */
fm6Get: (target, i) => [CMD.FM6_GET, [target & 0x7F, i & 0x7F]],
fm6Put: (target, i, packed) => [CMD.FM6_PUT, [target & 0x7F, i & 0x7F, ...packed.map((x) => x & 0x7F)]],
fm6List: () => [CMD.FM6_LIST, []],
fm6Erase: (i) => [CMD.FM6_ERASE, [i & 0x7F]],
menuDesc: (i) => [CMD.MENU_DESC, [i & 0x7F]],
menuSet: (id, v) => [CMD.MENU_SET, [id & 0x7F, ...v14enc(v)]],
kitGet: (lane) => [CMD.KIT_GET, [lane & 7]],
kitPut: (k) => [CMD.KIT_PUT, [k.lane, k.wave, k.filt, +k.snap, k.pmod, +k.drive, ...k.a, ...k.b].map((x) => x & 0x7F)],
transport: (op = 0) => [CMD.TRANSPORT, op ? [op] : []], /* 1 PLAY, 2 STOP, 3 RESTART, 4 REC; none: the state */
pool: (id) => [CMD.POOL, id == null ? [] : [1, id & 63]], /* id: CLEAR it; none: the pool */
/* 1 SET (v: pattern 1..64), 2 COPY, 3 PLAY, 4 CLEAR, 5 REPS (v: 1..16) entry e of track k; 6 SONG (k: on); none: the lists */
list: (op = 0, k = 0, e = 0, v = null) => [CMD.LIST, !op ? [] : op === 6 ? [6, k ? 1 : 0] : v == null ? [op, k, e] : [op, k, e, v]],
perform: (op = 0, v = 0) => [CMD.PERFORM, !op ? [] : op === 4 ? [4] : [op, v]], /* 1 STORE, 2 RECALL, 3 MUTE, 4 CANCEL, 5 LAUNCH */
projName: (op = 0, slot = 0, name = "") => [CMD.PROJ_NAME, op ? [op, slot & 3, ...strEnc(cleanProjName(name))] : []], /* 1 SAVE AS, 2 RENAME */
};
/* (Skiff W3) the device's MENU settings, each as MENU_DESC describes it (none asked of firmware without them) */
async function readDeviceMenu(rq, info) {
const items = [];
for (let i = 0; i < (info.menuCount | 0); i++) {
const d = parse[CMD.MENU_DESC](await rq(req.menuDesc(i)));
if (d.id === 127) break;
items.push(d);
}
return items;
}
/* which reply belongs to which request (the device echoes these) */
function replyMatches(cmd, args, a) {
switch (cmd) {
case CMD.MOTION: return a[0] === args[0];
case CMD.MENU_DESC: return a[0] === args[0];
case CMD.MENU_SET: return a[1] === args[0];
case CMD.KIT_GET: case CMD.KIT_PUT: return a[0] === args[0];
case CMD.PROJ_NAME: case CMD.POOL: case CMD.LIST: case CMD.PERFORM: return a[0] === (args[0] || 0);
case CMD.BACKUP_GET: return a[0] === args[0] && a.slice(2, 7).every((v, i) => v === args[i + 1]);
case CMD.BACKUP_PUT: return a[0] === args[0] && a[1] === args[1];
case CMD.UI_SET: return a[1] === args[0] && a[2] === args[1];
case CMD.FAV_GET: case CMD.FAV_SET:
return ![0, 3, 4].includes(a[0]) || (a[1] === args[0] && a[2] === args[1] && a[3] === args[2] && a[4] === args[3]);
case CMD.GET: case CMD.SET: case CMD.DESC: return a[0] === args[0] && a[1] === args[1];
case CMD.STEP_GET: case CMD.STEP_SET: case CMD.NAMES:
case CMD.SMP_BEGIN: case CMD.SMP_END: case CMD.SMP_ERASE: return a[0] === args[0];
case CMD.SMP_WRITE: return a[0] === args[0] && a[1] === args[1] && a[2] === args[2] && a[3] === args[3];
case CMD.SONG: return a[0] === args[0];
case CMD.FM6_GET: case CMD.FM6_PUT: return a[0] === args[0] && a[1] === args[1];
case CMD.FM6_ERASE: return a[0] === args[0];
case CMD.PROJECT: return a[0] === args[0] && a[1] === args[1];
case CMD.UP_LIST: case CMD.UP_GET: case CMD.UP_PUT: case CMD.UP_STORE: case CMD.UP_LOAD: case CMD.UP_ERASE:
case CMD.TRACK_MIX: case CMD.TRACK_DUMP: return a[0] === args[0];
case CMD.WATCH: return (a[0] & 1) === (args[0] & 1); /* bit 1: v4 firmware only */
case CMD.TRACK_STEP: case CMD.TRACK_PARAM: return a[0] === args[0] && a[1] === args[1];
default: return true;
}
}
/* strict request/response: one frame in flight, the rest queued. Push frames (CHANGED, RELOAD,
STEP_CHANGED) can come at any time, also between a request and its reply: they go to onPush. */
class Link {
constructor(send, opts = {}) {
this.sendRaw = send;
this.q = [];
this.cur = null;
this.closed = false;
this.lastSent = 0; /* Date.now() of the last frame sent (WATCH keep-alive) */
this.timeout = opts.timeout || 300;
this.onUnknown = opts.onUnknown || (() => {});
this.onTimeout = opts.onTimeout || (() => {});
this.onPush = opts.onPush || (() => {});
this.onGap = opts.onGap || (() => {}); /* (ms) nothing was sent for that long (WATCH may have ended) */
}
get idle() { return !this.cur && !this.q.length; }
hasQueued(key) { return this.q.some((r) => r.key === key); }
/* r = [cmd, args]; opt: {timeout, retries, key (coalesce queued requests: the latest args win), front,
quiet (a timeout is expected: no onTimeout)} */
request(r, opt = {}) {
if (this.closed) return Promise.reject(new Error("closed"));
const [cmd, args] = r;
if (opt.key) {
const old = this.q.find((x) => x.key === opt.key);
if (old) { old.cmd = cmd; old.args = args; return old.promise; }
}
let res, rej;
const promise = new Promise((a, b) => { res = a; rej = b; });
const item = { cmd, args, key: opt.key, res, rej, promise, quiet: !!opt.quiet,
timeout: opt.timeout || this.timeout, retries: opt.retries ?? 1 };
if (opt.front) this.q.unshift(item); else this.q.push(item);
this.pump();
return promise;
}
pump() {
if (this.cur || this.closed || !this.q.length) return;
this.cur = this.q.shift();
this.fire();
}
fire() {
const c = this.cur;
const now = Date.now();
if (this.lastSent && now - this.lastSent > 2500) this.onGap(now - this.lastSent);
this.lastSent = now;
try { this.sendRaw(frame(c.cmd, c.args)); } catch (e) { this.finish(null, e); return; }
c.timer = setTimeout(() => {
if (this.cur !== c) return;
if (c.retries-- > 0) { this.fire(); return; }
if (!c.quiet) this.onTimeout(c.cmd);
this.finish(null, new Error("timeout (cmd " + c.cmd + ")"));
}, c.timeout);
}
finish(val, err) {
const c = this.cur;
if (!c) return;
clearTimeout(c.timer);
this.cur = null;
if (err) c.rej(err); else c.res(val);
this.pump();
}
/* raw incoming MIDI bytes */
receive(data) {
const f = unframe(data);
if (!f) return; /* not ours (notes, clock, other SysEx) */
if (PUSH.has(f.cmd)) { this.onPush(f); return; }
const c = this.cur;
if (!c || f.cmd !== c.cmd || !replyMatches(c.cmd, c.args, f.a)) { this.onUnknown(f); return; }
this.finish(f.a);
}
close() {
this.closed = true;
const all = (this.cur ? [this.cur] : []).concat(this.q);
if (this.cur) clearTimeout(this.cur.timer);
this.cur = null;
this.q = [];
for (const r of all) r.rej(new Error("closed"));
}
}
/* ------------------------------------------------------------- formatting --- */
const NOTE_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
const noteName = (n) => NOTE_NAMES[n % 12] + (Math.floor(n / 12) - 1); /* 60 = C4 */
/* a note token: a number or a note name (C4, F#3, Bb2) */
function parseNote(tok) {
if (/^\d+$/.test(tok)) { const n = +tok; return n <= 127 ? n : null; }
const m = /^([A-Ga-g])([#b]?)(-?\d)$/.exec(tok);
if (!m) return null;
const base = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 }[m[1].toUpperCase()];
const n = base + (m[2] === "#" ? 1 : m[2] === "b" ? -1 : 0) + (parseInt(m[3], 10) + 1) * 12;
return n >= 0 && n <= 127 ? n : null;
}
/* "C4 E4 G4" -> [60, 64, 67]; null on a bad token or more than 4 notes */
function parseNotes(s) {
const t = s.trim().split(/[\s,]+/).filter(Boolean);
if (t.length > 4) return null;
const out = t.map(parseNote);
return out.includes(null) ? null : out;
}
/* close to the device's param_format (params.c), tables from tools/gen_tables.py */
function fmtValue(d, v) {
const sign = (x) => (x > 0 ? "+" + x : String(x));
switch (d.fmt) {
case F.PCT: return [String(d.max === 100 ? v : Math.trunc((v * 100 + 63) / 127)), "%"]; /* 0..100 (SWG): the value */
case F.BIPCT: return [sign(Math.trunc(v * 100 / (v > 0 ? 63 : 64))), "%"]; /* (Skiff 1.3: +100 at the top, as the device) */
case F.TIME: {
const ms10 = Math.round(10 * Math.pow(10000, (v & 127) / 127));
if (ms10 < 100) return [(ms10 / 10).toFixed(1), "ms"];
if (ms10 < 10000) return [String(Math.round(ms10 / 10)), "ms"];
return [(ms10 / 10000).toFixed(2), "s"];
}
case F.LFOHZ: { const h = 0.05 * Math.pow(800, (v & 127) / 127); return [h < 10 ? h.toFixed(2) : h.toFixed(1), "Hz"]; }
case F.CUTOFF: { const h = 30 * Math.pow(16000 / 30, (v & 127) / 127); return h < 1000 ? [String(Math.round(h)), "Hz"] : [(h / 1000).toFixed(1), "kHz"]; }
case F.DB: return v <= 0 ? ["OFF", ""] : [((v - 112) / 2).toFixed(1), "dB"];
case F.SEMI: return [sign(v), "st"];
case F.ENUM: return [d.names[v - d.min] ?? String(v), d.unit || ""];
case F.BPM: return [String(v), "BPM"];
case F.NOTE: return [NOTE_NAMES[((v % 12) + 12) % 12], ""];
case F.ONOFF: return [v ? "ON" : "OFF", ""];
case F.STEPS: return [String(v), "STEP"];
case F.ST16: { const t = Math.trunc(((v - 64) * 30 + (v < 64 ? -8 : 8)) / 16); return [(t > 0 ? "+" : "") + (t / 10).toFixed(1), "st"]; }
default: return [String(v), d.unit || ""];
}
}
/* ---------------------------------------------------------- user samples --- */
/* A port of tools/sampleio.py (read_any_wav, resample, to_int16, ima_encode, user_slot),
byte for byte: web/test_web.mjs compares them. */
const SMP = { SLOT_SIZE: 0x14000, DATA_OFF: 512, RATE: 22050, HDR_LEN: 32 + 16 * 28, MAX_ZONES: 16 };
SMP.MAX_DATA = SMP.SLOT_SIZE - SMP.DATA_OFF;
/* groups of up to 7 bytes, each preceded by their top bits */
function pack7(b) {
const out = [];
for (let i = 0; i < b.length; i += 7) {
const g = Array.from(b.slice(i, i + 7));
out.push(g.reduce((m, x, j) => m | (((x >> 7) & 1) << j), 0));
for (const x of g) out.push(x & 0x7F);
}
return out;
}
function unpack7(a) {
const out = [];
for (let i = 0; i < a.length; i += 8) {
const top = a[i];
for (let j = 0; j < 7 && i + 1 + j < a.length; j++) out.push(a[i + 1 + j] | (((top >> j) & 1) << 7));
}
return Uint8Array.from(out);
}
const CRC_TABLE = (() => {
const t = new Uint32Array(256);
for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; }
return t;
})();
function crc32(b) { let c = 0xFFFFFFFF; for (let i = 0; i < b.length; i++) c = CRC_TABLE[(c ^ b[i]) & 0xFF] ^ (c >>> 8); return (c ^ 0xFFFFFFFF) >>> 0; }
const IMA_STEP = [7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88,
97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658,
724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660,
4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818,
18500, 20350, 22385, 24623, 27086, 29794, 32767];
const IMA_IDX = [-1, -1, -1, -1, 2, 4, 6, 8];
/* IMA ADPCM, 4 bit, low nibble first, from predictor 0 / index 0 -> {data, pred, idx} (state at loopStart) */
function imaEncode(s, loopStart = 0) {
let pred = 0, idx = 0, atLoop = [0, 0];
const nib = new Uint8Array(s.length + (s.length & 1));
for (let n = 0; n < s.length; n++) {
if (n === loopStart) atLoop = [pred, idx];
const step = IMA_STEP[idx];
let diff = s[n] - pred, code = 0;
if (diff < 0) { code = 8; diff = -diff; }
let vd = step >> 3;
if (diff >= step) { code |= 4; diff -= step; vd += step; }
if (diff >= step >> 1) { code |= 2; diff -= step >> 1; vd += step >> 1; }
if (diff >= step >> 2) { code |= 1; vd += step >> 2; }
pred = Math.max(-32768, Math.min(32767, code & 8 ? pred - vd : pred + vd));
idx = Math.max(0, Math.min(88, idx + IMA_IDX[code & 7]));
nib[n] = code;
}
const out = new Uint8Array(nib.length >> 1);
for (let k = 0; k < nib.length; k += 2) out[k >> 1] = nib[k] | (nib[k + 1] << 4);
return { data: out, pred: atLoop[0], idx: atLoop[1] };
}
/* WAV: PCM 8/16/24/32 or float, any channel count, mixed to mono -> {sr, x} (gen_samples.read_any_wav) */
function parseWav(buf) {
const d = new Uint8Array(buf), v = new DataView(d.buffer, d.byteOffset, d.byteLength);
const id = (i) => String.fromCharCode(d[i], d[i + 1], d[i + 2], d[i + 3]);
if (d.length < 12 || id(0) !== "RIFF" || id(8) !== "WAVE") throw new Error("not a WAV file");
let i = 12, fmt = null, data = null;
while (i + 8 <= d.length) {
const cid = id(i), n = v.getUint32(i + 4, true);
if (cid === "fmt ") {
let tag = v.getUint16(i + 8, true);
const ch = v.getUint16(i + 10, true), sr = v.getUint32(i + 12, true), bits = v.getUint16(i + 22, true);
if (tag === 0xFFFE) tag = v.getUint16(i + 32, true);
fmt = { tag, ch, sr, bits };
} else if (cid === "data") {
data = [i + 8, Math.min(d.length, i + 8 + n)];
break;
}
i += 8 + n + (n & 1);
}
if (!fmt || !data) throw new Error("WAV without fmt/data");
const { tag, ch, sr, bits } = fmt, bps = bits >> 3, frame = bps * ch;
if (!(tag === 1 || tag === 3) || !bps || !ch) throw new Error("unsupported WAV format");
const nfr = Math.floor((data[1] - data[0]) / frame), x = new Float64Array(nfr);
for (let f = 0; f < nfr; f++) {
let acc = 0;
for (let c = 0; c < ch; c++) {
const o = data[0] + f * frame + c * bps;
let s;
if (tag === 3) s = bps === 4 ? v.getFloat32(o, true) : v.getFloat64(o, true);
else if (bps === 2) s = v.getInt16(o, true) / 32768;
else if (bps === 3) s = (((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) << 8) >> 8) / 8388608;
else if (bps === 4) s = v.getInt32(o, true) / 2147483648;
else s = (d[o] - 128) / 128;
acc += s;
}
x[f] = acc / ch;
}
return { sr, x };
}
/* gen_samples.resample: moving average over the ratio, then linear interpolation */
function resample(x, sr, to) {
if (sr === to) return Array.from(x);
if (sr > to) {
const k = Math.max(1, pyRound(sr / to));
if (k > 1) {
const y = new Array(x.length);
for (let i = 0; i < x.length; i++) { let s = 0; for (let j = i; j < Math.min(x.length, i + k); j++) s += x[j]; y[i] = s / k; }
x = y;
}
}
const step = sr / to, out = [];
let p = 0;
while (p < x.length - 1) { const i = Math.floor(p), f = p - i; out.push(x[i] * (1 - f) + x[i + 1] * f); p += step; }
return out;
}
function pyRound(v) { const f = Math.floor(v), r = v - f; return r > 0.5 ? f + 1 : r < 0.5 ? f : (f % 2 ? f + 1 : f); }
/* mono float -> int16, peak normalised to 30000 */
function normalize(x) {
let pk = 1e-9;
for (const v of x) pk = Math.max(pk, Math.abs(v));
return Int16Array.from(x, (v) => Math.max(-32768, Math.min(32767, Math.trunc(v / pk * 30000))));
}
/* a trimmed sample: raw (mono float at SMP.RATE) from a to b, a fade of FADE samples at both cut ends
* (no click where the sound was cut; none at the file's own start and end), normalised */
const FADE = 44; /* 2 ms at 22050 Hz */
function takeSample(raw, a, b) {
a = Math.max(0, Math.min(raw.length - 1, a | 0));
b = Math.max(a + 1, Math.min(raw.length, b | 0));
const x = Float64Array.from(raw.subarray ? raw.subarray(a, b) : raw.slice(a, b));
const n = Math.min(FADE, x.length >> 1);
for (let i = 0; i < n; i++) {
const g = i / n;
if (a > 0) x[i] *= g;
if (b < raw.length) x[x.length - 1 - i] *= g;
}
return normalize(x);
}
/* a trimming view [v0, v1) of n samples: zoomed by factor (< 1 in) around the fraction at of the
* view, then moved by pan views; at least 256 samples (~12 ms), inside [0, n) */
function zoomView(n, v0, v1, at, factor, pan) {
const min = Math.min(n, 256);
let span = Math.round(Math.max(min, Math.min(n, (v1 - v0) * factor)));
let c = v0 + at * (v1 - v0) + pan * span; /* the sample under the pointer stays under it */
let a = Math.round(c - at * span);
a = Math.max(0, Math.min(n - span, a));
return [a, a + span];
}
/* where the sound is: the first and last sample above rel x the peak, with a 5 ms pre-roll and a
* 20 ms tail; [0, length] for silence */
function autoTrim(raw, rel = 0.02) {
let pk = 0;
for (const v of raw) pk = Math.max(pk, Math.abs(v));
if (!pk) return [0, raw.length];
const th = pk * rel;
let a = 0, b = raw.length - 1;
while (a < raw.length && Math.abs(raw[a]) < th) a++;
while (b > a && Math.abs(raw[b]) < th) b--;
return [Math.max(0, a - Math.round(SMP.RATE * 0.005)), Math.min(raw.length, b + 1 + Math.round(SMP.RATE * 0.02))];
}
/* root from a file name like "piano_C4" or "F#3" (C4 = 60), else 60 (sampleio.note_from_name) */
function rootFromName(name) {
const m = /(?<![A-Za-z])([A-G])([#b]?)(-?\d)(?!\d)/.exec(name);
if (!m) return 60;
const n = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 }[m[1]] + (m[2] === "#" ? 1 : m[2] === "b" ? -1 : 0) + (parseInt(m[3], 10) + 1) * 12;
return Math.max(0, Math.min(127, n));
}
/* zones: [{s: Int16Array (22050 Hz), root, lo?, hi?}] -> {hdr (480 B), data, zones} (sampleio.user_slot) */
function buildSlot(name, zonesIn) {
const zones = [], parts = [];
let len = 0;
for (const z of zonesIn) {
const e = imaEncode(z.s, 0);
zones.push({ off: len, n: z.s.length, ls: 0, le: z.s.length - 1, root: z.root, lo: z.lo ?? null, hi: z.hi ?? null, pred: e.pred, idx: e.idx });
parts.push(e.data);
len += e.data.length;
}
const data = new Uint8Array(len);
let o = 0;
for (const p of parts) { data.set(p, o); o += p.length; }
if (len > SMP.MAX_DATA) throw new Error(`too long: ${len} B (max ${SMP.MAX_DATA} B)`);
if (!zones.length || zones.length > SMP.MAX_ZONES) throw new Error("1..16 files per slot");
zones.sort((a, b) => a.root - b.root);
zones.forEach((z, j) => {
if (z.lo == null) {
z.lo = j === 0 ? 0 : Math.floor((zones[j - 1].root + z.root) / 2) + 1;
z.hi = j === zones.length - 1 ? 127 : Math.floor((z.root + zones[j + 1].root) / 2);
}
});
const hdr = new Uint8Array(SMP.HDR_LEN), v = new DataView(hdr.buffer);
v.setUint32(0, 0x504D5346, true);
v.setUint16(4, 1, true);
hdr[6] = zones.length;
const nm = String(name).toUpperCase().replace(/[^\x20-\x7E]/g, "").slice(0, 8);
for (let i = 0; i < nm.length; i++) hdr[8 + i] = nm.charCodeAt(i);
v.setUint32(16, len, true);
v.setUint32(20, crc32(data), true);
const rate = pyRound(SMP.RATE / 44100 * 65536);
zones.forEach((z, j) => {
const b = 32 + j * 28;
[z.off, z.n, z.ls, z.le, rate].forEach((x, k) => v.setUint32(b + k * 4, x >>> 0, true));
v.setInt16(b + 20, z.root * 16, true);
v.setInt16(b + 22, z.pred, true);
hdr[b + 24] = z.idx; hdr[b + 25] = z.lo; hdr[b + 26] = z.hi; hdr[b + 27] = 0;
});
return { hdr, data, zones };
}
/* -------------------------------------------------------------- librarian --- */
/* A patch (library entry, user preset):
{name, engine (index), engineName, p: [P_COUNT values by parameter id, null = unknown],
pattern: 16 x [note 0..127 (0 rest), flags 1 accent | 2 slide | 4 tie] or null,
grid: 16 x [lane hits 0..255, their accents] or null (a DRUM sound's 16 steps; then no pattern),
tags: [], created, modified}
Library / bank / single-patch file (JSON):
{
"format": "felucca-library", "version": 1,
"kind": "library" | "bank" | "patch",
"firmware": "FELUCCA 0.5 ...", device version string when exported ("" if unknown)
"pCount": 57, "pE0": 49, P_COUNT and the first engine parameter id
"paramLabels": ["LEVEL", "ATTACK", ...], one key per parameter id: the DESC label, "#2", "#3" appended to
a repeated label (PITCH, PITCH#2), and "E0".."E7" for the engine
parameters (their labels depend on the engine)
"engines": ["ANALOG", ...], engine names by index
"exported": "2026-10-03T12:00:00.000Z",
"patches": [{ "name", "engine", "engineName", "params": [pCount numbers or null],
"pattern": [[note, flags] x 16] or null, "grid": [[hits, accents] x 16] (when there is one),
"tags": [...], "created", "modified",
"slot": n (bank files only, 0-based) }]
}
Reading maps every parameter by its key, so a firmware with other ids (or more parameters) still gets
the right values; parameters the file does not have are null (left at the engine default). Engines are
matched by name. The old single-sound file ("felucca-patch" version 1, "Save to file") is read too. */
const LIB = { FORMAT: "felucca-library", VERSION: 1 };
/* parameter keys by id from the instrument DESCs */
function paramKeys(pdesc, pe0, pcount) {
const seen = {}, out = [];
for (let i = 0; i < pcount; i++) {
if (i >= pe0) { out.push("E" + (i - pe0)); continue; }
const l = (pdesc[i] && pdesc[i].label) || "P" + i;
seen[l] = (seen[l] || 0) + 1;
out.push(seen[l] > 1 ? `${l}#${seen[l]}` : l);
}
return out;
}
const sameKeys = (a, b) => !!a && !!b && a.length === b.length && a.every((k, i) => k === b[i]);
/* (Skiff U4, the words) the track parameters' labels before U4 (LVL ATK .., by id): a library file keyed by them still
finds its values, its keys taken to today's by id (a file of today has LEVEL: as it is) */
const LEGACY_TP = ["LVL", "ATK", "DEC", "SUS", "REL", "FLT", "PIT", "SHP", "FX", "RATE", "WAVE", "PHS", "FADE", "PIT", "FLT",
"SHP", "AMP", "MODE", "RATE", "OCT", "GATE", "SWG", "PROB", "HOLD", "ORD", "ROOT", "SCL", "QNT", "TRN", "LEN", "DIV", "SWG",
"GATE", "DST", "CHO", "DLY", "REV", "VCE", "GLD", "PAN", "MUTE", "GLMOD", "PRIO", "ALLOC", "DTUNE", "SLCR", "PAT", "RATE",
"DEPTH", "SRC1", "DST1", "AMT1", "SRC2", "DST2", "AMT2", "SRC3", "DST3", "AMT3", "SRC4", "DST4", "AMT4",
"ATK", "DEC", "SUS", "REL", "LVL", "ATK", "DEC", "SUS", "REL", "LVL", "ATK", "DEC", "SUS", "REL", "LVL", "ATK", "DEC", "SUS",
"REL", "LVL", "CHRD", "VOIC", "KICK", "SNARE", "CLAP", "HATCL", "HATOP", "TOM", "RIM", "BELL", "DIR", "BY", "DEPTH", "REL"];
function legacyKeys(fileKeys, keys) {
if (!fileKeys || !keys || !fileKeys.includes("LVL") || fileKeys.includes("LEVEL")) return fileKeys;
const old = paramKeys(LEGACY_TP.map((label) => ({ label })), LEGACY_TP.length, LEGACY_TP.length);
const to = new Map(old.map((k, i) => [k, keys[i]]));
return fileKeys.map((k) => (to.has(k) && to.get(k) ? to.get(k) : k));
}
/* values by fromKeys -> values by toKeys (null where the source has no such key) */
function remapParams(p, fromKeys, toKeys, pe0) {
if (!fromKeys && toKeys && pe0 && p.length !== toKeys.length) return tailParams(p, toKeys.length, pe0);
if (!fromKeys || !toKeys || sameKeys(fromKeys, toKeys)) return p.slice();
const at = new Map(fromKeys.map((k, i) => [k, i]));
return toKeys.map((k) => (at.has(k) ? p[at.get(k)] ?? null : null));
}
/* values without keys from another firmware: ids below its P_E0 kept their places, its last 8 are E0..E7
(common ids are only ever appended before P_E0); the rest stay null */
function tailParams(p, n, pe0) {
const out = Array(n).fill(null), common = Math.max(0, p.length - 8);
for (let i = 0; i < Math.min(common, pe0); i++) out[i] = p[i] ?? null;
for (let k = 0; k < 8 && common + k < p.length; k++) out[pe0 + k] = p[common + k] ?? null;
return out;
}
/* one pattern step as the firmware keeps it (up_pat_norm): a tie has no note, a rest no flags; flags 1 accent, 2 slide,
4 tie, 8 | 16 the ratchet - 1 (core.h SF_RATCH) */
const patNorm = (n, f) => (f & 4 ? [0, 4] : [n & 0x7F, n ? f & 27 : 0]);
/* sequencer steps (STEP_GET objects) -> 16-step pattern, as the firmware's UP_STORE does (up_pat_from):
the first note of a NOTE step, flag 4 for a TIE step */
function patternFromSteps(steps) {
return Array.from({ length: UP.PAT }, (_, i) => {
const s = steps[i];
if (!s) return [0, 0];
return patNorm(s.time === 0 && s.n ? s.notes[0] : 0, s.time === 1 ? 4 : (s.flags & 3) | ((s.ratchet || 1) - 1) << 3);
});
}
/* pattern -> 16 STEP_SET objects, as the firmware loads one (load_pat16; velocity 96); the ratchet is sent only with a
chance (req.stepSet) */
function stepsFromPattern(pat) {
return Array.from({ length: UP.PAT }, (_, i) => {
const [n, f] = (pat && pat[i]) || [0, 0];
return { n: n ? 1 : 0, notes: [n & 0x7F, 0, 0, 0], time: f & 4 ? 1 : n ? 0 : 2, flags: n ? f & 3 : 0, vel: n ? 96 : 0,
ratchet: n ? (f >> 3 & 3) + 1 : 1 };
});
}
const patternUsed = (pat) => !!pat && pat.some((x) => x && x[0]);
/* a DRUM track's first 16 steps -> a grid, as the firmware's UP_STORE stores one (its notes on their lanes) */
const gridFromSteps = (steps) => Array.from({ length: UP.PAT }, (_, i) => (steps[i] ? [stepLanes(steps[i]), stepAccents(steps[i])] : [0, 0]));
function cleanPatch(pt) {
const now = new Date().toISOString();
const pat = Array.isArray(pt.pattern) && pt.pattern.length
? Array.from({ length: UP.PAT }, (_, i) => { const x = pt.pattern[i]; return Array.isArray(x) ? patNorm(x[0] | 0, x[1] | 0) : [0, 0]; })
: null;
const grid = Array.isArray(pt.grid) && pt.grid.length
? Array.from({ length: UP.PAT }, (_, i) => { const x = pt.grid[i]; const h = Array.isArray(x) ? x[0] & 255 : 0; return [h, Array.isArray(x) ? x[1] & h : 0]; })
: null;
const o = {
name: String(pt.name ?? "PATCH").slice(0, 32) || "PATCH",
engine: pt.engine | 0, engineName: String(pt.engineName ?? ""),
p: Array.from(pt.p || pt.params || [], (v) => (Number.isFinite(v) ? Math.round(v) : null)),
pattern: patternUsed(grid) ? null : patternUsed(pat) ? pat : null,
grid: patternUsed(grid) ? grid : null,
tags: Array.isArray(pt.tags) ? [...new Set(pt.tags.map((x) => String(x).trim()).filter(Boolean))] : [],
created: pt.created || now, modified: pt.modified || pt.created || now,
};
if (Number.isInteger(pt.slot)) o.slot = pt.slot;
if (Array.isArray(pt.fm6) && pt.fm6.length === FM6.PACKED) o.fm6 = pt.fm6.map((x) => (x | 0) & 127); /* (a converted */
if (Array.isArray(pt.fm4)) o.fm4 = pt.fm4.map((v) => (Number.isFinite(v) ? Math.round(v) : null)); /* DIGITAL sound) */
return o;
}
/* ctx: {keys, engines, firmware, pe0} of the library (the device's when connected) */
function libraryFile(kind, patches, ctx) {
return {
format: LIB.FORMAT, version: LIB.VERSION, kind, firmware: ctx.firmware || "",
pCount: ctx.keys ? ctx.keys.length : 0, pE0: ctx.pe0 ?? null, paramLabels: ctx.keys || [], engines: ctx.engines || [],
exported: new Date().toISOString(),
patches: patches.map((x) => {
const c = cleanPatch(x);
const o = { name: c.name, engine: c.engine, engineName: c.engineName || (ctx.engines || [])[c.engine] || "",
params: c.p, pattern: c.pattern, tags: c.tags, created: c.created, modified: c.modified };
if (c.grid) o.grid = c.grid;
if (c.fm6) { o.fm6 = c.fm6; if (c.fm4) o.fm4 = c.fm4; } /* an FM6 sound's own patch (a DIGITAL sound converted: and
the DIGITAL values) */
if (Number.isInteger(x.slot)) o.slot = x.slot;
return o;
}),
};
}
/* -> {patches, skipped, keys (the file's, for a library that has none yet)}; throws on a file it cannot read.
A DIGITAL patch (the engine retired in 1.0) where ctx has no DIGITAL imports as FM6 (fromDigital); a SAMPLE PERC
one (the set retired after 1.0.2) as DRUM's kit (fromPerc) */
function readLibraryFile(obj, ctx) {
if (!obj || typeof obj !== "object") throw new Error("not JSON");
const noFm4 = !(ctx.engines || []).includes("DIGITAL");
const perc = (pt, pe0) => (pt && fromPerc(pt, ctx.engines, pe0)) || pt;
const fm4 = (pt, nm, pe0) => (nm === "DIGITAL" && noFm4 ? fromDigital(pt, ctx.engines, pe0) : perc(pt, pe0));
const engIndex = (name, idx, fileEngines) => {
const nm = name || (fileEngines || [])[idx];
if (ctx.engines && ctx.engines.length) {
if (nm) return ctx.engines.indexOf(nm);
return idx < ctx.engines.length ? idx : -1;
}
return idx;
};
if (obj.format === "felucca-patch") { /* "Save to file": the whole current sound */
if (!Array.isArray(obj.p) || !Number.isInteger(obj.engine)) throw new Error("felucca-patch without engine / p");
const digital = obj.engineName === "DIGITAL" && noFm4;
const e = digital ? 1 : engIndex(obj.engineName, obj.engine);
if (e < 0) return { patches: [], skipped: 1, keys: null };
const p = ctx.keys && ctx.pe0 && obj.p.length !== ctx.keys.length ? tailParams(obj.p, ctx.keys.length, ctx.pe0)
: obj.p.slice(0, ctx.keys ? ctx.keys.length : obj.p.length);
const pt = fm4({ name: obj.presetName || obj.engineName || "PATCH", engine: e, engineName: obj.engineName, p,
pattern: Array.isArray(obj.steps) ? patternFromSteps(obj.steps) : null, tags: ["file"] }, obj.engineName,
ctx.keys && ctx.pe0 ? ctx.pe0 : p.length - 8);
return pt ? { patches: [cleanPatch(pt)], skipped: 0, keys: null } : { patches: [], skipped: 1, keys: null };
}
if (obj.format !== LIB.FORMAT) throw new Error("unknown format");
if (!(obj.version >= 1)) throw new Error("version");
if (!Array.isArray(obj.patches)) throw new Error("no patches");
const fileKeys = legacyKeys(Array.isArray(obj.paramLabels) && obj.paramLabels.length ? obj.paramLabels.map(String) : null,
ctx.keys); /* ((Skiff U4) a file of before U4's words: its keys by id) */
const out = [];
let skipped = 0;
for (const x of obj.patches) {
if (!x || !Array.isArray(x.params)) { skipped++; continue; }
const nm = x.engineName || (obj.engines || [])[x.engine | 0];
const digital = nm === "DIGITAL" && noFm4;
const e = digital ? 1 : engIndex(x.engineName, x.engine | 0, obj.engines);
if (e < 0) { skipped++; continue; }
const p = remapParams(x.params, fileKeys, ctx.keys, ctx.pe0);
const pe0 = ctx.keys && ctx.pe0 ? ctx.pe0 : obj.pE0 ?? p.length - 8;
const pt = digital ? fromDigital({ ...x, engine: e, p }, ctx.engines, pe0)
: perc(cleanPatch({ ...x, engine: e, engineName: (ctx.engines || [])[e] || x.engineName || (obj.engines || [])[x.engine], p }), pe0);
if (!pt) { skipped++; continue; }
out.push(cleanPatch(pt));
}
return { patches: out, skipped, keys: fileKeys };
}
/* device side; rq(r, opt) -> reply args (Link.request), info from INFO */
const FLASH_OPT = { timeout: 2500, retries: 0 };
const presetPatches = (info) => !!(info && info.fm6 && info.fm6.caps & 2); /* user presets carry FM6 patches (1.0.3) */
const bank = {
async list(rq) {
const first = parse[CMD.UP_LIST](await rq(req.upList(0, UP.LIST_MAX)));
const slots = first.slots.slice();
while (slots.length < first.total) {
const r = parse[CMD.UP_LIST](await rq(req.upList(slots.length, Math.min(UP.LIST_MAX, first.total - slots.length))));
if (!r.count) break;
slots.push(...r.slots);
}
return { total: first.total, slots };
},
/* an FM6 sound's own patch comes with it (fm6: packed) where the firmware keeps one (INFO fm6.caps bit 1) */
async get(rq, info, slot) {
const u = parse[CMD.UP_GET](await rq(req.upGet(slot)), info);
if (u.used && presetPatches(info) && info.engines[u.engine] === "FM6") {
const g = parse[CMD.FM6_GET](await rq(req.fm6Get(FM6.TARGET.USER, slot)));
if (!g.rc) u.fm6 = g.packed;
}
return u;
},
/* -> rc (0 ok); with info, an FM6 sound's patch (pt.fm6) goes with it */
async put(rq, slot, pt, info) {
const rc = parse[CMD.UP_PUT](await rq(req.upPut(slot, pt), FLASH_OPT)).rc;
if (rc || !pt.fm6 || !presetPatches(info) || info.engines[pt.engine] !== "FM6") return rc;
return parse[CMD.FM6_PUT](await rq(req.fm6Put(FM6.TARGET.USER, slot, pt.fm6), FLASH_OPT)).rc;
},
async store(rq, slot, name) { return parse[CMD.UP_STORE](await rq(req.upStore(slot, name), FLASH_OPT)).rc; },
async load(rq, slot) { return parse[CMD.UP_LOAD](await rq(req.upLoad(slot), { timeout: 1000 })).rc; },
async erase(rq, slot) { return parse[CMD.UP_ERASE](await rq(req.upErase(slot), FLASH_OPT)).rc; },
};
/* the current sound: DUMP + the first 16 steps */
async function capturePatch(rq, info, name) {
const dump = parse[CMD.DUMP](await rq(req.dump()), info);
const steps = [];
for (let i = 0; i < UP.PAT && i < info.nstep; i++) steps.push(parse[CMD.STEP_GET](await rq(req.stepGet(i))));
const drum = ["DRUM", "DRUM-X"].includes(info.engines[dump.engine]); /* (a kit's track that strikes a lane: its grid) */
let fm6 = null; /* an FM6 track: its own patch (the selected track's) */
if (info.fm6 && info.engines[dump.engine] === "FM6") {
const sel = info.ntrk ? parse[CMD.TRACK](await rq(req.track())).sel : 0;
const g = parse[CMD.FM6_GET](await rq(req.fm6Get(FM6.TARGET.TRACK, sel)));
if (!g.rc) fm6 = g.packed;
}
return { patch: cleanPatch({ name, engine: dump.engine, engineName: info.engines[dump.engine], p: dump.p, pattern: patternFromSteps(steps),
grid: drum ? gridFromSteps(steps) : null, fm6 }), dump, steps };
}
/* the track's own parameters, which no sound load changes (ui.c param_kept): LEVEL, the ARP and ARP 2 pages,
SCL, LEN DIV SWING GATE (17..32), PAN, MUTE, the SLICER (45..48); with P_E0 83 the chord keys CHRD VOIC (81, 82:
E0 E1 of the 89-parameter firmware) */
const TRACK_OWN = new Set([0, 39, 40, ...Array.from({ length: 16 }, (_, i) => 17 + i), 45, 46, 47, 48]);
const P_CHORD = [81, 82]; /* core.h P_CHRD, P_VOIC (since P_COUNT 91, P_E0 83) */
const P_LANES = [83, 84, 85, 86, 87, 88, 89, 90]; /* core.h P_LN0..P_LN7: the DRUM lane levels (since P_COUNT 99, P_E0 91) */
const P_DIR = 91; /* (Skiff) core.h P_DIR: the play direction, the track's (P_COUNT 100, P_E0 92) */
const P_DUCK = [92, 93, 94]; /* (Skiff) core.h P_DKSRC P_DKAMT P_DKREL: the ducking, the track's (P_COUNT 103, P_E0 95) */
/* (Skiff phase 9, P_COUNT 125, P_E0 117) core.h P_DTYPE P_DTONE (FX > DRIVE), P_EG2_ATK .. REL (ENV 2), P_LTUNE0..7 and
P_LDECAY0..7 (the DRUM lanes' TUNE and DECAY): sound parameters, as the engine's */
const P_DRIVE = [95, 96], P_ENV2 = [97, 98, 99, 100];
const P_LTUNE = Array.from({ length: 8 }, (_, i) => 101 + i), P_LDECAY = Array.from({ length: 8 }, (_, i) => 109 + i);
/* (Skiff 1.3, P_COUNT 135, P_E0 127: wide ids) core.h P_LSYNC P_LTRIG P_LPOL (LFO 2), P_SPRD (SPREAD), P_ITYPE P_IA P_IB P_IC
P_IMIX (FX > INSERT), P_ESYNC (ENV SYNC): sound parameters, as the engine's */
const P_LFO2 = [117, 118, 119], P_SPRD = 120, P_INSERT = [121, 122, 123, 124], P_IMIX = 125, P_ESYNC = 126;
const trackOwn = (i, pe0) => TRACK_OWN.has(i) || (pe0 >= 83 && P_CHORD.includes(i)) || (pe0 >= 92 && i === P_DIR) ||
(pe0 >= 95 && P_DUCK.includes(i));
/* play a patch without writing flash, as UP_LOAD would load it: the sound only. SET the engine (G_ENGSEL:
engine defaults and its first preset), then every instrument parameter that differs, except the track's
own (TRACK_OWN). The steps are never touched. The device keeps a copy of the sound from before (SAVE held
there = undo) and treats the SETs right after G_ENGSEL as part of this load (EDITOR_PROTOCOL.md "undo").
opt: {gEng: G_ENGSEL id, progress(i, n)} */
/* (Skiff phase 6, W4) whether track `tr` may not play engine `e` (INFO 54 01: the light tracks, the engines they may not) */
function lightRefuses(info, tr, e) {
const l = info && info.light;
return !!l && ((l.tracks >> (tr | 0)) & 1) === 1 && ((l.engines >> (e | 0)) & 1) === 1;
}
async function auditionPatch(rq, info, pt, opt = {}) {
if (lightRefuses(info, opt.track ?? 0, pt.engine)) /* ((Skiff W4) refused before anything is written) */
throw new Error(`${info.engines[pt.engine] || pt.engine}: not on T${(opt.track ?? 0) + 1} (a light track)`);
await rq(req.set(1, opt.gEng ?? 20, pt.engine));
const dump = parse[CMD.DUMP](await rq(req.dump()), info);
const n = Math.min(info.pcount, pt.p.length);
for (let i = 0; i < n; i++) {
const v = pt.p[i];
if (opt.progress) opt.progress(i, n);
if (v == null || v === dump.p[i] || trackOwn(i, info.pe0)) continue;
await rq(req.set(0, i, v));
}
if (pt.fm6 && info.fm6) /* a converted DIGITAL sound: its own FM6 patch on the track */
await rq(req.fm6Put(FM6.TARGET.TRACK, opt.track ?? 0, pt.fm6));
return {};
}
/* WATCH on (asking for TRACK_CHANGED too): false when the firmware does not know it (older than protocol v2),
else 1, or 3 when it also has TRACK_PARAM / TRACK_CHANGED (protocol v4) */
async function startWatch(rq) {
try { const on = parse[CMD.WATCH](await rq(req.watch(3), { timeout: 300, retries: 1, quiet: true })).on; return on & 1 ? on & 3 : false; }
catch (e) { if (e.message === "closed") throw e; return false; }
}
/* ------------------------------------------------------------ mixer (v3) --- */
/* The TRACKS page in the editor: TRACK (engine, preset, level, mute, armed of every track) and TRACK_DUMP
of each track for its P_PAN. Level and mute go through TRACK_MIX (any track). Pan: TRACK_PARAM (v4, any track); with v3 firmware a plain SET, which reaches only the
selected track: another track is selected for it and the selection is put back (TRACK pushes no
RELOAD). ids: {pan: P_PAN id} */
const mixer = {
async read(rq, info, ids, prev = null) { /* prev: the tracks as last read: their pans kept, no TRACK_DUMP ((Skiff W7)) */
const tr = parse[CMD.TRACK](await rq(req.track()));
for (let i = 0; i < tr.ntrk; i++) {
if (prev && prev[i]) { tr.tracks[i].pan = prev[i].pan; tr.tracks[i].rev = prev[i].rev ?? null; continue; }
const d = parse[CMD.TRACK_DUMP](await rq(req.trackDump(i)), info);
tr.tracks[i].pan = ids.pan == null ? null : d.p[ids.pan];
tr.tracks[i].rev = ids.rev == null ? null : d.p[ids.rev]; /* ((Skiff W3) REV, the device's MIXER's too) */
}
return tr;
},
/* -> {track, level, mute} as the device has them now */
async setMix(rq, track, level, mute, opt) { return parse[CMD.TRACK_MIX](await rq(req.trackMix(track, level, mute), opt)); },
/* -> the pan value after clamping. v4: TRACK_PARAM, the selection stays */
async setPan(rq, track, sel, panId, v, v4, key = "pan:" + track) { /* ((Skiff W3) REV too: its id, its key) */
if (v4) return parse[CMD.TRACK_PARAM](await rq(req.trackParam(track, panId, v), { key })).value;
if (track === sel) return parse[CMD.SET](await rq(req.set(0, panId, v))).value;
await rq(req.track(track));
try { return parse[CMD.SET](await rq(req.set(0, panId, v))).value; }
finally { await rq(req.track(sel)).catch(() => {}); }
},
};
/* ------------------------------------------------------------ mock device --- */
/* Implements the protocol like firmware/src/editor.c, with tables copied from params.c
and the engine sources (test_web.mjs checks them against the firmware's, tests/descdump.c). Used with ?mock=1 (add &legacy=1 for a firmware without cmds 16..26).
opt: {legacy: no user bank / WATCH, v3: no TRACK_PARAM / TRACK_CHANGED (firmware 0.8),
auto: false = no simulated knobs (tests drive sim.*),
watchMs: how long WATCH lasts after the last request (3000), slots: user bank size (32)} */
/* ------------------------------------------------------------------- FM6 --- */
/* The FM6 engine's patches (eng_fm6.c, EDITOR_PROTOCOL.md "FM6 patches"): the generic 6-operator voice.
voice: 155 bytes, 6 x 21 operator bytes (the sixth operator first, as the format has them), then 19 voice bytes
and a 10-character name. packed: the 128-byte record of a 32-voice bank (every byte 7-bit). SysEx files: a
single voice (F0 43 0n 00 01 1B, 155 bytes, checksum, F7: 163 bytes) or 32 packed voices (F0 43 0n 09 20 00,
4096 bytes, checksum, F7: 4104 bytes); parseSysex also reads the variants real files have (see there). */
const FM6 = (() => {
/* per operator byte: name, highest value; then the voice bytes */
const OP = [["R1", 99], ["R2", 99], ["R3", 99], ["R4", 99], ["L1", 99], ["L2", 99], ["L3", 99], ["L4", 99],
["BP", 99], ["LD", 99], ["RD", 99], ["LC", 3], ["RC", 3], ["RS", 7], ["AMS", 3], ["KVS", 7], ["OL", 99],
["MODE", 1], ["FC", 31], ["FF", 99], ["DET", 14]];
const VOICE = [["PR1", 99], ["PR2", 99], ["PR3", 99], ["PR4", 99], ["PL1", 99], ["PL2", 99], ["PL3", 99], ["PL4", 99],
["ALG", 31], ["FB", 7], ["OKS", 1], ["LFS", 99], ["LFD", 99], ["LPMD", 99], ["LAMD", 99], ["LKS", 1], ["LFW", 5],
["LPMS", 7], ["TRNSP", 48]];
const OPI = Object.fromEntries(OP.map(([n], i) => [n, i])), VI = Object.fromEntries(VOICE.map(([n], i) => [n, 126 + i]));
const NAME = 145, SIZE = 155, PACKED = 128;
const max = (i) => (i < 126 ? OP[i % 21][1] : i < NAME ? VOICE[i - 126][1] : 126);
/* byte i of operator n (1..6) */
const at = (n, field) => (6 - n) * 21 + OPI[field];
function sanitize(v) {
const o = Uint8Array.from(v.slice(0, SIZE));
for (let i = 0; i < SIZE; i++) o[i] = i >= NAME ? (o[i] < 32 || o[i] > 126 ? 32 : o[i]) : Math.min(o[i], max(i));
return o;
}
function unpack(b) { /* eng_fm6.c fm6_unpack */
const v = new Uint8Array(SIZE);
for (let k = 0; k < 6; k++) {
const o = k * 17, d = k * 21;
for (let i = 0; i < 11; i++) v[d + i] = b[o + i] & 127;
v[d + 11] = b[o + 11] & 3; v[d + 12] = b[o + 11] >> 2 & 3; v[d + 13] = b[o + 12] & 7; v[d + 20] = b[o + 12] >> 3 & 15;
v[d + 14] = b[o + 13] & 3; v[d + 15] = b[o + 13] >> 2 & 7; v[d + 16] = b[o + 14] & 127; v[d + 17] = b[o + 15] & 1;
v[d + 18] = b[o + 15] >> 1 & 31; v[d + 19] = b[o + 16] & 127;
}
for (let i = 0; i < 9; i++) v[126 + i] = b[102 + i] & 127;
v[134] &= 31; v[135] = b[111] & 7; v[136] = b[111] >> 3 & 1;
for (let i = 0; i < 4; i++) v[137 + i] = b[112 + i] & 127;
v[141] = b[116] & 1; v[142] = b[116] >> 1 & 7; v[143] = b[116] >> 4 & 7; v[144] = b[117] & 127;
for (let i = 0; i < 10; i++) v[NAME + i] = b[118 + i] & 127;
return sanitize(v);
}
function pack(v) { /* eng_fm6.c fm6_pack */
const b = new Array(PACKED).fill(0);
for (let k = 0; k < 6; k++) {
const o = k * 17, d = k * 21;
for (let i = 0; i < 11; i++) b[o + i] = v[d + i] & 127;
b[o + 11] = (v[d + 11] & 3) | (v[d + 12] & 3) << 2; b[o + 12] = (v[d + 13] & 7) | (v[d + 20] & 15) << 3;
b[o + 13] = (v[d + 14] & 3) | (v[d + 15] & 7) << 2; b[o + 14] = v[d + 16] & 127;
b[o + 15] = (v[d + 17] & 1) | (v[d + 18] & 31) << 1; b[o + 16] = v[d + 19] & 127;
}
for (let i = 0; i < 9; i++) b[102 + i] = v[126 + i] & 127;
b[110] &= 31; b[111] = (v[135] & 7) | (v[136] & 1) << 3;
for (let i = 0; i < 4; i++) b[112 + i] = v[137 + i] & 127;
b[116] = (v[141] & 1) | (v[142] & 7) << 1 | (v[143] & 7) << 4; b[117] = v[144] & 127;
for (let i = 0; i < 10; i++) b[118 + i] = v[NAME + i] & 127;
return b;
}
const name = (v) => String.fromCharCode(...v.slice(NAME, NAME + 10)).replace(/\s+$/, "");
function setName(v, s) {
const t = String(s).toUpperCase().replace(/[^\x20-\x7E]/g, " ").slice(0, 10).padEnd(10, " ");
for (let i = 0; i < 10; i++) v[NAME + i] = t.charCodeAt(i);
return v;
}
const checksum = (a) => (128 - (a.reduce((s, x) => s + x, 0) & 127)) & 127;
/* every voice in a file's bytes, tolerant of what real files have:
- SysEx F0 43 0n 00 xx xx (one voice, 155 bytes) and F0 43 0n 09 xx xx (32 packed voices, 4096 bytes): the byte
count is not checked (some tools write 09 10 00, i.e. 0x1000 as two plain bytes); the payload is taken right
after the 6-byte header whatever follows it: a checksum or not, F7 or not, a stray byte, the next F0;
a message cut short (EOF, or a byte >= 0x80 inside it) keeps its whole voices (the name may be cut: blanks);
- several messages in one file, junk before / between / after them;
- the format's other blocks (manufacturer 43h: supplements, performances, 4-operator voices, universal "LM ..." blocks) and other
makers' messages are skipped and counted;
- raw data without SysEx: 4096 x n bytes (banks), 155 (one voice) or 128 bytes (one packed voice).
-> {voices: [{name, v}], badSum: messages with a wrong checksum (still read), short: messages cut short,
skipped: other messages, kinds: what the skipped ones were ("fm4" 4-operator voices, "other43" the format's other
blocks, "universal", "maker:XX" another manufacturer id), sysex: F0 seen} */
function parseSysex(bytes) {
const d = Uint8Array.from(bytes), voices = [], kinds = [];
let badSum = 0, short = 0, skipped = 0;
const add = (v) => voices.push({ v, name: name(v) });
const kind = (k) => { skipped++; if (!kinds.includes(k)) kinds.push(k); };
const sysex = d.includes(0xF0);
if (d[0] !== 0xF0 && !sysex) {
if (d.length && d.length % 4096 === 0) {
for (let o = 0; o < d.length; o += 128) add(unpack(d.subarray(o, o + 128)));
} else if (d.length === SIZE) add(sanitize(d));
else if (d.length === PACKED) add(unpack(d));
return { voices, badSum, short, skipped, kinds, sysex };
}
for (let i = 0; i < d.length; i++) {
if (d[i] !== 0xF0) continue;
const id = d[i + 1], st = d[i + 2], f = d[i + 3];
if (id === 0x43 && st !== undefined && (st & 0xF0) === 0 && (f === 0 || f === 9) && i + 6 <= d.length) {
const want = f === 0 ? SIZE : 4096, s = i + 6;
let e = s;
while (e < d.length && e < s + want && d[e] < 0x80) e++;
const data = d.subarray(s, e);
if (data.length < want) short++;
else if (e < d.length && d[e] < 0x80 && checksum(data) !== d[e]) badSum++;
if (f === 0) {
if (data.length >= NAME) { const v = new Uint8Array(SIZE); v.set(data); add(sanitize(v)); }
} else {
for (let o = 0; o + 118 <= data.length; o += 128) { /* whole voices, and one cut in its name (at 118) */
const pk = new Uint8Array(128); pk.set(data.subarray(o, o + 128)); add(unpack(pk));
}
}
i = e - 1; /* on to the next F0 (the checksum, F7, junk are passed over) */
continue;
}
if (id === 0x43) kind(f === 3 || f === 4 ? "fm4" : "other43");
else if (id === 0x7E || id === 0x7F) kind("universal");
else if (id !== undefined && id < 0x80) kind("maker:" + (id === 0 ? [0, d[i + 2], d[i + 3]] : [id])
.map((x) => (x ?? 0).toString(16).toUpperCase().padStart(2, "0")).join(" "));
}
return { voices, badSum, short, skipped, kinds, sysex };
}
function singleSysex(v, ch = 0) {
const data = Array.from(sanitize(v));
return Uint8Array.from([0xF0, 0x43, ch & 15, 0, 0x01, 0x1B, ...data, checksum(data), 0xF7]);
}
function bankSysex(voices, ch = 0) { /* up to 32 voices (155 bytes each), the rest the init voice */
const data = [];
for (let k = 0; k < 32; k++) data.push(...(voices[k] ? pack(voices[k]) : INIT_PK));
return Uint8Array.from([0xF0, 0x43, ch & 15, 9, 0x20, 0, ...data, checksum(data), 0xF7]);
}
/* the 32 algorithms (msfa's tables; fm6_core.c FM6_ALG): per operator, the sixth first */
const ALG = [[0xc1, 0x11, 0x11, 0x14, 0x01, 0x14], [0x01, 0x11, 0x11, 0x14, 0xc1, 0x14], [0xc1, 0x11, 0x14, 0x01, 0x11, 0x14],
[0xc1, 0x11, 0x94, 0x01, 0x11, 0x14], [0xc1, 0x14, 0x01, 0x14, 0x01, 0x14], [0xc1, 0x94, 0x01, 0x14, 0x01, 0x14],
[0xc1, 0x11, 0x05, 0x14, 0x01, 0x14], [0x01, 0x11, 0xc5, 0x14, 0x01, 0x14], [0x01, 0x11, 0x05, 0x14, 0xc1, 0x14],
[0x01, 0x05, 0x14, 0xc1, 0x11, 0x14], [0xc1, 0x05, 0x14, 0x01, 0x11, 0x14], [0x01, 0x05, 0x05, 0x14, 0xc1, 0x14],
[0xc1, 0x05, 0x05, 0x14, 0x01, 0x14], [0xc1, 0x05, 0x11, 0x14, 0x01, 0x14], [0x01, 0x05, 0x11, 0x14, 0xc1, 0x14],
[0xc1, 0x11, 0x02, 0x25, 0x05, 0x14], [0x01, 0x11, 0x02, 0x25, 0xc5, 0x14], [0x01, 0x11, 0x11, 0xc5, 0x05, 0x14],
[0xc1, 0x14, 0x14, 0x01, 0x11, 0x14], [0x01, 0x05, 0x14, 0xc1, 0x14, 0x14], [0x01, 0x14, 0x14, 0xc1, 0x14, 0x14],
[0xc1, 0x14, 0x14, 0x14, 0x01, 0x14], [0xc1, 0x14, 0x14, 0x01, 0x14, 0x04], [0xc1, 0x14, 0x14, 0x14, 0x04, 0x04],
[0xc1, 0x14, 0x14, 0x04, 0x04, 0x04], [0xc1, 0x05, 0x14, 0x01, 0x14, 0x04], [0x01, 0x05, 0x14, 0xc1, 0x14, 0x04],
[0x04, 0xc1, 0x11, 0x14, 0x01, 0x14], [0xc1, 0x14, 0x01, 0x14, 0x04, 0x04], [0x04, 0xc1, 0x11, 0x14, 0x04, 0x04],
[0xc1, 0x14, 0x04, 0x04, 0x04, 0x04], [0xc4, 0x04, 0x04, 0x04, 0x04, 0x04]];
/* operators 1..6 that are carriers (on the output bus), and the one with the feedback, of algorithm a (0..31) */
const carriers = (a) => [1, 2, 3, 4, 5, 6].filter((n) => !(ALG[a & 31][6 - n] & 3));
const feedbackOp = (a) => [1, 2, 3, 4, 5, 6].find((n) => (ALG[a & 31][6 - n] & 0xc0) === 0xc0);
/* an operator's frequency as text: x ratio, or Hz for a fixed one (msfa note osc_freq) */
function freqText(v, n) {
const fc = v[at(n, "FC")], ff = v[at(n, "FF")];
if (v[at(n, "MODE")]) return (10 ** ((fc & 3) + ff / 100)).toPrecision(4) + " Hz";
return "x" + ((fc ? fc : 0.5) * (1 + ff / 100)).toFixed(2);
}
const INIT_PK = [99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,99,99,99,99,99,99,0,39,0,0,0,56,0,99,2,0,99,99,99,99,50,50,50,50,0,8,35,0,0,0,49,24,73,78,73,84,32,86,79,73,67,69];
const FACTORY_PK = [
[95,40,30,60,99,80,0,0,39,0,0,0,56,12,52,2,0,95,30,20,60,99,90,0,0,39,0,0,0,48,4,78,2,0,97,62,40,60,99,60,0,0,39,0,0,0,59,24,68,28,0,95,20,20,50,99,95,0,0,39,0,0,0,66,8,90,2,0,95,50,35,78,99,75,0,0,39,0,0,0,59,28,58,2,0,96,25,25,67,99,75,0,0,39,0,0,0,59,8,98,2,0,99,99,99,99,50,50,50,50,4,11,34,33,0,0,41,24,84,73,78,69,32,69,80,32,32,32], /* TINE EP */
[99,60,40,45,99,50,0,0,39,0,0,0,56,0,60,2,0,99,60,40,45,99,50,0,0,39,0,0,0,40,0,78,10,40,99,50,30,40,99,60,0,0,39,0,0,0,56,12,70,10,0,99,45,30,40,99,70,0,0,39,0,0,0,72,4,84,4,38,99,35,25,35,99,70,0,0,39,0,0,0,56,12,78,6,50,99,40,25,35,99,80,0,0,39,0,0,0,56,4,96,2,0,99,99,99,99,50,50,50,50,4,8,35,0,0,0,1,24,71,76,65,83,83,32,66,69,76,76], /* BELL */
[99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,72,50,75,99,65,40,0,39,0,0,0,56,24,78,4,0,99,55,40,75,99,70,50,0,39,0,0,0,64,4,80,2,0,99,60,40,75,99,72,55,0,39,0,0,0,56,20,80,2,0,99,40,30,75,99,85,70,0,39,0,0,0,56,8,99,2,0,99,99,99,99,50,50,50,50,4,8,35,0,0,0,1,24,82,79,85,78,68,32,66,65,83,83], /* FM BASS */
[52,50,40,60,99,85,82,0,39,0,0,0,56,8,72,2,0,62,50,40,60,99,92,90,0,39,0,0,0,40,4,88,2,0,50,50,40,60,99,88,85,0,39,0,0,0,56,12,78,2,0,62,50,40,60,99,92,90,0,39,0,0,0,72,4,92,2,0,55,50,40,60,99,88,85,0,39,0,0,0,56,12,80,2,0,65,50,40,60,99,92,90,0,39,0,0,0,56,4,98,2,0,80,60,99,60,46,50,50,50,4,13,33,50,6,0,57,24,66,82,65,83,83,32,83,69,67,84], /* BRASS */
[35,30,40,40,85,90,85,0,39,0,0,0,56,0,50,2,0,38,30,40,40,99,95,90,0,39,0,0,0,56,0,80,4,0,30,25,40,40,80,90,85,0,39,0,0,0,56,4,55,4,0,40,30,40,40,99,95,90,0,39,0,0,0,80,0,92,2,0,35,30,40,40,85,90,80,0,39,0,0,0,56,4,60,2,0,40,30,40,40,99,95,90,0,39,0,0,0,40,0,92,2,0,99,99,99,99,50,50,50,50,4,10,30,60,4,0,41,24,83,79,70,84,32,80,65,68,32,32], /* PAD */
[99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,80,50,60,99,0,0,0,39,0,0,0,59,12,45,2,0,99,70,50,60,99,0,0,0,39,0,0,0,59,12,72,8,0,99,75,50,60,99,0,0,0,39,0,0,0,59,20,70,8,0,99,52,40,55,99,0,0,0,39,0,0,0,58,8,99,2,0,99,99,99,99,50,50,50,50,4,8,35,0,0,0,1,24,87,79,79,68,32,66,65,82,83,32], /* MARIMBA */
[99,99,99,85,99,99,99,0,39,0,0,0,56,0,72,2,50,99,99,99,85,99,99,99,0,39,0,0,0,56,0,78,8,0,99,99,99,85,99,99,99,0,39,0,0,0,56,0,76,6,0,99,99,99,85,99,99,99,0,39,0,0,0,56,0,86,4,0,99,99,99,85,99,99,99,0,39,0,0,0,56,0,84,0,0,99,99,99,85,99,99,99,0,39,0,0,0,56,0,90,2,0,99,99,99,99,50,50,50,50,31,8,60,0,3,0,57,24,68,82,65,87,66,65,82,83,32,32], /* ORGAN */
[99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,75,40,60,99,30,0,0,39,0,0,0,58,12,68,2,0,99,60,40,60,99,30,0,0,39,0,0,0,66,8,74,4,0,99,70,40,60,99,40,0,0,39,0,0,0,58,16,76,6,0,99,45,30,60,99,60,0,0,39,0,0,0,58,8,98,2,0,99,99,99,99,50,50,50,50,4,8,35,0,0,0,1,24,78,89,76,79,78,32,80,73,67,75], /* PLUCK */
];
const init = () => unpack(INIT_PK);
const factory = (k) => unpack(FACTORY_PK[k]);
return { OP, VOICE, OPI, VI, NAME, SIZE, PACKED, max, at, sanitize, unpack, pack, name, setName, checksum, parseSysex,
singleSysex, bankSysex, ALG, carriers, feedbackOp, freqText, INIT_PK, FACTORY_PK, init, factory,
TARGET: { TRACK: 0, BANK: 1, FACTORY: 2, USER: 3 } };
})();
/* ----------------------------------------------------------------- DIGITAL --- */
/* DIGITAL (engine 1, four-operator FM) was replaced by FM6 (1.0): the firmware keeps engine 1 reserved (its name
"-"; a FELUCCA_FM4=1 build has DIGITAL back) and turns every DIGITAL sound into an FM6 one with a patch of its own
(src/fm4_convert.c). This is the same conversion (test_web.mjs: == the firmware's, build/host/desc.json "FM4"), for
library files and device slots of DIGITAL sounds. convert(p, pe0): p the values as DIGITAL has them (null: its
defaults), P_E0 at pe0 (the OP ENV values at 61..80 when pe0 >= 81) -> {p: FM6's (the macros neutral, PTCH the
nearest factory patch, the OP ENV values their defaults), voice: the 155-byte patch, preset: FM6's that covers it} */
const FM4 = (() => {
const P = (name, e, env, fenv, mono, fx, pat) => ({ name, e, env, fenv, mono, fx, pat });
const PRESETS = [ /* src/fm4_convert.c DIGITAL_PRESETS (fx: the sends) */
P("E.PIANO", [4, 1, 1, 14, 70, 55, 0, 0], [0, 80, 40, 60], 0, 0, [0, 50, 25, 35], 6),
P("BELL", [4, 8, 1, 4, 90, 70, 0, 0], [0, 95, 0, 85], 0, 0, [0, 0, 30, 70], 7),
P("BASS", [0, 1, 1, 1, 48, 40, 8, 0], [0, 60, 70, 25], 0, 1, [0, 0, 10, 10], 2),
P("BRASS", [0, 1, 1, 1, 70, 40, 20, 0], [40, 70, 100, 40], 20, 0, [0, 20, 20, 40], 6),
P("ORGAN", [7, 2, 3, 4, 0, 0, 0, 0], [2, 60, 127, 20], 0, 0, [10, 40, 0, 30], 6),
P("PAD", [5, 2, 1, 3, 40, 90, 10, 0], [80, 90, 110, 95], 0, 0, [0, 60, 30, 70], 5),
P("MARIMBA", [4, 4, 1, 1, 60, 30, 0, 0], [0, 80, 0, 60], 0, 0, [0, 0, 25, 40], 3),
P("FUNK KEY", [3, 1, 3, 5, 90, 25, 20, 0], [0, 45, 30, 30], 0, 0, [0, 20, 30, 20], 6)];
const TO_FM6 = [0, 1, 2, 3, 6, 4, 5, 7]; /* DIGITAL preset k -> the FM6 preset (its PTCH) covering it */
const ALG = [[0, [3, 4, 5, 6], [1, 1, 1, 1]], [13, [3, 4, 5, 6], [1, 1, 2, 2]], [7, [3, 5, 6, 4], [1, 2, 1, 2]],
[6, [3, 4, 5, 6], [1, 2, 2, 1]], [4, [1, 2, 5, 6], [2, 1, 2, 1]], [21, [3, 4, 5, 6], [3, 3, 3, 1]],
[28, [1, 2, 5, 6], [3, 3, 3, 1]], [31, [1, 2, 3, 6], [4, 4, 4, 4]]];
const MUTE = -100000, FB_NOISE = 20, FB_LIFT = 768, ATK = 1, DEC = 2, SUS = 3, REL = 4, ED_FLT = 5, OPENV = 61;
const EDEF = [0, 1, 1, 1, 60, 60, 0, 0], TDEF = { 1: 10, 2: 70, 3: 90, 4: 60, 5: 0 };
const MS10 = Array.from({ length: 128 }, (_, v) => Math.round(10 * 10000 ** (v / 127))); /* TIME_MS_X10 */
const LUT = [0, 5, 9, 13, 17, 20, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 42, 43, 45, 46];
const scaleout = (l) => (l >= 20 ? 28 + l : LUT[l < 0 ? 0 : l]);
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
const div = (a, b) => Math.trunc(a / b);
function lg(x) { /* 256 log2(x) (fm4_lg) */
if (!x) return MUTE;
let n = 0;
while (n < 31 && Math.floor(x / 2 ** (n + 1))) n++;
const f = (n >= 8 ? Math.floor(x / 2 ** (n - 8)) : x * 2 ** (8 - n)) & 255;
return n * 256 + f + Math.floor(f * (256 - f) * 89 / 65536);
}
const ms = (q) => (q ? lg(q) - 3840 : MUTE);
const samples = (v) => Math.floor(MS10[v & 127] * 441 / 100);
function rate(per) {
const lt = lg(per < 1 ? 1 : per);
let best = 0, bd = Infinity;
for (let r = 0; r < 100; r++) {
const q = (r * 41) >> 6, d = Math.abs(lg(Math.floor((1 << (22 - (q >> 2))) / (4 + (q & 3)))) - lt);
if (d < bd) { bd = d; best = r; }
}
return best;
}
const fall = (t, drop) => (drop <= 0 ? (drop === MUTE ? rate(div(t * 100, 664)) : 99) : rate(div(t * 111, drop)));
function nearestLevel(m, f) {
if (m <= MUTE) return 0;
let best = 0, bd = Infinity;
for (let l = 0; l < 100; l++) { const d = Math.abs(f(l) - m); if (d < bd) { bd = d; best = l; } }
return best;
}
const level = (m) => nearestLevel(m, (l) => ((scaleout(l) >> 1) << 6) - 4032);
const outlevel = (m) => nearestLevel(m, (l) => (scaleout(l) << 5) - 4064);
function nearest(e) {
let best = 0, bd = Infinity;
PRESETS.forEach((pr, k) => {
let d = ((e[0] & 7) !== pr.e[0]) * 1000;
for (let i = 1; i < 7; i++) d += Math.abs(e[i] - pr.e[i]) * (i < 4 ? 8 : 1);
if (d < bd) { bd = d; best = k; }
});
return best;
}
function convert(pin, pe0 = pin.length - 8) {
const p = pin.slice(), v = new Array(156).fill(0), op = pe0 >= 81;
const g = (i, d) => (p[i] == null ? d : p[i]);
const ev = Array.from({ length: 8 }, (_, i) => g(pe0 + i, EDEF[i]));
const tv = (i) => g(i, TDEF[i]);
const alg = ev[0] & 7, near = nearest(ev);
const idx = clamp(ev[4], 0, 127), fenv = clamp(tv(ED_FLT), -64, 63), sus = clamp(tv(SUS), 0, 127);
const ipk = clamp(idx + fenv, 0, 127), isus = clamp(div(idx, 4) + div(fenv * sus, 127), 0, 127);
const tAtt = samples(tv(ATK)), tMod = samples(ev[5]), car = FM6.carriers(ALG[alg][0]);
let fb = MUTE;
for (let k = 0; k < 6; k++) { const o = k * 21; v[o] = v[o + 1] = v[o + 2] = v[o + 3] = 99; v[o + 8] = 39; v[o + 18] = 1; v[o + 20] = 7; }
v[134] = ALG[alg][0];
for (let k = 0; k < 4; k++) {
const e = op ? [0, 1, 2, 3, 4].map((i) => g(OPENV + k * 5 + i, i === 2 || i === 4 ? 127 : 0)) : [0, 0, 127, 0, 127];
const opn = ALG[alg][1][k], share = ALG[alg][2][k], o = (6 - opn) * 21;
const flat = !e[0] && !e[1] && e[2] === 127 && !e[3];
const lvl = clamp(e[4], 0, 127) * 258, osus = flat ? 32767 : clamp(e[2], 0, 127) * 258;
const tOdec = flat || e[2] === 127 ? 0 : e[1] ? samples(e[1]) : 1;
const tOrel = flat ? 0x7FFFFFFF : e[3] ? samples(e[3]) : 0;
const r = k ? (ev[k] >>> 0) % 15 : 1;
let ta, td, tr, msS;
v[o + 18] = k ? (r === 0 ? 0 : r <= 12 ? r : r === 13 ? 14 : 16) : 1;
if (car.includes(opn)) { /* a carrier: the master envelope x the op's */
v[o + 16] = outlevel(ms(Math.floor(lvl / share)) + 256 - 96);
v[o + 15] = 3;
ta = tAtt;
if (!flat && e[0] && samples(e[0]) > ta) ta = samples(e[0]);
const s = Math.floor(sus * 258 * osus / 32768);
td = Math.max(sus < 127 ? samples(tv(DEC)) : 0, tOdec);
tr = samples(tv(REL));
if (!flat) tr = tOrel ? Math.floor((tr >> 5) * (tOrel >> 5) / ((tr >> 5) + (tOrel >> 5) + 1)) << 5 : 0;
msS = ms(s);
v[o] = rate(div(ta * 100, 146)); v[o + 4] = 99; v[o + 5] = v[o + 6] = level(msS);
v[o + 1] = fall(td, msS === MUTE ? MUTE : -msS); v[o + 2] = 99; v[o + 3] = rate(div(tr * 100, 664)); v[o + 7] = 0;
if (k === 3 && ev[6] && v[o + 16]) {
const need = ms(Math.floor(ev[6] * 258 * lvl / 32768)) + 256;
let out = (scaleout(v[o + 16]) << 5) - 4064 + (msS === MUTE ? -2048 : msS);
if (ev[6] >= FB_NOISE && msS !== MUTE && out < need) {
out += Math.min(need - out, FB_LIFT);
v[o + 16] = outlevel(out - msS);
out = (scaleout(v[o + 16]) << 5) - 4064 + msS;
}
fb = need - 256 - out;
}
} else { /* a modulator: INDEX through MODDEC x the op's envelope */
const a = Math.floor(Math.floor(ipk * lvl / 127) / share);
const m = ipk ? Math.floor(Math.floor(isus * 32767 / ipk) * osus / 32768) : 0;
let msA = ms(a);
msS = ms(m);
if (k === 3 && ev[6] && a) {
const need = ms(Math.floor(ev[6] * 258 * lvl / 32768)) + 256;
if (ev[6] >= FB_NOISE && msS !== MUTE && msA + msS < need) {
const t = msA + msS + Math.min(need - (msA + msS), FB_LIFT);
if (t <= msA) msS = t - msA;
else { msS = 0; msA = t > 0 ? 0 : t; }
}
fb = need - 256 - (msA + (msS === MUTE ? -2048 : msS));
}
v[o + 16] = outlevel(msA); v[o + 15] = a ? 1 : 0;
ta = fenv > 0 ? div(tAtt * fenv, idx + fenv) : 0;
if (!flat && e[0] && samples(e[0]) > ta) ta = samples(e[0]);
td = Math.max(msS < 0 ? (isus < ipk ? tMod : 0) : 0, tOdec);
v[o] = rate(div(ta * 100, 146)); v[o + 4] = 99; v[o + 5] = v[o + 6] = level(msS);
v[o + 1] = fall(td, msS === MUTE ? MUTE : -msS); v[o + 2] = 99;
if (flat) { v[o + 3] = v[o + 1]; v[o + 7] = v[o + 6]; }
else { v[o + 3] = tOrel ? rate(div(tOrel * 100, 664)) : 99; v[o + 7] = 0; }
}
}
fb += 8 * 256 + 128; /* FM6 feedback: deviation = output x 2^(FB - 8) */
if (ev[6] && fb > 0) v[135] = Math.min(div(fb, 256), 7);
for (let k = 0; k < 4; k++) { v[126 + k] = 99; v[130 + k] = 50; }
v[136] = 1; v[137] = 35; v[144] = 24;
const same = PRESETS.find((pr) => pr.env.every((x, i) => x === tv(ATK + i)) && pr.e.slice(0, 7).every((x, i) => x === ev[i]));
FM6.setName(v, same ? same.name : `4OP ALG ${alg + 1}`);
for (let k = 0; k < 7; k++) p[pe0 + k] = 0;
p[pe0 + 7] = TO_FM6[near];
if (op) for (let i = 0; i < 20; i++) p[OPENV + i] = i % 5 === 2 || i % 5 === 4 ? 127 : 0;
return { p, voice: FM6.sanitize(v), preset: TO_FM6[near] };
}
/* preset k's values into p (src/fm4_convert.c fm4_preset_values: EDIT, ENV, ENV -> FLT, VOICE, sends, OP ENV) */
function presetValues(p, k, pe0 = p.length - 8) {
const pr = PRESETS[k % PRESETS.length];
pr.e.forEach((x, i) => { p[pe0 + i] = x; });
pr.env.forEach((x, i) => { p[ATK + i] = x; });
p[ED_FLT] = pr.fenv; p[37] = pr.mono ? 2 : 0;
pr.fx.forEach((x, i) => { p[33 + i] = x; });
if (pe0 >= 81) for (let i = 0; i < 20; i++) p[OPENV + i] = i % 5 === 2 || i % 5 === 4 ? 127 : 0;
return p;
}
return { PRESETS, TO_FM6, ALG, convert, presetValues };
})();
/* a DIGITAL sound for a device / library without DIGITAL (engines: its names; "-" at 1 = reserved) -> the FM6 patch
that replaces it: {..., engine: FM6's index, engineName "FM6", p, fm6: packed, fm4: the DIGITAL values}; null when
the engines have no FM6. A device's slot of engine 1 holds such a sound (its record kept: the device converts it) */
function fromDigital(pt, engines, pe0) {
const fm6 = engines && engines.length ? engines.indexOf("FM6") : 12;
if (fm6 < 0) return null;
const src = Array.from(pt.p || pt.params || []);
const r = FM4.convert(src, pe0 ?? src.length - 8);
return { ...pt, engine: fm6, engineName: "FM6", p: r.p, params: undefined, fm6: FM6.pack(r.voice), fm4: src };
}
const reservedFm4 = (engines, e) => e === 1 && (engines || [])[1] === "-"; /* a device's slot of a DIGITAL sound */
/* SAMPLE SET 4 was PERC, the GM drum kit (retired after 1.0.2; src/core.h drum_from_perc): a sound of it is the DRUM
engine with its default kit (eng_drum.c DRUM_PRESETS[0], the same GM key map); the rest of its values stay. engines:
the names ("SAMPLE", "DRUM"; none: the firmware's indices 4, 10), pe0: P_E0 in its p. -> the DRUM patch, or null when
pt is no such sound or there is no DRUM. The device converts its own (projects, user presets) the same way */
const PERC_SET = 4, DRUM_KIT_E = [0, 64, 70, 64, 64, 100, 0, 0];
function fromPerc(pt, engines, pe0) {
const names = engines && engines.length ? engines : null;
const name = pt.engineName || (names || [])[pt.engine];
const p = pt.p || pt.params, drum = names ? names.indexOf("DRUM") : 10;
if ((name ? name !== "SAMPLE" : pt.engine !== 4) || !Array.isArray(p) || drum < 0) return null;
const e0 = pe0 ?? p.length - 8;
if (p[e0] !== PERC_SET) return null;
const q = p.slice();
DRUM_KIT_E.forEach((v, i) => { q[e0 + i] = v; });
return { ...pt, engine: drum, engineName: "DRUM", p: q, params: undefined };
}
/* an engine's name to show: the reserved engine 1 holds DIGITAL sounds that play as FM6 */
const engineLabel = (engines, e) => (e === 1 && (engines || [])[1] === "-" ? "FM6" : (engines || [])[e] ?? String(e));
function makeMockDevice(opt = {}) {
const NONOFF = ["OFF", "ON"], NDIV = ["1/4", "1/8", "1/16", "1/32", "8T", "16T", "1/2", "1/1", "2BAR", "4BAR"], NGO = ["--", "GO"], NDASH = ["--"];
const D = (label, fmt, min, max, def, names = null, unit = "") => ({ label, fmt, min, max, def, names, unit });
const E = (label, names, def) => D(label, F.ENUM, 0, names.length - 1, def, names);
const MSRC = ["OFF", "LFO", "ENV", "VEL", "KEY", "RAND", "MODW", "AT", "EXPR", "ENV2", "S&H", "SLEW"]; /* ((Skiff phase 9) ENV2;
(1.3) S&H SLEW) */
const MDST = ["OFF", "PITCH", "CUT", "SHP", "AMP", "PAN", "DIST", "CHO", "DLY", "REV", "RATE", "VIB", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8",
"DEPTH", "VEL", "TIME"]; /* ((1.3) the LFO's depth; at a note: VEL, TIME) */
const TP = [
D("LEVEL", F.DB, 0, 127, 104),
D("ATTACK", F.TIME, 0, 127, 10), D("DECAY", F.TIME, 0, 127, 70), D("SUSTAIN", F.PCT, 0, 127, 90), D("RELEASE", F.TIME, 0, 127, 60),
D("CUTOFF", F.BIPCT, -64, 63, 0), D("PITCH", F.BIPCT, -64, 63, 0), D("SHAPE", F.BIPCT, -64, 63, 0), D("FX", F.BIPCT, -64, 63, 0),
D("RATE", F.LFOHZ, 0, 127, 60), E("WAVE", ["SIN", "TRI", "SAW", "SQR", "S&H"], 0), D("PHASE", F.INT, 0, 127, 0), D("FADE", F.TIME, 0, 127, 0),
D("PITCH", F.BIPCT, -64, 63, 0), D("CUTOFF", F.BIPCT, -64, 63, 0), D("SHAPE", F.BIPCT, -64, 63, 0), D("AMP", F.PCT, 0, 127, 0),
E("MODE", ["OFF", "UP", "DN", "UPDN", "RND", "ORD", "REPEAT", "DNUP", "UP+8", "CONV", "DIVG", "PINKY", "THUMB", "WALK", "CHORD"], 0), E("RATE", NDIV, 2), D("OCTAVE", F.INT, 1, 4, 1), D("GATE", F.PCT, 1, 127, 64),
D("SWING", F.PCT, 0, 100, 0), D("CHANCE", F.PCT, 0, 127, 127), E("HOLD", NONOFF, 0), E("ORDER", ["NOTE", "PLAYED"], 0),
D("ROOT", F.NOTE, 0, 11, 0), E("SCALE", ["CHR", "MAJ", "MIN", "DOR", "MIX", "PEN", "MPEN", "HARM", "PHRY", "LYD", "LOC", "MEL", "BLUES", "WHOLE", "DIMHW", "DIMWH"], 0), E("QUANTIZE", ["OFF", "SNAP", "WHITE", "SEQ", "SEQ+T"], 0), D("TRANSP", F.SEMI, -24, 24, 0),
D("LENGTH", F.STEPS, 1, 64, 16), E("DIV", NDIV, 2), D("SWING", F.PCT, 0, 100, 0), D("GATE", F.PCT, 1, 127, 64),
D("DIST", F.PCT, 0, 127, 0), D("CHORUS", F.PCT, 0, 127, 0), D("DELAY", F.PCT, 0, 127, 0), D("REVERB", F.PCT, 0, 127, 0),
E("VOICE", ["POLY", "MONO", "LEG", "UNI"], 0), D("GLIDE", F.TIME, 0, 127, 0), D("PAN", F.BIPCT, -64, 63, 0), E("MUTE", NONOFF, 0),
E("GL MODE", ["RATE", "TIME"], 0), E("PRIORITY", ["LAST", "LOW", "HIGH"], 0), E("ALLOC", ["ROT", "REUSE"], 0), D("DETUNE", F.INT, 0, 127, 40),
E("SLICER", ["OFF", "GATE", "STUT"], 0), D("PATTERN", F.INT, 1, 16, 1), E("RATE", ["1/8", "1/16", "1/32", "8T", "16T", "32T"], 1), D("DEPTH", F.PCT, 0, 127, 127),
...[1, 2, 3, 4].flatMap((k) => [E("SRC" + k, MSRC, 0), E("DEST" + k, MDST, 0), D("AMT" + k, F.BIPCT, -64, 63, 0)]), /* the matrix */
];
const GP = [
D("BPM", F.BPM, 40, 240, 120), D("SWING+", F.PCT, 0, 100, 0), E("CLOCK", ["INT", "USB", "TRS"], 0), D("TUNE", F.INT, -50, 50, 0),
E("TIME", [...NDIV, "1/8D", "1/16D", "1/4D"], 1), D("FEEDBACK", F.PCT, 0, 120, 60), /* ((1.3) the dotted ones) */ D("COLOR", F.PCT, 0, 127, 70), D("MIX", F.PCT, 0, 127, 90),
D("SIZE", F.PCT, 0, 127, 90), D("DAMP", F.PCT, 0, 127, 60), D("RATE", F.LFOHZ, 0, 127, 40), D("DEPTH", F.PCT, 0, 127, 60),
E("MIDI", ["USB", "TRS"], 0), E("SYNC", NDASH, 0), E("ROUTE", ["CH1-6", "SEL"], 0), D("CPU", F.INT, 0, 0, 0),
D("SLOT", F.INT, 1, 4, 1), E("NAME", NDASH, 0), E("LOAD", NGO, 0), E("SAVE", NGO, 0),
E("ENGINE", ["ANALOG", "-", "PHASE", "LOFI", "SAMPLE", "VOICE", "TRIO", "WHEEL",
"GRAIN", "PHYS", "DRUM", "NOISE", "FM6", "SLICE", "DRUM-X"], 0), E("SET", NGO, 0),
E("CLRSQ", NGO, 0), E("INIT", NGO, 0),
E("TYPE", ["ROOM", "SPRING", "HALL"], 0), /* G_RTYPE (id 24, was G_DRCH): the reverb's model ((Skiff phase 9) HALL) */
E("MODE", ["CHORUS", "FLANGER", "PHASER"], 0), D("FEEDBACK", F.PCT, 0, 127, 0), /* 25, 26: (Skiff phase 9) the CHORUS bus
(G_CMODE, G_CFDBK; G_DRLVL, G_DRREV before: inert since 1.0) */
];
const NONE = D("-", F.INT, 0, 0, 0);
const RATIO = [".5", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "14", "16"];
const P = (name, e, env = [10, 70, 90, 60], mono = 0, pat = 0, more = []) => ({ name, e, env, mono, pat, more });
const ENG = [
{ name: "ANALOG", titles: ["OSC", "FLT"], edit: [E("WAVE", ["SAW", "SQR", "TRI", "SIN", "PWM", "SYNC", "SUB"], 0), D("DETUNE", F.INT, 0, 127, 10, null, "ct"), D("MIX", F.PCT, 0, 127, 64),
D("NOISE", F.PCT, 0, 127, 0), D("CUTOFF", F.CUTOFF, 0, 127, 90), D("RES", F.PCT, 0, 127, 30), D("DRIVE", F.PCT, 0, 127, 0), D("KEYTRK", F.PCT, 0, 127, 64)],
presets: [P("SAW LEAD", [0, 12, 64, 0, 90, 30, 10, 64], [4, 70, 100, 50], 1, 4), P("SOFT PAD", [0, 20, 64, 4, 60, 10, 0, 32], [80, 90, 110, 95], 0, 5),
P("SQR BASS", [1, 0, 0, 0, 50, 70, 40, 64], [0, 60, 40, 30], 1, 2), P("PWM STR", [4, 8, 40, 0, 75, 20, 0, 48], [60, 80, 110, 85], 0, 5),
P("ACID", [0, 0, 0, 0, 50, 100, 25, 64], [0, 55, 20, 30], 1, 1), P("SINE KEY", [3, 6, 50, 0, 127, 0, 0, 0], [2, 80, 30, 70], 0, 6),
P("RAVE", [4, 30, 64, 0, 85, 20, 30, 64], [20, 80, 110, 60], 1, 13), P("SUB BASS", [3, 0, 0, 0, 40, 0, 20, 0], [0, 60, 100, 20], 1, 8),
P("SYNTH PLUCK", [0, 8, 50, 0, 30, 40, 0, 64], [0, 88, 0, 60], 0, 3), P("SYNTH BRASS", [0, 10, 64, 0, 45, 20, 10, 64], [35, 70, 90, 45], 0, 6),
P("WIND SWEEP", [0, 0, 0, 90, 30, 90, 0, 0], [60, 90, 60, 80], 0, 5), P("STRINGS", [4, 6, 64, 0, 92, 8, 0, 48], [48, 90, 118, 72], 0, 5, [[15, 20], [9, 72], [13, 1], [12, 80]]),
/* (Skiff) the themes' sounds (src/eng_*.c) */
P("BONE FLUTE", [2, 3, 30, 22, 84, 15, 0, 64], [56, 80, 110, 64], 1, 0, [[9, 84], [12, 90], [13, 1]]),
P("WAR HORN", [0, 5, 64, 4, 42, 12, 20, 64], [72, 80, 110, 80], 1, 0, [[9, 80], [12, 96], [13, 1]]),
P("DARK STRINGS", [1, 4, 64, 6, 40, 34, 22, 40], [100, 90, 120, 105], 0, 0, [[9, 30], [14, 8], [13, 1], [12, 110]]),
P("NIGHT BASS", [0, 7, 64, 0, 40, 35, 15, 64], [0, 64, 50, 30], 1),
P("NEON LEAD", [0, 14, 64, 0, 92, 25, 12, 64], [6, 70, 110, 55], 1, 0, [[9, 86], [12, 92], [13, 2], [38, 28]]),
P("SUNSET PAD", [4, 9, 55, 0, 74, 15, 0, 48], [78, 90, 115, 92], 0, 0, [[10, 1], [9, 52], [15, 48]]),
P("HERO BRASS", [0, 16, 64, 0, 50, 18, 8, 56], [50, 75, 95, 55]),
P("SYN TOM", [3, 0, 0, 6, 127, 0, 25, 0], [0, 76, 0, 60], 0, 0, [[6, 63]]),
P("QUANTA", [3, 0, 0, 0, 127, 0, 0, 0], [0, 64, 127, 50], 1, 0, [[10, 4], [9, 96], [13, 40]]),
/* (Skiff phase 9) more for every engine (src/eng_*.c) */
P("REESE", [0, 40, 64, 0, 52, 15, 30, 32], [0, 64, 127, 30], 1, 0, [[9, 30], [14, 8]]),
P("DRIVE BASS", [0, 14, 64, 0, 62, 20, 10, 64], [0, 64, 64, 25], 1, 0, [[95, 1], [96, -32]]),
/* (1.3, from Felucca) WAVE SYNC and SUB */
P("HARD SYNC", [5, 36, 96, 0, 88, 24, 12, 64], [2, 70, 96, 40], 1, 0, [[7, 44], [38, 20]]),
P("SUB SAW", [6, 0, 80, 0, 70, 22, 6, 64], [0, 60, 110, 22], 1)] },
/* 1: reserved (DIGITAL, retired: src/fm4_convert.c ENG_FM4_GONE; its sounds load as FM6, FM4 above) */
{ name: "-", titles: ["-", "-"], edit: [D("-", F.INT, 0, 7, 0), D("-", F.INT, 0, 14, 1), D("-", F.INT, 0, 14, 1),
D("-", F.INT, 0, 14, 1), D("-", F.PCT, 0, 127, 60), D("-", F.INT, 0, 127, 60), D("-", F.PCT, 0, 127, 0), NONE],
presets: [] },
{ name: "PHASE", titles: ["PHASE", "LINE"], edit: [E("WAVE", ["SAW", "SQR", "PLS", "DSIN", "SPLS", "RSAW", "RTRI", "RTRP"], 0),
E("WAVE2", ["-", "SAW", "SQR", "PLS", "DSIN", "SPLS", "RSAW", "RTRI", "RTRP"], 0), D("DCW", F.PCT, 0, 127, 60), D("ENV", F.PCT, 0, 127, 64),
D("DETUNE", F.INT, 0, 127, 0, null, "ct"), E("LINE", ["MIX", "RING"], 0), D("SUB", F.PCT, 0, 127, 0), D("FOLD", F.PCT, 0, 127, 0)], /* ((1.3) FOLD) */
presets: [P("PD BRASS", [0, 0, 30, 90, 0, 0, 0, 0], [8, 70, 90, 40], 0, 6), P("PD ORGAN", [3, 0, 40, 0, 0, 0, 0, 0], [0, 127, 127, 30], 0, 6),
P("PD STRINGS", [0, 4, 50, 40, 12, 0, 0, 0], [40, 90, 100, 70], 0, 5), P("RESO", [5, 0, 60, 60, 0, 0, 0, 0], [0, 70, 30, 60], 0, 1),
P("PD BELL", [6, 0, 80, 50, 0, 0, 0, 0], [0, 95, 0, 90], 0, 7), P("WIRE", [4, 7, 70, 40, 7, 0, 0, 0], [10, 80, 80, 60], 0, 4),
/* (Skiff) the themes' sounds (src/eng_*.c) */
P("NEUTRINO", [3, 0, 20, 70, 0, 0, 0, 0], [0, 80, 0, 75]),
/* (Skiff phase 9) more for every engine (src/eng_*.c) */
P("PD BASS", [0, 0, 50, 80, 4, 0, 60, 0], [0, 60, 60, 25], 1),
P("SOFT KEYS", [3, 0, 30, 60, 6, 0, 0, 0], [0, 85, 30, 60])] },
{ name: "LOFI", titles: ["CHIP", "MOTION"], edit: [E("CHIP", ["4BIT", "4B/2", "8BIT", "1BIT", "STEP"], 0), E("WAVE", ["PLS", "TRI", "SAW", "NOIS", "WRAM"], 0), D("DUTY", F.INT, 0, 127, 64),
D("CRUSH", F.PCT, 0, 127, 0), D("SWEEP", F.PCT, 0, 127, 0), D("VIBRATO", F.PCT, 0, 127, 0), E("ARP", ["OFF", "OCT", "MAJ", "MIN"], 0), D("TONE", F.PCT, 0, 127, 127)],
presets: [P("PULSE LD", [0, 0, 32, 0, 0, 20, 0, 127], [0, 60, 90, 30], 1, 4), P("WAVE BASS", [1, 1, 0, 0, 0, 0, 0, 90], [0, 50, 70, 20], 1, 2),
P("ARP 8BIT", [2, 0, 96, 0, 0, 0, 2, 110], [0, 60, 80, 40], 0, 13), P("WAVE LEAD", [0, 4, 92, 0, 0, 18, 0, 110], [0, 70, 90, 30], 1, 3),
P("STEP LEAD", [4, 0, 40, 34, 0, 16, 0, 127], [0, 64, 127, 55], 1, 4),
/* (Skiff) the themes' sounds (src/eng_*.c) */
P("PHOTON", [2, 1, 64, 0, 16, 0, 0, 120], [0, 70, 0, 40]),
/* (Skiff phase 9) more for every engine (src/eng_*.c) */
P("TRI BASS", [0, 1, 64, 0, 0, 0, 0, 100], [0, 60, 90, 20], 1),
P("CHIP BELL", [2, 0, 20, 0, 30, 0, 0, 110], [0, 70, 0, 50])] },
{ name: "SAMPLE", titles: ["SET", "TONE"], edit: [E("SET", ["PIANO", "PIANO", "FLUTE", "SAX", "PIANO", "USR1", "USR2", "USR3"], 0), D("PITCH", F.SEMI, -24, 24, 0), D("BITS", F.INT, 0, 127, 0),
E("LOOP", NONOFF, 1), D("CUTOFF", F.INT, 0, 127, 127), NONE, D("DRIVE", F.PCT, 0, 127, 0), NONE],
presets: [P("PIANO", [0, 0, 0, 1, 127, 0, 0, 0], [0, 127, 127, 70]), P("PIANO", [0, 0, 0, 1, 127, 0, 0, 0], [0, 127, 127, 70]),
P("FLUTE", [2, 0, 0, 1, 127, 0, 0, 0], [12, 80, 120, 60]), P("SAX", [3, 0, 0, 1, 127, 0, 0, 0], [12, 80, 120, 60]),
/* (Skiff phase 9) more for every engine (src/eng_*.c) */
P("PIANO", [0, 0, 0, 1, 127, 0, 0, 0], [0, 127, 127, 70]),
P("LOFI PIANO", [0, 0, 110, 1, 30, 0, 30, 0], [0, 127, 127, 70], 0, 0, [[95, 3], [9, 40], [13, 1]]),
P("MUSIC BOX", [0, 24, 0, 0, 110, 0, 0, 0], [0, 90, 0, 80]),
P("FLUTE PAD", [2, 0, 0, 1, 90, 0, 0, 0], [80, 90, 120, 100]),
P("DARK SAX", [3, -12, 0, 1, 26, 0, 48, 0], [22, 80, 120, 55], 1, 0, [[13, 1], [9, 84], [12, 100]]),
P("KOTO", [0, 12, 0, 0, 120, 0, 22, 0], [0, 72, 0, 50], 0, 0, [[6, 2]])] },
{ name: "VOICE", titles: ["VOWEL", "TONE"], edit: [D("VOWEL", F.INT, 0, 127, 0), D("VOWEL2", F.INT, 0, 127, 64), D("TALK", F.TIME, 0, 127, 0),
D("PITCH", F.SEMI, -12, 12, 0), D("BUZZ", F.PCT, 0, 127, 64), D("BREATH", F.PCT, 0, 127, 10), D("Q", F.PCT, 0, 127, 64), D("RANDOM", F.PCT, 0, 127, 0)],
presets: [P("CHOIR AAH", [0, 0, 0, 0, 40, 22, 60, 0], [85, 90, 115, 95], 0, 5), P("VOX LEAD", [32, 0, 0, 2, 90, 8, 72, 0], [6, 70, 105, 55], 1, 4),
P("WOW BASS", [95, 0, 68, 0, 100, 0, 80, 0], [0, 70, 70, 30], 1, 8), P("WHISPER", [0, 95, 88, 3, 50, 120, 50, 0], [50, 90, 110, 90], 0, 5),
/* (Skiff) the themes' sounds (src/eng_*.c) */
P("CRYPT CHOIR", [112, 0, 0, -3, 34, 30, 64, 14], [90, 90, 118, 100], 0, 0, [[9, 70], [13, 1]]),
P("MONK CHANT", [95, 0, 96, -5, 80, 12, 80, 0], [50, 80, 115, 85], 1, 0, [[9, 82], [12, 96], [13, 1]]),
P("DREAM CHOIR", [0, 20, 0, 3, 55, 45, 55, 8], [80, 90, 118, 95]),
/* (Skiff phase 9) more for every engine (src/eng_*.c) */
P("ROBOT TALK", [20, 100, 40, -12, 110, 4, 90, 30], [0, 70, 100, 30], 1)] },
{ name: "TRIO", titles: ["OSC", "TONE"], edit: [E("WAVE", ["SAW3", "PLS3", "PPT", "SST", "TRI3", "S&T", "P&S", "P+N", "NOIS", "SYNC", "SYNCP", "SYNC3",
"RING", "RING3", "R+S", "R+SP"], 0), D("PITCH2", F.SEMI, -24, 24, 0), D("PITCH3", F.SEMI, -24, 24, -12), D("DETUNE", F.INT, 0, 50, 6, null, "ct"),
E("MODE", ["LP", "BP", "HP", "NOT"], 0), D("CUTOFF", F.CUTOFF, 0, 127, 80), D("RES", F.PCT, 0, 127, 40), D("PW", F.PCT, 0, 127, 64)],
presets: [P("FAT BASS", [0, 0, -12, 9, 0, 62, 45, 64], [0, 62, 60, 25], 1, 2), P("ARP LEAD", [2, 12, 0, 4, 0, 88, 25, 32], [0, 60, 90, 30], 0, 13),
P("SYNC LEAD", [9, 9, 0, 0, 0, 82, 30, 64], [2, 70, 100, 40], 1, 4), P("RING BELL", [13, 0, 18, 6, 1, 96, 30, 64], [0, 92, 0, 80], 0, 7),
P("CHIP CHOIR", [1, 0, 12, 7, 1, 62, 95, 40], [70, 90, 110, 85], 0, 5),
/* (Skiff) the themes' sounds (src/eng_*.c) */
P("TURBO SYNC", [9, 7, 0, 3, 0, 92, 28, 64], [2, 72, 105, 45], 1, 0, [[38, 24], [9, 86], [12, 90], [13, 1]]),
P("NEON ARP", [1, 12, 0, 5, 0, 70, 35, 40], [0, 66, 0, 45]),
P("COLLIDER", [13, 0, 23, 9, 2, 60, 50, 64], [0, 70, 0, 55], 0, 0, [[6, 36]]),
/* (Skiff phase 9) more for every engine (src/eng_*.c) */
P("DIRTY BASS", [1, -12, 0, 8, 1, 62, 85, 30], [0, 50, 50, 20], 1, 0, [[95, 1], [96, -10]])] },
{ name: "WHEEL", titles: ["BARS", "TONE"], edit: [E("REG", ["FLUTE", "MELLOW", "HOLLOW", "SMOOTH", "3BAR", "BLUES", "GOSPEL", "ROCK",
"TOPS", "CLARI", "REED", "STRNG", "CHAPL", "BRITE", "BASS", "FULL"], 4), D("SUB", F.INT, -8, 8, 0), D("BODY", F.INT, -8, 8, 0), D("TOP", F.INT, -8, 8, 0),
E("PERC", ["OFF", "2ND", "3RD", "2SOFT", "3SOFT", "2SLOW", "3SLOW"], 0), D("CLICK", F.PCT, 0, 127, 40), D("DRIVE", F.PCT, 0, 127, 0), E("ROTOR", ["OFF", "SLOW", "FAST"], 1)],
presets: [P("FULL ORGAN", [15, 0, 0, 0, 0, 30, 20, 1], [0, 64, 127, 45], 0, 5), P("JAZZ PERC", [4, 0, 0, 0, 2, 50, 8, 1], [0, 64, 127, 40], 0, 3),
P("GOSPEL", [6, 0, 0, 0, 1, 60, 40, 2], [0, 64, 127, 45], 0, 6), P("SOFT FLUTE", [1, 0, -2, 0, 0, 10, 0, 1], [0, 64, 127, 55], 0, 5),
P("ROCK DRIVE", [7, 0, 0, 0, 0, 70, 100, 2], [0, 64, 127, 40], 0, 4),
/* (Skiff) the themes' sounds (src/eng_*.c) */
P("CATHEDRAL", [12, 2, 0, 0, 0, 6, 0, 0], [48, 64, 127, 72]),
/* (Skiff phase 9) more for every engine (src/eng_*.c) */
P("PEDAL BASS", [14, 4, 0, -4, 0, 20, 10, 0], [0, 64, 127, 30], 1),
P("CLARINET", [9, 0, 2, -5, 0, 0, 14, 1], [24, 64, 120, 45], 1, 0, [[13, 1], [9, 89], [12, 70]])] },
{ name: "GRAIN", titles: ["GRAIN", "SPRAY"], edit: [E("SOURCE", ["PIANO", "PIANO", "FLUTE", "SAX", "PIANO", "USR1", "USR2", "USR3"], 0),
D("POS", F.PCT, 0, 127, 32), D("SIZE", F.PCT, 0, 127, 80), D("DENSITY", F.PCT, 0, 127, 80),
D("PITCH", F.SEMI, -24, 24, 0), D("SPREAD", F.PCT, 0, 127, 30), D("RANDOM", F.PCT, 0, 127, 10), D("TONE", F.PCT, 0, 127, 127)],
presets: [P("CLOUD PAD", [2, 50, 92, 88, 0, 40, 14, 100], [70, 90, 120, 90], 0, 5), P("GLITCH", [3, 64, 24, 112, 0, 100, 90, 127], [0, 70, 100, 30], 0, 4),
P("FROZEN", [0, 40, 108, 72, 0, 0, 10, 92], [50, 100, 127, 100], 0, 5), P("SHIMMER", [0, 30, 70, 100, 12, 30, 24, 110], [30, 90, 110, 90], 0, 7),
/* (Skiff) the themes' sounds (src/eng_*.c) */
P("QUARK CLOUD", [2, 70, 6, 124, 12, 120, 70, 115], [50, 90, 120, 95]),
/* (Skiff phase 9) more for every engine (src/eng_*.c) */
P("PIANO HAZE", [0, 20, 100, 80, 0, 50, 20, 90], [70, 90, 120, 100]),
P("SAX DRONE", [3, 60, 120, 90, -12, 20, 10, 80], [90, 90, 127, 100]),
P("SCATTER", [2, 64, 40, 70, 12, 50, 0, 110], [0, 70, 100, 50])] },
{ name: "PHYS", titles: ["BODY", "EXCITE"], edit: [E("MODEL", ["MODAL", "STRNG", "MEMB", "SYMP"], 0), D("STRUCT", F.PCT, 0, 127, 64),
D("BRIGHT", F.PCT, 0, 127, 80), D("DAMP", F.PCT, 0, 127, 80), D("POS", F.PCT, 0, 127, 20), D("ACCENT", F.PCT, 0, 127, 90),
D("BOW", F.PCT, 0, 127, 0), D("EXCITE", F.PCT, 0, 127, 0)],
presets: [P("BELL TREE", [0, 70, 100, 106, 12, 100, 0, 6], [0, 100, 127, 96], 0, 7), P("MARIMBA", [0, 116, 38, 40, 24, 90, 0, 30], [0, 90, 127, 52], 0, 6),
P("PLUCK", [1, 56, 72, 84, 40, 96, 0, 0], [0, 100, 127, 58], 0, 3), P("BOWED METAL", [0, 98, 70, 112, 10, 80, 90, 0], [60, 90, 127, 90], 0, 5),
P("KALIMBA", [0, 34, 16, 56, 100, 90, 0, 48], [0, 100, 127, 60], 0, 7), P("HAND DRUM", [2, 112, 76, 56, 44, 100, 14, 24], [0, 100, 127, 64], 0, 6),
P("TOMS", [2, 0, 52, 40, 30, 100, 40, 30], [0, 100, 127, 70], 0, 2), P("DRONE STRING", [3, 127, 80, 88, 64, 100, 92, 0], [0, 100, 127, 90], 0, 3),
P("HARP", [3, 8, 62, 74, 60, 90, 0, 0], [0, 100, 127, 80], 0, 3),
/* (Skiff) the themes' sounds (src/eng_*.c) */
P("HARPSICHORD", [1, 44, 112, 76, 10, 127, 0, 24], [0, 100, 127, 50]),
/* (Skiff phase 9) more for every engine (src/eng_*.c) */
P("UPRIGHT", [1, 60, 60, 90, 20, 127, 0, 60], [0, 100, 127, 40], 1)] },
{ name: "DRUM", titles: ["KIT", "HIT"], edit: [E("KIT", ["STD", "66", "10", "77", "80", "10", "66", "55", "77", "DEEP", "TIGHT", "PERC"], 0), D("PITCH", F.ST16, 0, 127, 64),
D("TONE", F.PCT, 0, 127, 64), D("DECAY", F.PCT, 0, 127, 64), D("SNAP", F.PCT, 0, 127, 64), D("ACCENT", F.PCT, 0, 127, 100),
E("KICK", ["PUNCH", "ROUND"], 0), D("DRIVE", F.PCT, 0, 127, 0)],
presets: [P("DRUM KIT", [0, 64, 70, 64, 64, 100, 0, 0], [0, 100, 127, 100], 0, 12),
/* (Skiff) the themes' sounds (src/eng_*.c) */
P("WAR DRUMS", [0, 40, 38, 108, 40, 110, 1, 24], [0, 100, 127, 100]),
P("NEON KIT", [4, 60, 80, 56, 90, 100, 0, 20], [0, 100, 127, 100]),
/* (Skiff phase 9) more for every engine (src/eng_*.c) */
P("BOOM KIT", [4, 58, 60, 100, 50, 100, 0, 10], [0, 100, 127, 100]),
P("CRISP KIT", [5, 64, 76, 60, 80, 100, 0, 0], [0, 100, 127, 100]),
P("RHYTHM BOX", [6, 66, 64, 56, 64, 100, 0, 0], [0, 100, 127, 100]),
P("ELECTRO KIT", [7, 64, 70, 60, 70, 100, 0, 15], [0, 100, 127, 100]),
P("STUDIO KIT", [8, 64, 64, 64, 64, 100, 0, 0], [0, 100, 127, 100]),
P("TIGHT KIT", [0, 70, 80, 30, 100, 110, 0, 10], [0, 100, 127, 100]),
P("LOFI KIT", [0, 56, 30, 70, 40, 100, 1, 50], [0, 100, 127, 100]),
/* (1.3, from Felucca) its kits DEEP, TIGHT, PERC */
P("DEEP DRUMS", [9, 64, 64, 64, 64, 100, 0, 0], [0, 100, 127, 100]),
P("SNAP KIT", [10, 64, 64, 56, 64, 100, 0, 16], [0, 100, 127, 100]),
P("PERC KIT", [11, 64, 64, 64, 64, 100, 0, 0], [0, 100, 127, 100])] },
{ name: "NOISE", titles: ["SOURCE", "MOVE"], edit: [E("MODE", ["ANLG", "DUST", "LFSR", "META"], 0), D("COLOR", F.PCT, 0, 127, 64),
D("CUTOFF", F.CUTOFF, 0, 127, 80), D("RES", F.PCT, 0, 127, 30), D("KEYTRK", F.PCT, 0, 127, 64), D("DENSITY", F.PCT, 0, 127, 0),
D("DRIFT", F.PCT, 0, 127, 0), D("CRUSH", F.PCT, 0, 127, 0)],
presets: [P("WIND", [0, 64, 70, 100, 127, 0, 70, 0], [90, 90, 110, 90], 0, 5), P("RAIN", [1, 30, 88, 80, 64, 105, 40, 0], [50, 90, 127, 70], 0, 5),
P("ARCADE", [2, 0, 127, 0, 127, 112, 0, 84], [0, 80, 0, 50], 0, 3), P("METAL", [3, 0, 100, 40, 100, 32, 0, 0], [0, 75, 40, 60], 0, 7),
/* (Skiff) the themes' sounds (src/eng_*.c) */
P("CAVE WIND", [0, 100, 70, 112, 127, 0, 100, 0], [100, 90, 120, 100]),
P("GEIGER", [1, 10, 100, 40, 64, 34, 0, 0], [0, 90, 127, 40]),
P("PLASMA", [3, 0, 90, 90, 100, 40, 80, 0], [60, 90, 110, 90], 0, 0, [[9, 56], [14, 18]]),
/* (Skiff phase 9) more for every engine (src/eng_*.c) */
P("OCEAN", [0, 50, 60, 20, 0, 0, 40, 0], [100, 90, 120, 110], 0, 0, [[9, 20], [14, 40], [10, 1]])] },
{ name: "FM6", titles: ["OPS", "PATCH"], edit: [D("ALGO", F.INT, 0, 32, 0), D("FEEDBACK", F.INT, -7, 7, 0), D("MOD LVL", F.BIPCT, -64, 63, 0),
D("RATIO", F.INT, -16, 16, 0), D("MOD ENV", F.BIPCT, -64, 63, 0), D("VEL MOD", F.INT, -7, 7, 0), D("DETUNE", F.PCT, 0, 127, 0),
D("PATCH", F.INT, 0, FM6.FACTORY_PK.length, 0)], /* F1..F8, then OWN (eng_fm6.c, 1.0.3) */
presets: [P("TINE EP", [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 127, 0], 0, 6), P("GLASS BELL", [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 127, 0], 0, 7),
P("FM BASS", [0, 0, 0, 0, 0, 0, 0, 2], [0, 0, 127, 0], 1, 2), P("FM BRASS", [0, 0, 0, 0, 0, 0, 0, 3], [0, 0, 127, 0], 0, 4),
P("PAD", [0, 0, 0, 0, 0, 0, 30, 4], [0, 0, 127, 0], 0, 5), P("FM MARIMBA", [0, 0, 0, 0, 0, 0, 0, 5], [0, 0, 127, 0], 0, 3),
P("FM ORGAN", [0, 0, 0, 0, 0, 0, 0, 6], [0, 0, 127, 0], 0, 6), P("NYLON PICK", [0, 0, 0, 0, 0, 0, 0, 7], [0, 0, 127, 0], 0, 13),
/* (Skiff) the themes' sounds (src/eng_*.c) */
P("GRAVE BELL", [0, 0, 6, 0, 20, 0, 30, 1], [0, 0, 127, 0]),
P("GLASS KEYS", [0, 0, 8, 0, 0, 0, 24, 0], [0, 0, 127, 0]),
P("ISOTOPE", [0, 0, 14, 2, -10, 0, 50, 1], [0, 0, 127, 0]),
P("DARK MATTER", [0, 4, 16, 0, 10, 0, 0, 2], [0, 0, 127, 0], 1),
/* (Skiff phase 9) more for every engine (src/eng_*.c) */
P("PICK BASS", [0, 2, 12, 0, 16, 2, 0, 7], [0, 0, 127, 0], 1),
P("GROWL BASS", [0, 5, 8, 0, 20, 0, 8, 3], [0, 0, 127, 0], 1, 0, [[14, 36], [9, 80], [95, 2]])] },
{ name: "SLICE", titles: ["SLICE", "PLAYBACK"], edit: [E("SOURCE", ["BREAK", "USR1", "USR2", "USR3", "PIANO", "FUNK"], 0),
E("DIV", ["4", "8", "16", "32", "AUTO", "MAN"], 2), D("START", F.INT, 0, 31, 0), D("PITCH", F.SEMI, -24, 24, 0),
E("MODE", ["ONE", "GATE", "LOOP"], 0), E("RVRS", ["OFF", "ON"], 0), D("DECAY", F.TIME, 0, 127, 127), D("CUTOFF", F.INT, 0, 127, 127)],
presets: [P("CHOP", [0, 2, 0, 0, 0, 0, 127, 127], [0, 127, 127, 30], 0, 9), P("STUTTER", [0, 1, 0, 0, 1, 0, 90, 110], [0, 127, 127, 12], 0, 10),
/* (Skiff phase 9) more for every engine (src/eng_*.c) */
P("LOW BREAK", [0, 2, 0, -7, 0, 0, 127, 100], [0, 127, 127, 30]),
P("BACK BREAK", [0, 2, 0, 0, 0, 1, 127, 127], [0, 127, 127, 30]),
P("BREAK HITS", [0, 4, 0, 0, 0, 0, 127, 127], [0, 127, 127, 30]),
P("SHORT CHOP", [0, 2, 0, 0, 0, 0, 80, 127], [0, 127, 127, 20]),
P("FAST BREAK", [0, 2, 0, 5, 0, 0, 110, 127], [0, 127, 127, 25], 0, 0, [[95, 1]]),
P("ROLL LOOP", [0, 3, 0, 0, 2, 0, 127, 127], [0, 127, 127, 20]),
/* (Skiff phase 9) more for every engine (src/eng_*.c) */
P("FUNK BREAK", [5, 1, 0, 0, 0, 0, 127, 127], [0, 127, 127, 30])] },
{ name: "DRUM-X", titles: ["KIT", "HIT"], edit: [D("MORPH", F.PCT, 0, 127, 64), D("PITCH", F.ST16, 0, 127, 64), /* (Skiff: JIANT FM's) */
D("COLOR", F.PCT, 0, 127, 64), D("DECAY", F.PCT, 0, 127, 64), D("NOISE", F.PCT, 0, 127, 64), D("FM", F.PCT, 0, 127, 0),
D("FOLD", F.PCT, 0, 127, 0), D("DRIVE", F.PCT, 0, 127, 0)],
presets: [P("OWN KIT", [64, 64, 70, 64, 64, 0, 0, 0], [0, 100, 127, 100], 0, 12),
/* (Skiff) the themes' sounds (src/eng_*.c) */
P("HADRON KIT", [100, 72, 90, 40, 80, 70, 60, 25], [0, 100, 127, 100]),
/* (Skiff phase 9) more for every engine (src/eng_*.c) */
P("FACTORY KIT", [64, 64, 70, 64, 64, 0, 0, 0], [0, 100, 127, 100]),
P("DEEP KIT", [64, 60, 64, 62, 60, 0, 0, 10], [0, 100, 127, 100]),
P("CLICK KIT", [64, 64, 70, 64, 64, 0, 0, 0], [0, 100, 127, 100]),
P("INDUSTRIAL", [64, 62, 70, 64, 70, 20, 30, 40], [0, 100, 127, 100]),
P("SOFT KIT", [64, 64, 56, 60, 56, 0, 0, 0], [0, 100, 127, 100]),
P("GLITCH KIT", [64, 64, 70, 60, 64, 30, 20, 0], [0, 100, 127, 100]),
P("TRIBAL KIT", [64, 64, 64, 64, 60, 0, 0, 0], [0, 100, 127, 100]),
P("LASER KIT", [64, 64, 70, 64, 64, 10, 0, 10], [0, 100, 127, 100])] },
];
const FM6_E = ENG.findIndex((e) => e.name === "FM6"), FM6_OWN = FM6.FACTORY_PK.length, DRUM_E = ENG.findIndex((e) => e.name === "DRUM");
/* factory PATTERNS[] (engines.c; the device loads them from SEQ > PATTERNS, presets only suggest one): absolute
notes, 0 rest; flags 1 accent, 2 slide, 4 tie (holds the previous note) */
const T_ = 4;
const PATTERNS = [
[[45, 45, 57, 45, 0, 48, 45, 55, 45, 0, 57, 52, 45, 48, 0, 50], [1, 0, 2, 0, 0, 0, 1, 2, 0, 0, 1, 0, 0, 2, 0, 1]],
[[0, 36, 0, 36, 0, 36, 0, 48, 0, 36, 0, 36, 0, 39, 0, 43], [0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]],
[[60, 0, 67, 0, 72, 67, 0, 64, 62, 0, 69, 0, 74, 69, 0, 67], [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]],
[[72, 0, 0, 74, 0, 0, 76, 0, 79, 0, 76, 0, 74, 0, 0, 0], [1, T_, 0, 2, T_, 0, 0, 0, 1, 0, 2, 0, 0, T_, T_, 0]],
[[60, 0, 0, 0, 0, 0, 0, 0, 57, 0, 0, 0, 55, 0, 0, 0], [0, T_, T_, T_, T_, T_, T_, 0, 0, T_, T_, 0, 0, T_, T_, 0]],
[[0, 0, 60, 0, 0, 63, 0, 0, 0, 0, 60, 0, 0, 65, 0, 63], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]],
[[72, 0, 0, 79, 0, 0, 84, 0, 0, 0, 76, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
[[36, 0, 0, 0, 0, 0, 0, 36, 0, 0, 34, 0, 0, 0, 0, 0], [1, T_, T_, T_, 0, 0, 0, 0, 0, 0, 0, T_, T_, T_, 0, 0]],
[[60, 61, 62, 67, 64, 65, 60, 69, 68, 70, 62, 67, 72, 72, 74, 64], [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]],
[[60, 60, 61, 61, 62, 0, 63, 63, 64, 65, 65, 0, 66, 66, 66, 67], [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]],
[[60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75], [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]],
[[36, 42, 42, 42, 38, 42, 36, 42, 36, 42, 42, 36, 38, 42, 46, 42], [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]], /* 12 BEAT (DRUM) */
[[48, 51, 55, 60, 63, 67, 72, 75, 48, 51, 55, 60, 63, 67, 72, 75], [1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]], /* 13 ARP */
];
for (let op = 0; op < 4; op++) TP.push(D("ATK", F.TIME, 0, 127, 0), D("DEC", F.TIME, 0, 127, 0), D("SUS", F.PCT, 0, 127, 127), D("REL", F.TIME, 0, 127, 0), D("LVL", F.PCT, 0, 127, 127));
TP.push(E("CHORD", ["OFF", "DIA3", "DIA7", "MAJ", "MIN", "DOM7", "MAJ7", "MIN7", "SUS4", "POW"], 0), /* the chord keys 81, 82 */
E("VOICING", ["CLOSE", "OPEN", "INV1", "INV2", "+OCT"], 0));
for (const l of ["KICK", "SNARE", "CLAP", "CL HAT", "OP HAT", "TOM", "RIM", "BELL"]) TP.push(D(l, F.PCT, 0, 127, 127)); /* 83..90: DRUM lane levels */
TP.push(E("DIR", ["FWD", "RVRS", "PING", "RAND"], 0)); /* 91: (Skiff) the play direction */
TP.push(E("BY", ["OFF", "T1", "T2", "T3", "T4", "T5", "T6"], 0), D("DEPTH", F.PCT, 0, 127, 96), D("RELEASE", F.TIME, 0, 127, 73)); /* 92..94:
(Skiff) the ducking */
TP.push(E("TYPE", ["SOFT", "HARD", "FOLD", "BITS"], 0), D("TONE", F.BIPCT, -64, 63, 0)); /* 95, 96: (Skiff phase 9) DRIVE */
TP.push(D("ATTACK", F.TIME, 0, 127, 0), D("DECAY", F.TIME, 0, 127, 60), D("SUSTAIN", F.PCT, 0, 127, 0),
D("RELEASE", F.TIME, 0, 127, 40)); /* 97..100: (Skiff phase 9) ENV 2 */
for (let k = 0; k < 8; k++) TP.push(D("TUNE", F.ST16, 0, 127, 64)); /* 101..108: (phase 9) the DRUM lanes' TUNE, */
for (let k = 0; k < 8; k++) TP.push(D("DECAY", F.BIPCT, -64, 63, 0)); /* 109..116: .. DECAY (0: as designed) */
TP.push(E("SYNC", ["OFF", "4BAR", "2BAR", "1/1", "1/2", "1/4", "1/8", "8T", "1/16", "16T", "1/32"], 0), /* 117..119: (1.3) LFO 2 */
E("TRIG", ["NOTE", "FREE"], 0), E("POLARITY", ["BI", "UNI"], 0));
TP.push(D("SPREAD", F.PCT, 0, 127, 0)); /* 120: (1.3) SPREAD */
TP.push(E("TYPE", ["OFF", "SOFT", "HARD", "FOLD", "FUZZ", "CRUSH", "PHASR", "FLANG", "CHOR"], 0), /* 121..125: (1.3) the INSERT */
D("A", F.PCT, 0, 127, 64), D("B", F.PCT, 0, 127, 96), D("C", F.PCT, 0, 127, 96), D("MIX", F.PCT, 0, 127, 127));
TP.push(E("SYNC", NONOFF, 0)); /* 126: (1.3) ENV SYNC */
const P_COUNT = 135, G_COUNT = 27, NSTEP = 64, P_E0 = 127, G_ENGSEL = 20, P_SLCR = 45;
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
const enumOrig = (d, v) => d.fmt === F.ENUM && d.names ? aliasOf(d.names, v - d.min) + d.min : v; /* params.c enum_orig */
/* six tracks (firmware v3; Skiff phase 6), a synth part each; engine / preset / p / step below are the selected track's */
const NTRK = 6;
const newTrack = () => ({ engine: 0, preset: 0, fm6: FM6.INIT_PK.slice(),
p: TP.map((d) => d.def).concat(new Array(8).fill(0)),
motion: {on: true, events: []},
step: Array.from({ length: NSTEP }, () => ({ chance: 100, ratchet: 1, n: 0, notes: [0, 0, 0, 0], time: 2, flags: 0, vel: 0, hit: 0, acc: 0 })) });
const st = {
tracks: Array.from({ length: NTRK }, newTrack), sel: 0, rec: 0,
g: GP.map((d) => d.def),
slots: [null, null, null, null], songRows: [], chainPlaying: false, chainRow: 0, chainRemaining: 0,
slotNames: ["", "", "", ""], projCur: -1, projName: "", projSig: "", playing: false, /* ((Skiff W3) PROJ_NAME, TRANSPORT) */
/* ((Skiff W3) the pool (each pattern's LEN, 0 empty: 01 02 T1's A B, 03 T4's A, 04 kept and unused), the lists
([pattern 1..64 or 0, REPS - 1]), the entry each track is on, its pattern + 1, the entry staged (127 none), SONG;
the scenes ({cur, mutes}), the last one, LAUNCH, the mutes staged (bank.c) */
pool: [16, 16, 16, 8].concat(new Array(60).fill(0)),
lists: Array.from({ length: NTRK }, (_, k) => Array.from({ length: 16 }, (_, e) => [k === 0 && e < 2 ? e + 1 : k === 3 && !e ? 3 : 0, 0])),
cur: new Array(NTRK).fill(0), pid: [1, 0, 0, 3, 0, 0], staged: new Array(NTRK).fill(127), song: 0,
scenes: new Array(16).fill(null), sceneLast: -1, launch: 0, muteArm: new Array(NTRK).fill(0),
smp: [0, 1, 2].map(() => ({ flash: new Uint8Array(SMP.SLOT_SIZE).fill(0xFF), zones: 0, name: "", len: 0, next: SMP.DATA_OFF })),
bank: new Array(opt.slots || 32).fill(null), /* user presets: {engine, name, p, pattern, grid, fm6 (FM6: its patch)} */
uiCaps: opt.legacy || opt.v3 || opt.v5 ? 0 : opt.uiCaps ?? 9,
palette: 0, font: 0, monitor: 0, filter: 0, bankSig: 0,
palettes: ["SKIFF", "HI-CON", "PAPER", "CRYPT", "NEON", "QUARK"], // (Skiff, R1) THEME: the device's list (tools/gen_ui_palettes.py)
favorites: Array.from({ length: ENG.length + 1 }, () => []),
watch: false, v4: false, lastReq: 0,
};
for (const k of ["engine", "preset", "p", "step"]) {
Object.defineProperty(st, k, { enumerable: false, get: () => st.tracks[st.sel][k], set: (v) => { st.tracks[st.sel][k] = v; } });
}
const watchMs = opt.watchMs || 3000;
const desc = (scope, id) => (scope === 0 && id < P_COUNT ? (id >= P_E0 ? ENG[st.engine].edit[id - P_E0] : TP[id])
: scope === 1 && id < G_COUNT ? GP[id] : null);
const EMPTY = { n: 0, notes: [0, 0, 0, 0], time: 2, flags: 0, vel: 0, hit: 0, acc: 0, chance: 100, ratchet: 1 };
const isDrum = () => ["DRUM", "DRUM-X"].includes(ENG[st.engine].name); /* (Skiff: DRUM-X a drum track too) */
const clearSteps = () => st.step.forEach((s) => Object.assign(s, EMPTY, { notes: [0, 0, 0, 0] }));
function toGrid(s) { /* eng_drum.c step_to_grid: a lane's own note becomes its hit */
if (s.time !== 0) return;
const keep = s.notes.slice(0, s.n).filter((n) => { const l = drumLane(n); if (n !== LANE_NOTE[l]) return true; s.hit |= 1 << l; return false; });
s.notes = [...keep, 0, 0, 0, 0].slice(0, 4); s.n = keep.length;
if (!s.n && s.flags & 1) { s.acc |= s.hit; s.flags &= ~1; }
}
function loadPat16(pat) { /* ui.c load_pat16 (into a DRUM track: its grid) */
const ps = stepsFromPattern(pat);
st.step.forEach((s, i) => { Object.assign(s, EMPTY, i < 16 ? ps[i] : { notes: [0, 0, 0, 0] }); if (isDrum()) toGrid(s); });
st.p[29] = 16;
}
const loadPattern = (k) => loadPat16(PATTERNS[k][0].map((n, i) => [n, PATTERNS[k][1][i]]));
function applyPreset(pi) {
const e = ENG[st.engine];
if (e.name === "SAMPLE" && pi === PERC_SET) { setEngine(DRUM_E); return; } /* once PERC: DRUM's kit (ui.c apply_preset_to) */
pi = aliasOf(e.presets.map((x) => x.name), pi % e.presets.length);
const pr = e.presets[pi];
st.preset = pi;
for (let i = 0; i < P_E0; i++) if (!trackOwn(i, P_E0)) st.p[i] = TP[i].def; /* the rest of the sound to its defaults:
the matrix off; the SLICER, the chord keys, the steps and the other track
settings stay (ui.c apply_preset_to) */
for (let i = 0; i < 8; i++) st.p[P_E0 + i] = pr.e[i];
[1, 2, 3, 4].forEach((id, k) => { st.p[id] = pr.env[k]; });
st.p[37] = pr.mono ? 2 : 0;
st.p[33] = 0; st.p[34] = 24; st.p[35] = 28; st.p[36] = 36;
for (const [id, v] of pr.more) st.p[id] = v; /* (Skiff) its LFO, GLIDE, .. (core.h preset_t more) */
if (e.name === "DRUM-X" && DRUMX_PKIT[pi]) /* ((Skiff phase 9) its kit, the project's: eng_drumx.c DRUMX_PKIT) */
st.kit = DX_KITS[DRUMX_PKIT[pi] - 1].map(([mode, x, y]) => ({ mode, a: x.slice(), b: y.slice() }));
if (st.engine === FM6_E) { /* eng_fm6.c fm6_track_loaded */
const t = st.tracks[st.sel];
t.own = null;
if (st.p[P_E0 + 7] < FM6_OWN) { t.fm6 = FM6.FACTORY_PK[st.p[P_E0 + 7]].slice(); t.slot = st.p[P_E0 + 7]; } else fm6Adopt(t);
}
}
/* SLOT s turned (eng_fm6.c fm6_poll): F1..F8 that factory patch (from OWN the own patch kept aside), OWN the own
patch back */
function fm6Slot(t, s) {
if (s === t.slot) return;
if (s >= FM6_OWN) { if (t.own) t.fm6 = t.own; t.own = null; t.slot = FM6_OWN; return; }
if (t.slot === FM6_OWN && !t.own) t.own = t.fm6.slice();
t.fm6 = FM6.FACTORY_PK[s].slice(); t.slot = s;
}
/* t's patch was put in as its own (eng_fm6.c fm6_adopt): SLOT = the factory patch it equals, else OWN */
function fm6Adopt(t) {
t.own = null;
if (t.engine !== FM6_E) return;
const k = FM6.FACTORY_PK.findIndex((pk) => pk.every((x, i) => x === t.fm6[i]));
t.p[P_E0 + 7] = t.slot = k < 0 ? FM6_OWN : k;
}
function setEngine(ei) {
if (ei % ENG.length === 1) { fm4Load(0); return; } /* DIGITAL (retired): its first preset, as FM6 (ui.c set_engine_of) */
st.engine = ei % ENG.length;
for (let i = 0; i < 8; i++) st.p[P_E0 + i] = ENG[st.engine].edit[i].def;
applyPreset(0);
}
/* the selected track's sound = p, DIGITAL's values, converted (ui.c fm4_apply) */
function fm4Apply(p) {
const r = FM4.convert(p, P_E0);
st.engine = FM6_E; st.preset = r.preset; st.p = r.p;
st.tracks[st.sel].fm6 = FM6.pack(r.voice);
fm6Adopt(st.tracks[st.sel]); /* (the converted patch is the track's own: SLOT OWN) */
}
function fm4Load(k) { /* a DIGITAL preset number (ui.c fm4_load_preset) */
const p = st.p.map((x, i) => (i < P_E0 && !trackOwn(i, P_E0) ? TP[i].def : x));
fm4Apply(FM4.presetValues(p, k, P_E0));
}
const snapshot = (name) => { /* (upreset.c up_store: a DRUM track that strikes a lane: its grid; an FM6
track: its patch, up_fm6.c) */
const grid = isDrum() ? gridFromSteps(st.step) : null;
const fm6 = st.engine === FM6_E ? st.tracks[st.sel].fm6.slice() : null;
return patternUsed(grid) ? { engine: st.engine, name, p: st.p.slice(), pattern: null, grid, fm6 }
: { engine: st.engine, name, p: st.p.slice(), pattern: patternFromSteps(st.step), grid: null, fm6 };
};
const ratchetOn = () => !!syncCaps() && !opt.noRatchet; /* (INFO 52 01 04, after the sync tag) */
const stepxOn = () => ratchetOn() && !opt.noStepx; /* (Skiff W1) a step's FLAM, COND, NUDGE (INFO 43 01) */
const locksOn = () => ratchetOn() && !opt.noLocks; /* (1.1, INFO 4C 01 01) MOTION ops 5..7 */
const kitOn = () => stepxOn() && !opt.noKit; /* (Skiff W3, INFO 4B 01 08) the DRUM-X kit */
const projOn = () => kitOn() && !opt.noProj; /* (Skiff W3, INFO 57 01 03) TRANSPORT, PROJ_NAME */
const songOn = () => projOn() && !opt.noSong; /* (Skiff W3, INFO 57 01 31) POOL, LIST, PERFORM */
const stepOut = (x, b) => { b(x.n); x.notes.forEach(b); b(x.time); b(x.flags); b(x.vel); hitsEnc(x.hit, x.acc).forEach(b); if (!opt.legacy && !opt.v3 && !opt.v5) b(x.chance ?? 100); if (ratchetOn()) b(x.ratchet ?? 1);
if (stepxOn()) { b(x.flam ? 1 : 0); b(x.cond | 0); b(((x.nudge | 0) + 32) & 63); } };
function stepIn(x, a) { /* editor.c ed_step_put: n, 4 notes, time, flags, vel [, hits (3) [, chance [, ratchet]]] */
x.n = Math.min(4, a[0]); x.notes = a.slice(1, 5); x.time = Math.min(2, a[5]); x.flags = a[6] & 3; x.vel = a[7];
if (a.length >= 11) { x.hit = a[8] | (a[10] & 1) << 7; x.acc = (a[9] | (a[10] & 2) << 6) & x.hit; }
if (a.length >= 12) x.chance = Math.min(100, a[11]);
if (a.length >= 13 && ratchetOn() && a[12] !== (x.ratchet ?? 1)) { x.ratchet = Math.max(1, Math.min(4, a[12])); x.flam = 0; }
if (a.length >= 16 && stepxOn()) { /* (Skiff W1) FLAM (x1 only), COND, NUDGE (as the firmware: kept otherwise) */
x.flam = a[13] && (x.ratchet ?? 1) === 1 ? 1 : 0; x.cond = a[14] < TC_NAMES.length ? a[14] : 0; x.nudge = Math.min(63, a[15]) - 32;
}
}
/* a few user presets to start with, each with its preset's suggested pattern stored (as UP_STORE would) */
[[0, 0, 0, "MY LEAD"], [1, FM6_E, 1, "GLASS BELL"], [2, 2, 3, "PHASE RESO"], [5, 3, 2, "8BIT ARP"]].forEach(([slot, e, p, name]) => {
setEngine(e); applyPreset(p);
if (ENG[e].presets[p].pat) loadPattern(ENG[e].presets[p].pat - 1);
st.bank[slot] = snapshot(name);
clearSteps(); st.p[29] = 16;
});
/* the power-on sounds (engines.c TRK_DEF): ACID, PAD, PULSE LD, DRUM KIT, (Skiff phase 6) PIANO, DRUM KIT */
[[1, FM6_E, 4], [2, 3, 0], [3, 10, 0], [4, 4, 0], [5, 10, 0], [0, 0, 4]].forEach(([i, e, p]) => { st.sel = i; setEngine(e); applyPreset(p); });
/* the device powers on with its sequencers empty; the mock starts as a little demo to look at: track 1 with
the ACID pattern, track 4 with BEAT (as SEQ > PATTERNS would load them), pads left, lead right */
st.sel = 3; loadPattern(11);
st.sel = 0; loadPattern(0);
st.tracks[1].p[39] = -24; st.tracks[2].p[39] = 20; st.tracks[2].p[0] = 92;
const project = () => JSON.parse(JSON.stringify({ tracks: st.tracks, sel: st.sel, g: st.g, songRows: st.songRows }));
st.slots[0] = project();
/* ((Skiff W3) bank.c, as the mock needs it: the entry track k is on (127: on no entry's pattern), what uses pattern
id, track k to entry e (at once stopped, staged playing; 1: empty), a MUTE to m (staged playing), STOP landing what
is staged) */
const bankCur = (k) => { const p = st.lists[k][st.cur[k]][0]; return p && p === st.pid[k] ? st.cur[k] : 127; };
const refsOf = (id) => st.lists.reduce((n, l) => n + l.filter((x) => x[0] === id + 1).length, 0) +
st.pid.filter((p, k) => p === id + 1 && bankCur(k) === 127).length;
const entryGo = (k, e) => {
const p = st.lists[k][e][0];
if (!p || !st.pool[p - 1]) return 1;
if (st.playing) st.staged[k] = e; else { st.cur[k] = e; st.pid[k] = p; st.staged[k] = 127; }
return 0;
};
const muteTo = (k, m) => {
const tp = st.tracks[k].p;
st.muteArm[k] = 0;
if (!st.playing) tp[40] = m ? 1 : 0;
else if (!!tp[40] !== !!m) st.muteArm[k] = m ? 2 : 1;
};
const landStaged = () => {
st.staged.forEach((e, k) => { if (e !== 127) { st.cur[k] = e; st.pid[k] = st.lists[k][e][0]; st.staged[k] = 127; } });
st.muteArm.forEach((m, k) => { if (m) st.tracks[k].p[40] = m - 1; st.muteArm[k] = 0; });
};
function handle(cmd, a) {
const out = [];
const b = (x) => out.push(x & 0x7F), v = (x) => out.push(...v14enc(x)), s = (x) => out.push(...strEnc(x));
const light = () => { /* (Skiff phase 6) INFO 54 01: T5, T6; no GRAIN, no PHYS there */
const e = ENG.reduce((m, x, i) => m | (x.name === "GRAIN" || x.name === "PHYS" ? 1 << i : 0), 0);
[0x54, 1, 0x30, e, e >> 7, e >> 14].forEach(b);
if (stepxOn()) [0x43, 1, TC_NAMES.length].forEach(b); /* (Skiff W1) */
if (kitOn()) [0x4B, 1, 8].forEach(b); /* (Skiff W3) */
if (projOn()) [0x57, 1, songOn() ? 31 : 3].forEach(b);
if (projOn()) [0x49, 1, P_COUNT & 127, P_COUNT >> 7, P_E0 & 127, P_E0 >> 7].forEach(b); /* ((Skiff 1.3) wide ids) */
};
const wid = (s, i) => (s === 2 ? [0, i + 128] : [s, i]); /* ((1.3) scope 2: a track id from 128 on) */
if (opt.legacy && cmd >= CMD.UP_LIST) return null;
if (opt.v3 && cmd >= CMD.TRACK_PARAM) return null;
if (opt.v5 && cmd >= CMD.SONG) return null;
if (!st.uiCaps && cmd >= CMD.UI_STATE) return null;
const uiState = () => {
const sig = JSON.stringify(st.favorites).split("").reduce((h, c) => Math.imul(h ^ c.charCodeAt(0), 16777619) >>> 0, st.filter);
[st.uiCaps, st.palette, st.uiCaps & 2 ? st.font : 127, st.uiCaps & 4 ? st.monitor : 127, st.uiCaps & 8 ? st.filter : 127].forEach(b);
for (const n of [sig, st.bankSig]) for (let i = 0; i < 4; i++) b(n >>> (i * 7));
};
const NB = st.bank.length;
switch (cmd) {
case CMD.UP_LIST: {
if (a.length < 2) return null;
const start = a[0], n = Math.max(0, Math.min(a[1], UP.LIST_MAX, NB - start));
b(start); b(n); b(NB);
for (let i = start; i < start + n; i++) { const u = st.bank[i]; b(u ? 1 : 0); b(u ? u.engine : 0); s(u ? u.name : ""); }
break;
}
case CMD.UP_GET: {
if (a.length < 1 || a[0] >= NB) return null;
const u = st.bank[a[0]];
b(a[0]); b(u ? 1 : 0); b(u ? u.engine : 0); s(u ? u.name : "");
for (let i = 0; i < P_COUNT; i++) v(u ? u.p[i] : 0);
if (u && u.grid) { /* kind 1: the grid's low 7 bits, then its bit 7s */
for (let i = 0; i < UP.PAT; i++) { const x = hitsEnc(...u.grid[i]); b(x[0]); b(x[1]); }
b(1);
for (let i = 0; i < UP.PAT; i++) b(hitsEnc(...u.grid[i])[2]);
} else {
for (let i = 0; i < UP.PAT; i++) { const x = u ? u.pattern[i] : [0, 0]; b(x[0]); b(x[1]); }
b(0);
}
break;
}
case CMD.UP_PUT: {
if (a.length < 3) return null;
const r = new Reader(a);
let rc = 0;
try {
const slot = r.b(), engine = r.b(), name = r.s(), p = [], raw = [];
let pattern = null, grid = null;
for (let i = 0; i < P_COUNT; i++) p.push(r.v());
for (let i = 0; i < UP.PAT; i++) raw.push([r.b(), r.b()]);
const tail = a.length - r.i;
if (tail !== 0 && (tail !== 1 + UP.PAT || a[r.i] > 1)) throw new Error("bad preset extension");
if (tail && a[r.i] === 1) { /* kind 1: a complete drum grid */
r.b();
grid = raw.map(([h, c]) => { const x = r.b(), hit = h | (x & 1) << 7; return [hit, (c | (x & 2) << 6) & hit]; });
} else pattern = raw.map(([n, f]) => patNorm(n, f));
if (slot >= NB || engine >= ENG.length || !name.length || name.length > UP.NAME_MAX || /[^\x20-\x7E]/.test(name)) rc = 1;
else {
const saved = st.engine; /* values clamped to the ranges of that engine */
const pc = fromPerc({ engine, p }, ENG.map((x) => x.name), P_E0); /* SAMPLE PERC: DRUM (upreset.c up_migrate) */
st.engine = pc ? pc.engine : engine;
st.bank[slot] = { engine: st.engine, name, p: (pc ? pc.p : p).map((x, i) => { const d = desc(0, i); return clamp(x, d.min, d.max); }), pattern, grid };
st.engine = saved;
}
} catch (e) { rc = 1; }
b(a[0]); b(rc);
break;
}
case CMD.UP_STORE: {
if (a.length < 2) return null;
const name = new Reader(a.slice(1)).s();
const rc = a[0] >= NB || name.length > UP.NAME_MAX ? 1 : 0;
if (!rc) st.bank[a[0]] = snapshot(name || `${ENG[st.engine].name} ${String(a[0] + 1).padStart(2, "0")}`); /* (FM6: its patch) */
b(a[0]); b(rc);
break;
}
case CMD.UP_LOAD: {
if (a.length < 1) return null;
const u = st.bank[a[0]];
if (u) { /* the sound only (upreset.c up_load): the steps and the track's own */
const own = st.p.slice(); /* parameters (TRACK_OWN: mix, ARP, SCL, LEN.., SLICER) stay */
const p = u.p.map((x, i) => (trackOwn(i, P_E0) ? own[i] : x));
if (u.engine === 1) fm4Apply(p); /* a DIGITAL record (kept as it is): FM6 */
else { st.engine = u.engine; st.preset = 0; st.p = p; }
if (u.engine === FM6_E) { /* its own patch (up_fm6.c upf_track_load); none: SLOT's factory / init */
const t = st.tracks[st.sel], s = p[P_E0 + 7];
t.fm6 = (u.fm6 || (s < FM6_OWN ? FM6.FACTORY_PK[s] : FM6.INIT_PK)).slice();
fm6Adopt(t);
}
}
b(a[0]); b(u ? 0 : 1);
break;
}
case CMD.UP_ERASE:
if (a.length < 1) return null;
if (a[0] < NB) { st.bank[a[0]] = null; st.favorites[ENG.length][a[0]] = false; }
b(a[0]); b(a[0] < NB ? 0 : 1);
break;
case CMD.WATCH:
if (a.length < 1) return null;
st.watch = !!(a[0] & 1);
st.v4 = st.watch && !opt.v3 && !!(a[0] & 2); /* v4: TRACK_CHANGED pushes too */
b((st.watch ? 1 : 0) | (st.v4 ? 2 : 0));
break;
case CMD.PING:
b(0);
break;
case CMD.UI_STATE: uiState(); break;
case CMD.UI_PALETTES: b(st.palettes.length); st.palettes.forEach(s); break;
case CMD.UI_SET: {
const id = a[0], val = a[1], key = ["palette", "font", "monitor", "filter"][id];
const rc = a.length !== 2 || !key ? 1 : !(st.uiCaps & 1 << id) ? 2 : val >= (id === 0 ? st.palettes.length : id === 2 ? 3 : 2) ? 1 : 0;
if (!rc) st[key] = val;
b(rc || (opt.noFlash ? 3 : opt.deferSettings ? 4 : 0)); b(id ?? 127); b(val ?? 127); uiState(); break;
}
case CMD.FAV_GET: case CMD.FAV_SET: {
if (!(st.uiCaps & 8)) { b(2); break; }
const engine = a[0], preset = v14dec(a[1], a[2]), count = a[3];
const limit = engine === ENG.length ? st.bank.length : engine < ENG.length ? ENG[engine].presets.length : 0;
if (a.length !== 4 || preset < 0 || preset >= limit ||
(cmd === CMD.FAV_GET ? !count || count > 32 || preset + count > limit : count > 1 || engine === ENG.length && count && !st.bank[preset])) { b(1); break; }
if (cmd === CMD.FAV_SET) st.favorites[engine][preset] = !!count;
b(cmd === CMD.FAV_SET ? (opt.noFlash ? 3 : opt.deferSettings ? 4 : 0) : 0); b(engine); v(preset); b(count);
if (cmd === CMD.FAV_GET) for (let i = 0; i < count; i++) b(!!st.favorites[engine][preset + i]);
break;
}
case CMD.MENU_DESC: case CMD.MENU_SET: { /* (Skiff W3) editor_menu.c */
if (opt.noMenu || !st.uiCaps || !syncCaps()) return null;
st.menu = st.menu || Object.fromEntries(MENU.map((x) => [x.id, x.def]));
const names = (x) => x.names || st.palettes;
const val = (x) => x.id === 0 ? st.palette : st.menu[x.id];
if (cmd === CMD.MENU_DESC) {
const x = MENU[a[0]];
b(a[0]);
if (!x) { b(127); break; }
b(x.id); b(0); v(val(x)); v(0); v(names(x).length - 1); s(x.name); names(x).forEach(s); b(x.tab); s(MENU_TABS[x.tab]);
} else {
const x = MENU.find((m) => m.id === a[0]);
if (!x) { b(1); b(a[0]); v(0); break; }
const w = Math.max(0, Math.min(names(x).length - 1, v14dec(a[1], a[2])));
if (x.id === 0) st.palette = w; else st.menu[x.id] = w;
b(0); b(x.id); v(w);
}
break;
}
case CMD.TRANSPORT: { /* (Skiff W3) editor_project.c (the mock's audio takes a request at once) */
if (!projOn() || a.length > 1 || (a.length && (a[0] < 1 || a[0] > 4))) return null;
if (a[0] === 4) { st.rec ^= 1 << st.sel; if (st.rec >> st.sel & 1) st.playing = true; } /* (as its button) */
else if (a[0] === 1 || a[0] === 3) st.playing = true;
else if (a[0] === 2) { st.playing = false; landStaged(); } /* (stopped: what is staged comes in) */
[0, +st.playing, 0, 0, st.rec, st.sel].forEach(b);
break;
}
case CMD.PROJ_NAME: { /* (Skiff W3) editor_project.c: SAVE AS, RENAME (the transport stopped first) */
if (!projOn()) return null;
let rc = 0;
if (a.length) {
const nb = a.slice(2);
if (nb.length && !nb[nb.length - 1]) nb.pop();
if (a.length < 2 || (a[0] !== 1 && a[0] !== 2) || a[1] > 3 || nb.length > 12 || nb.some((c) => c < 32 || c > 126)) return null;
const nm = String.fromCharCode(...nb).toUpperCase(), k = a[1];
st.playing = false;
if (a[0] === 1) { st.slots[k] = project(); st.slotNames[k] = nm; st.projCur = k; st.projName = nm; st.projSig = JSON.stringify(project()); }
else if (!st.slots[k]) rc = 1;
else { st.slotNames[k] = nm; if (st.projCur === k) st.projName = nm; }
}
b(a.length ? a[0] : 0); b(rc); b(st.projCur < 0 ? 127 : st.projCur); b(JSON.stringify(project()) !== st.projSig ? 1 : 0); s(st.projName);
for (let k = 0; k < 4; k++) { b(st.slots[k] ? 1 : 0); s(st.slots[k] ? st.slotNames[k] : ""); }
break;
}
case CMD.POOL: { /* (Skiff W3) editor_song.c */
if (!songOn() || (a.length && (a.length !== 2 || a[0] !== 1 || a[1] > 63))) return null;
let rc = 0;
if (a.length) {
const id = a[1];
if (!st.pool[id]) rc = 1; else if (refsOf(id)) rc = 2; else if (st.playing) rc = 3; else st.pool[id] = 0;
}
b(a.length ? 1 : 0); b(rc);
for (let i = 0; i < 64; i++) { b(st.pool[i]); b(Math.min(127, refsOf(i))); }
break;
}
case CMD.LIST: { /* (Skiff W3) editor_song.c */
const [op, k, e, v] = a, L = st.lists;
if (!songOn() || (a.length && !(op === 6 ? a.length === 2 && k <= 1 : a.length >= 3 && k < NTRK && e < 16 &&
(op === 1 || op === 5 ? a.length === 4 && v >= 1 && v <= (op === 1 ? 64 : 16) : a.length === 3 && op >= 2 && op <= 4)))) return null;
let rc = 0;
if (op === 1) { if (!st.pool[v - 1]) rc = 1; else { L[k][e][0] = v; if (st.cur[k] === e) rc = entryGo(k, e); } }
else if (op === 2) {
const id = L[k][e][0] - 1, n = st.pool.findIndex((x) => !x);
if (id < 0) rc = 1;
else if (n < 0) rc = 4;
else { st.pool[n] = st.pool[id]; L[k][e][0] = n + 1; if (st.cur[k] === e && st.pid[k] === id + 1) st.pid[k] = n + 1; }
} else if (op === 3) rc = entryGo(k, e);
else if (op === 4) {
if (st.playing) rc = 3;
else {
const id = L[k][e][0] - 1, on = st.cur[k] === e && st.pid[k] === id + 1;
L[k][e] = [0, 0];
if (on) st.pid[k] = 0;
if (id >= 0 && !refsOf(id)) st.pool[id] = 0;
}
} else if (op === 5) { if (!L[k][e][0]) rc = 1; else L[k][e][1] = v - 1; }
else if (op === 6) st.song = k;
b(a.length ? op : 0); b(rc); b(st.song);
for (let t = 0; t < NTRK; t++) {
b(bankCur(t)); b(st.staged[t]); b(st.pid[t] ? st.pid[t] - 1 : 127);
L[t].forEach(([p, r]) => { b(p); b(r); });
}
break;
}
case CMD.PERFORM: { /* (Skiff W3) editor_song.c */
const [op, v] = a;
if (!songOn() || (a.length && !(op === 4 ? a.length === 1 : a.length === 2 &&
((op >= 1 && op <= 2 && v < 16) || (op === 3 && v < NTRK) || (op === 5 && v < 4))))) return null;
let rc = 0;
if (op === 1) { st.scenes[v] = { cur: st.lists.map((_, k) => bankCur(k)), mutes: st.tracks.map((x) => x.p[40] ? 1 : 0) }; st.sceneLast = v; }
else if (op === 2) {
const sc = st.scenes[v];
if (!sc) rc = 1;
else {
sc.cur.forEach((e, k) => { if (e !== 127 && e !== bankCur(k)) entryGo(k, e); });
sc.mutes.forEach((m, k) => muteTo(k, m));
st.sceneLast = v;
}
} else if (op === 3) { if (st.muteArm[v]) st.muteArm[v] = 0; else muteTo(v, st.tracks[v].p[40] ? 0 : 1); }
else if (op === 4) { st.staged.fill(127); st.muteArm.fill(0); }
else if (op === 5) st.launch = v;
const bits = st.scenes.reduce((m, x, i) => m | (x ? 1 << i : 0), 0);
[a.length ? op : 0, rc, st.launch, st.sceneLast < 0 ? 127 : st.sceneLast, bits & 127, bits >> 7 & 127, bits >> 14 & 3].forEach(b);
st.tracks.forEach((x, k) => { b(x.p[40] ? 1 : 0); b(st.muteArm[k]); });
break;
}
case CMD.KIT_GET: case CMD.KIT_PUT: { /* (Skiff W3) editor.c: a lane; KIT_PUT its 15 values in range (else no reply) */
if (!kitOn() || a[0] > 7 || a.length !== (cmd === CMD.KIT_GET ? 1 : 16)) return null;
if (cmd === CMD.KIT_PUT && (a[1] > 3 || a[2] > 2 || a[3] > 1 || a[4] > 3 || a[5] > 1)) return null;
st.kit = st.kit || DX_KIT_DEF.map(([mode, x, y]) => ({ mode, a: x.slice(), b: y.slice() }));
const L = st.kit[a[0]];
if (cmd === CMD.KIT_PUT) { L.mode = a[1] | a[2] << 2 | a[3] << 4 | a[4] << 5 | (a[5] ? 0x80 : 0); L.a = a.slice(6, 11); L.b = a.slice(11, 16); }
[a[0], L.mode & 3, L.mode >> 2 & 3, L.mode >> 4 & 1, L.mode >> 5 & 3, L.mode >> 7 & 1, ...L.a, ...L.b].forEach(b);
break;
}
case CMD.MOTION: {
const track = st.tracks[a[0]], m = track && track.motion;
if (!m) return null;
let rc = 0;
if (a.length > 1 && st.chainPlaying) rc = 3;
else if (a[1] === 1) m.on = !!a[2];
else if (a[1] === 2) m.events = [];
else if (a[1] === 6 && locksOn()) m.events = m.events.filter(e => !e.lock || (a[2] !== 127 && e.step !== a[2]));
else if (a[1] === 3 || a[1] === 4 || (a[1] === 5 && locksOn())) { /* (1.1: 5 a lock, as 3 an event) */
const step = a[2] & 63, param = a[3] | (a[2] >> 6 & 1) << 7; /* ((1.3) bit 6: the id's bit 7) */
const at = m.events.findIndex(e => e.step === step && e.param === param);
if (a[1] === 4) { if (at >= 0) m.events.splice(at, 1); }
else if (at < 0 && st.tracks.reduce((n,t) => n + t.motion.events.length, 0) >= 64) rc = 2;
else { const e = {step,param,value:v14dec(a[4],a[5]),lock:a[1] === 5}; if (at >= 0) m.events[at] = e; else m.events.push(e); }
} else if (a.length > 1 && !(a[1] === 7 && locksOn())) rc = 1;
[a[0],rc,+m.on,m.events.length,64].forEach(b);
m.events.forEach(e => {b(e.step | (e.param >> 7) << 6);b(e.param & 127);v(e.value);});
if (a.length > 1 && a[1] >= 5 && locksOn()) m.events.forEach(e => b(e.lock ? 1 : 0)); /* (the kinds) */
break;
}
case CMD.INFO:
s(opt.legacy ? "FELUCCA 0.4 BETA (MOCK)" : "SKIFF (MOCK)"); b(ENG.length); b(Math.min(P_COUNT, 127)); b(G_COUNT); b(NSTEP); b(Math.min(P_E0, 127));
ENG.forEach((e) => s(e.name));
if (!opt.legacy) b(NTRK);
if (!opt.legacy && !opt.v3 && !opt.v5) {
b(16);
if (st.uiCaps) { b(0x55); b(1); b(st.uiCaps); b(0x4d); b(1); b(64); b(1); if (!opt.noFm6) { b(0x46); b(1); b(FM6.FACTORY_PK.length); b(0); }
if (syncCaps()) { b(0x53); b(1); b(syncCaps()); if (!opt.noFm6) { b(0x50); b(1); b(3); } if (!opt.noMenu) { b(0x4E); b(1); b(MENU.length); } if (ratchetOn()) { b(0x52); b(1); b(4); if (locksOn()) { b(0x4C); b(1); b(1); } light(); } } } /* (FM6 v2: no bank, preset patches) */
}
break;
case CMD.GET: case CMD.SET: {
if (a.length < 2) return null;
const [sc, id] = wid(a[0], a[1]), d = desc(sc, id);
if (!d) return null;
const arr = sc ? st.g : st.p;
if (cmd === CMD.SET && a.length >= 4) {
if (sc === 1 && id === G_ENGSEL) setEngine(clamp(v14dec(a[2], a[3]), 0, ENG.length - 1));
else if (d.max > d.min) arr[id] = enumOrig(d, clamp(v14dec(a[2], a[3]), d.min, d.max));
if (!sc && id === P_E0 + 7 && st.engine === FM6_E) fm6Slot(st.tracks[st.sel], arr[id]); /* PTCH (fm6_poll) */
}
b(a[0]); b(a[1]); v(arr[id]);
break;
}
case CMD.DUMP:
b(st.engine); b(st.preset); st.p.forEach(v); st.g.forEach(v);
break;
case CMD.TRACK:
if (a.length >= 1 && a[0] < NTRK) st.sel = a[0];
b(st.sel); b(NTRK);
st.tracks.forEach((t, i) => { b(t.engine); b(t.preset); v(t.p[0]); b(t.p[40] ? 1 : 0); b((st.rec >> i) & 1); });
break;
case CMD.TRACK_MIX: {
if (a.length < 1 || a[0] >= NTRK) return null;
const t = st.tracks[a[0]];
if (a.length >= 4) {
t.p[0] = clamp(v14dec(a[1], a[2]), 0, 127);
t.p[40] = a[3] ? 1 : 0;
}
b(a[0]); v(t.p[0]); b(t.p[40] ? 1 : 0);
break;
}
case CMD.TRACK_DUMP: {
if (a.length < 1 || a[0] >= NTRK) return null;
const t = st.tracks[a[0]];
b(a[0]); b(t.engine); b(t.preset); t.p.forEach(v);
break;
}
case CMD.TRACK_PARAM: {
const tr = a[0] & 63, id = a[1] | (a[0] >> 6 & 1) << 7; /* ((1.3) bit 6: the id's bit 7) */
if (a.length < 2 || tr >= NTRK || id >= P_COUNT) return null;
const t = st.tracks[tr], d = id >= P_E0 ? ENG[t.engine].edit[id - P_E0] : TP[id];
if (a.length >= 4 && d.max > d.min) t.p[id] = enumOrig(d, clamp(v14dec(a[2], a[3]), d.min, d.max));
b(a[0]); b(a[1]); v(t.p[id]);
break;
}
case CMD.TRACK_STEP: {
if (a.length < 2 || a[0] >= NTRK || a[1] >= NSTEP) return null;
const x = st.tracks[a[0]].step[a[1]];
if (a.length >= 10) stepIn(x, a.slice(2));
b(a[0]); b(a[1]); stepOut(x, b);
break;
}
case CMD.DESC: {
if (a.length < 2) return null;
const d = desc(...wid(a[0], a[1]));
if (!d) return null;
b(a[0]); b(a[1]); b(d.fmt); v(d.min); v(d.max); v(d.def); s(d.label); s(d.unit || "");
if (d.fmt === F.ENUM && d.names) for (let i = 0; i <= d.max - d.min && i < 24; i++) s(d.names[i]);
break;
}
case CMD.STEP_GET: case CMD.STEP_SET: {
if (a.length < 1 || a[0] >= NSTEP) return null;
const x = st.step[a[0]];
if (cmd === CMD.STEP_SET && a.length >= 9) stepIn(x, a.slice(1));
b(a[0]); stepOut(x, b);
break;
}
case CMD.FM6_GET: case CMD.FM6_PUT: case CMD.FM6_LIST: case CMD.FM6_ERASE: { /* editor_fm6.c */
if (opt.noFm6 || !st.uiCaps) return null;
const nf = FM6.FACTORY_PK.length, fm6User = (k) => k < NB && st.bank[k] && st.bank[k].engine === FM6_E;
if (cmd === CMD.FM6_LIST) { /* the factory patches; no bank (1.0.3) */
if (a.length) return null;
b(nf); b(0);
for (let i = 0; i < nf; i++) { b(1); s(FM6.name(FM6.unpack(FM6.FACTORY_PK[i]))); }
} else if (cmd === CMD.FM6_ERASE) {
b(a[0] ?? 127); b(a.length !== 1 ? 1 : 3); /* (3: no bank) */
} else if (cmd === CMD.FM6_GET) {
let rc = a.length !== 2 || a[0] > 3 ? 1 : 0, pk = null;
if (!rc) {
if (a[0] === 0 && a[1] < NTRK) pk = st.tracks[a[1]].fm6;
else if (a[0] === 1) rc = 3;
else if (a[0] === 2 && a[1] < nf) pk = FM6.FACTORY_PK[a[1]];
else if (a[0] === 3 && a[1] < NB) { pk = fm6User(a[1]) ? st.bank[a[1]].fm6 : null; rc = pk ? 0 : 2; }
else rc = 1;
}
b(a[0] ?? 127); b(a[1] ?? 127); b(rc);
if (!rc) pk.forEach(b);
} else {
let rc = a.length !== 2 + 128 ? 1 : 0;
const pk = rc ? null : FM6.pack(FM6.unpack(a.slice(2))); /* (every value into its range) */
if (!rc && a[0] === 0 && a[1] < NTRK) { st.tracks[a[1]].fm6 = pk; fm6Adopt(st.tracks[a[1]]); }
else if (!rc && a[0] === 1) rc = 3;
else if (!rc && a[0] === 3 && fm6User(a[1])) st.bank[a[1]].fm6 = pk;
else rc = 1;
b(a[0] ?? 127); b(a[1] ?? 127); b(rc);
}
break;
}
case CMD.PRESET:
if (a.length < 2 || a[0] >= ENG.length) return null;
if (a[0] === 1) fm4Load(a[1]); /* a DIGITAL preset: its sound, as FM6 */
else {
if (a[0] !== st.engine) setEngine(a[0]);
applyPreset(a[1]);
}
b(st.engine); b(st.preset);
break;
case CMD.SONG: {
if (!a.length || a[0] > 3) return null;
let rc = 0;
if (a[0] === 1) {
const rows = Array.from({ length: a[1] || 0 }, (_, i) => ({ slot: a[2 + 2 * i], repeat: a[3 + 2 * i] }));
if (a.length < 2 || a[1] > 16 || a.length !== 2 + 2 * a[1] || rows.some((r) => r.slot > 3 || r.repeat < 1 || r.repeat > 16)) rc = 1;
else if (st.chainPlaying) rc = 2;
else st.songRows = rows;
} else if (a[0] === 2) {
if (st.chainPlaying) rc = 2;
else if (!st.songRows.length) rc = 1;
else {
const missing = st.songRows.find((r) => !st.slots[r.slot]);
if (missing) rc = 3 + missing.slot;
else { st.chainPlaying = true; st.chainRow = 0; st.chainRemaining = st.songRows[0].repeat; }
}
} else if (a[0] === 3) st.chainPlaying = false;
b(a[0]); b(rc); b(st.songRows.length); b(st.chainPlaying ? 1 : 0); b(st.chainRow); b(st.chainRemaining);
st.songRows.forEach((r) => { b(r.slot); b(r.repeat); });
break;
}
case CMD.PROJECT: {
if (a.length < 2) return null;
const k = a[1] & 3;
if (a[0] > 2) return null;
if (a[0] === 1) { st.chainPlaying = false; st.slots[k] = project(); }
else if (a[0] === 0 && st.slots[k]) {
st.chainPlaying = false; Object.assign(st, JSON.parse(JSON.stringify(st.slots[k])));
/* SAMPLE PERC tracks: DRUM's kit (project.c proj_perc). Removed factory presets keep their saved sound; only
the display index is normalized. */
st.tracks.forEach((t) => {
const pc = fromPerc({ engine: t.engine, p: t.p }, ENG.map((x) => x.name), P_E0);
if (pc) { t.engine = pc.engine; t.p = pc.p; t.preset = 0; }
if (t.preset >= ENG[t.engine].presets.length) t.preset = 0;
});
}
if (a[0] === 1) st.slotNames[k] = st.projName; /* ((Skiff W3) a save keeps the music's name; the music is the slot's) */
if (a[0] === 1 || (a[0] === 0 && st.slots[k])) { st.projCur = k; st.projName = st.slotNames[k]; st.projSig = JSON.stringify(project()); }
b(a[0]); b(k); b(st.slots[k] ? 1 : 0);
break;
}
case CMD.NAMES:
if (a.length < 1 || a[0] >= ENG.length) return null;
b(a[0]); b(ENG[a[0]].presets.length); ENG[a[0]].presets.forEach((p) => s(p.name));
ENG[a[0]].titles.forEach(s);
break;
/* user sample slots: the header is checked like the firmware's ed_smp_end() */
case CMD.SMP_BEGIN: case CMD.SMP_ERASE: {
if (a.length < 1 || a[0] >= 3) return null;
const u = st.smp[a[0]];
if (cmd === CMD.SMP_ERASE) u.flash.fill(0xFF); else u.flash.fill(0xFF, 0, 4096);
u.zones = 0; u.name = ""; u.len = 0; u.next = SMP.DATA_OFF;
b(a[0]); b(0);
break;
}
case CMD.SMP_WRITE: {
if (a.length < 5 || a[0] >= 3) return null;
const u = st.smp[a[0]], off = a[1] | (a[2] << 7) | (a[3] << 14), dat = unpack7(a.slice(4));
let rc = 0;
if (off < SMP.DATA_OFF || (off & 0xFF) || !dat.length || off + dat.length > SMP.SLOT_SIZE || dat.length > 256) rc = 1;
else {
if (!(off & 0xFFF)) u.flash.fill(0xFF, off, off + 4096);
u.flash.set(dat, off);
u.next = off + dat.length;
}
b(a[0]); b(off); b(off >> 7); b(off >> 14); b(rc);
break;
}
case CMD.SMP_END: {
if (a.length < 2 || a[0] >= 3) return null;
const u = st.smp[a[0]], hd = unpack7(a.slice(1)), dv = new DataView(hd.buffer);
let rc = 0;
if (hd.length < SMP.HDR_LEN || dv.getUint32(0, true) !== 0x504D5346 || dv.getUint16(4, true) !== 1) rc = 2;
else if (!hd[6] || hd[6] > 16) rc = 5;
else {
const len = dv.getUint32(16, true);
if (len > SMP.MAX_DATA) rc = 1;
else if (crc32(u.flash.subarray(SMP.DATA_OFF, SMP.DATA_OFF + len)) !== dv.getUint32(20, true)) rc = 3;
else {
u.flash.set(hd, 0);
u.zones = hd[6]; u.len = len;
u.name = String.fromCharCode(...hd.slice(8, 16)).replace(/\0.*$/, "");
}
}
b(a[0]); b(rc);
break;
}
case CMD.SMP_INFO:
b(3); b(SMP.SLOT_SIZE / 1024);
st.smp.forEach((u) => { b(u.zones); s(u.zones ? u.name : ""); b(u.zones ? Math.ceil(u.len / 1024) : 0); });
break;
default:
return null;
}
if ([CMD.UP_PUT, CMD.UP_STORE, CMD.UP_ERASE].includes(cmd) && out[1] === 0) st.bankSig++;
return frame(cmd, out);
}
/* a WebMIDI-like access object: one input and one output named "Felucca" */
const input = { id: "mock-in", name: "Felucca", type: "input", state: "connected", onmidimessage: null };
let busy = false;
const output = {
id: "mock-out", name: "Felucca", type: "output", state: "connected",
send(data) {
const f = unframe(data);
if (!f) { console.error("mock: refused a frame that is not F0 7D 46 4C ... F7", data); return; }
if (busy) { console.warn("mock: frame dropped (device holds only one frame)", data); return; }
busy = true;
watching(); /* a lapsed WATCH ends before this request counts */
st.lastReq = Date.now();
const flash = [CMD.UP_PUT, CMD.UP_STORE, CMD.UP_ERASE].includes(f.cmd) && !opt.legacy;
setTimeout(() => {
busy = false;
const r = handle(f.cmd, f.a);
if (r && input.onmidimessage) input.onmidimessage({ data: Uint8Array.from(r) });
const ra = r ? r.slice(5, -1) : [];
if (r && ((!syncCaps() && ((f.cmd === CMD.SET && f.a[0] === 1 && f.a[1] === G_ENGSEL) || f.cmd === CMD.PRESET))
|| (f.cmd === CMD.PROJECT && f.a[0] === 0 && ra[2]) || (f.cmd === CMD.UP_LOAD && !ra[1]))) reloadPush();
}, f.cmd === CMD.SMP_ERASE ? 900 : f.cmd === CMD.SMP_BEGIN ? 120 : flash ? 150 : f.cmd === CMD.SMP_WRITE ? 25 + Math.random() * 10 : 4 + Math.random() * 12);
},
};
/* WATCH ends by itself watchMs after the last request */
function watching() {
if (st.watch && Date.now() - st.lastReq > watchMs) st.watch = false;
return st.watch;
}
function push(cmd, args) {
if (!watching()) return false;
const fr = Uint8Array.from(frame(cmd, args));
setTimeout(() => { if (input.onmidimessage) input.onmidimessage({ data: fr }); }, 0);
return true;
}
/* INFO 53 01 caps (firmware after 1.0): no RELOAD echo of the editor's own PRESET / G_ENGSEL */
const syncCaps = () => (!opt.legacy && !opt.v3 && !opt.v5 && !opt.noFm6 && !opt.noSync && st.uiCaps ? 3 : 0);
const reloadPush = () => push(CMD.RELOAD, opt.legacy ? [st.engine, st.preset] : [st.engine, st.preset, st.sel]);
/* things done on the device itself */
const sim = {
knob(id = [9, 33, 35, P_E0 + 4][Math.floor(Math.random() * 4)], dv = Math.random() < 0.5 ? -4 : 4) {
const d = desc(0, id);
st.p[id] = clamp(st.p[id] + dv, d.min, d.max);
push(CMD.CHANGED, [...widOut(0, id), ...v14enc(st.p[id])]);
return { id, value: st.p[id] };
},
reload(pi = st.preset + 1) {
applyPreset(pi);
reloadPush();
return { engine: st.engine, preset: st.preset };
},
track(i = (st.sel + 1) % NTRK) { /* TRACKS page KNOB 1 */
st.sel = i;
reloadPush();
return i;
},
/* TRACKS page KNOB 2: the selected track's level; pushes CHANGED */
level(v) {
st.p[0] = v = clamp(v, 0, 127);
push(CMD.CHANGED, [0, 0, ...v14enc(v)]);
return v;
},
mute(on = !st.p[40]) { st.p[40] = on ? 1 : 0; push(CMD.CHANGED, [0, 40, ...v14enc(st.p[40])]); return st.p[40]; },
/* a parameter of track i changed on the device: CHANGED for the selected track, else TRACK_CHANGED (v4 watch) */
param(i, id, val) {
const t = st.tracks[i], d = id >= P_E0 ? ENG[t.engine].edit[id - P_E0] : TP[id];
t.p[id] = clamp(val, d.min, d.max);
if (i === st.sel) push(CMD.CHANGED, [...widOut(0, id), ...v14enc(t.p[id])]);
else if (st.v4) push(CMD.TRACK_CHANGED, [i | (id >> 7 & 1) << 6, id & 127, ...v14enc(t.p[id])]);
return t.p[id];
},
/* REC on TRACKS: arm / disarm live recording of a track (no push: the editor reads TRACK) */
arm(i = st.sel) { st.rec ^= 1 << i; return (st.rec >> i) & 1; },
step(i = Math.floor(Math.random() * 16)) {
const x = st.step[i];
if (x.n) x.flags ^= 1;
else Object.assign(x, { n: 1, notes: [60 + Math.floor(Math.random() * 12), 0, 0, 0], time: 0, flags: 0, vel: 96 });
push(CMD.STEP_CHANGED, opt.legacy ? [i] : [i, st.sel]);
return i;
},
};
if (opt.auto !== false) st.rec = 1 << 2; /* the browser mock: track 3 armed, to show it */
const timers = opt.auto === false ? [] : [
setInterval(() => sim.knob(), 3000),
setInterval(() => sim.step(), 11000),
setInterval(() => sim.reload(), 27000),
setInterval(() => sim.param((st.sel + 1) % NTRK, 39, Math.round(Math.random() * 80) - 40), 13000), /* pan of another track */
];
return {
state: st, sim,
tables: { TP, GP, ENG, PATTERNS, P_COUNT, G_COUNT, NSTEP, P_E0, G_ENGSEL, P_SLCR, NTRK,
FM6: { bank: 0, own: FM6_OWN, init: FM6.INIT_PK, factory: FM6.FACTORY_PK } }, /* test_web.mjs: == the firmware */
stop: () => timers.forEach(clearInterval),
access: { sysexEnabled: true, inputs: new Map([[input.id, input]]), outputs: new Map([[output.id, output]]), onstatechange: null },
};
}
/* Optional preferences: old firmware is never probed with unknown commands. */
async function readDevicePreferences(rq, info, names, previous = null) {
if (!info.uiCaps) return null;
const state = parse[CMD.UI_STATE](await rq(req.uiState()));
const palettes = previous ? previous.palettes : parse[CMD.UI_PALETTES](await rq(req.uiPalettes()));
let favorites = previous ? previous.favorites : [], slots = previous ? previous.slots : null;
if (state.caps & 8) {
if (!previous || state.bankSig !== previous.state.bankSig) slots = await bank.list(rq);
if (!previous || state.favoriteSig !== previous.state.favoriteSig || state.bankSig !== previous.state.bankSig) {
favorites = [];
for (let engine = 0; engine <= info.nengines; engine++) {
const total = engine === info.nengines ? slots.total : (names[engine] || []).length;
const flags = favorites[engine] = [];
for (let start = 0; start < total; start += 32) {
const count = Math.min(32, total - start);
const r = parse[CMD.FAV_GET](await rq(req.favGet(engine, start, count)));
if (r.rc || r.engine !== engine || r.start !== start || r.count !== count) throw new Error("Invalid favorites reply");
flags.push(...r.values);
}
}
}
}
return { state, palettes, favorites, slots };
}
/* an enum value or a preset named like another is an alias kept for stored numbers: the device loads the original,
the lists hide the alias (shown when set). The original: the first entry when it has that name (SAMPLE / GRAIN 1
and 4, once TRANH and PERC: PIANO 0), else the last with it (DRUM KIT 1..3, once HAND CYM H+CYM: 66 10 77 at 6 5 8;
EDITOR_PROTOCOL.md). -> the original's index */
function aliasOf(names, i) {
if (!names || names[i] == null) return i;
const k = names[0] === names[i] ? 0 : names.lastIndexOf(names[i]);
return k >= 0 ? k : i;
}
/* #48: note divisions (1/4, 8T, 2BAR, ...) are listed by length, longest first, as the device's knobs step them
(src/params.c enum_order); the values stay. Any other list: in value order. -> d's values in the order shown */
function divLength(n) {
const d = /^(\d+)\/(\d+)D$/.exec(n); /* ((1.3) DELAY TIME's dotted ones: half again) */
if (d) return 1.5 * +d[1] / +d[2];
const m = /^(\d+)\/(\d+)$/.exec(n) || /^(\d+)(T|BAR)$/.exec(n);
return !m ? null : m[2] === "BAR" ? +m[1] : m[2] === "T" ? 2 / 3 / +m[1] : +m[1] / +m[2];
}
function enumShown(d) {
const vals = [];
for (let v = d.min; v <= d.max; v++) vals.push(v);
const len = d.fmt === F.ENUM && d.names ? d.names.map(divLength) : [null];
return len.includes(null) ? vals : vals.sort((a, b) => len[b - d.min] - len[a - d.min] || a - b);
}
/* the order the device shows its engines in (src/engines.c ENGINE_ORDER): the lists here follow it, the protocol keeps
the engine numbers. engineOrder(names): the indices of names in that order, "-" (a reserved number) left out; a name
the list does not know (another firmware) follows in index order */
const ENGINE_ORDER = ["ANALOG", "FM6", "DIGITAL", "PHASE", "LOFI", "SAMPLE", "VOICE", "TRIO", "WHEEL", "GRAIN", "PHYS", "NOISE",
"SLICE", "DRUM", "DRUM-X"];
function engineOrder(names) {
const rank = (n) => { const k = ENGINE_ORDER.indexOf(n); return k < 0 ? ENGINE_ORDER.length : k; };
return (names || []).map((n, i) => i).filter((i) => names[i] !== "-")
.sort((a, b) => rank(names[a]) - rank(names[b]) || a - b);
}
function devicePresetRows(info, names, preferences) {
if (!preferences || !(preferences.state.caps & 8)) return [];
const rows = engineOrder(info.engines).filter((engine) => names[engine]).flatMap((engine) => names[engine]
.map((name, preset) => ({ engine, preset, name, user: false })).filter((row) => aliasOf(names[engine], row.preset) === row.preset));
for (const slot of preferences.slots.slots) if (slot.used)
rows.push({ engine: info.nengines, preset: slot.slot, name: slot.name, user: true });
return rows.map((row) => ({ ...row, favorite: !!(preferences.favorites[row.engine] || [])[row.preset] }))
.filter((row) => !preferences.state.filter || row.favorite);
}
/*PROTO-END*/
/* ===================================================================== UI === */
if (typeof document !== "undefined") (() => {
const $ = (id) => document.getElementById(id);
const el = (tag, attrs = {}, ...kids) => {
const e = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (k === "text") e.textContent = v;
else if (k === "ic") continue;
else if (k.startsWith("on")) e.addEventListener(k.slice(2), v);
else if (v !== false && v != null) e.setAttribute(k, v === true ? "" : v);
}
for (const k of kids) e.append(k);
if (attrs.ic) e.prepend(icon(attrs.ic));
return e;
};
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
/* ---------------------------------------------------------------- icons --- */
/* Fukiai glyphs by their names in hugelton-plugin-rules lib/include/hugelton/Glyphs.h */
const GLYPH = {
port_usb_c: 0xEA3F, symbol_audio: 0xEA40, symbol_download: 0xEAD4, symbol_upload: 0xEAD5,
symbol_folder: 0xEAB8, symbol_folder_open: 0xEAB9, port_disk: 0xEAB3, symbol_trash: 0xEAC1,
control_arrow_loop: 0xEAD6, note_eight: 0xEAEF, symbol_waves: 0xEAE6, function_env_adsr_exp: 0xEA12,
ui_knob: 0xEA70, symbol_keyboard: 0xEABC, symbol_effector: 0xEAB7, symbol_echo: 0xEAB5, symbol_spring: 0xEAD1,
symbol_tuning: 0xEAA7, control_arrow_up_down: 0xEACF, symbol_grid: 0xEABA, symbol_cog: 0xEA46,
function_filter_hpf_peak: 0xEA9E, ui_slider_vertical: 0xEA73, symbol_books: 0xEADC, control_rec_f: 0xEA09, control_stop_f: 0xEA0F, control_play_f: 0xEA07,
symbol_pan: 0xEA53, control_speaker_mute: 0xEAEB,
waveform_sine: 0xEA85, waveform_triangle_ac: 0xEA89, waveform_sawtooth_ac: 0xEA81, waveform_square: 0xEA87,
waveform_pulse_quarter: 0xEA7F, waveform_pulse_eighth: 0xEA7B, waveform_noise_step: 0xEA79,
waveform_noise_white: 0xEA7A, waveform_harmonic: 0xEAC5,
};
/* section headings (LAYOUT titles) and page titles */
const HEAD_IC = { ENV: "function_env_adsr_exp", LFO: "waveform_sine", MOD: "symbol_waves", EDIT: "ui_knob", VOICE: "symbol_keyboard",
FX: "symbol_effector", SCALE: "symbol_tuning", ARP: "control_arrow_up_down", "SEQ PATTERN": "symbol_grid",
GLOBAL: "symbol_cog", INSTRUMENT: "symbol_keyboard" };
/* ((1.3.1) Fukiai's filter names are mirrored: its "hpf_peak" glyph draws a low-pass with its resonance peak) */
const PAGE_IC = { FLT: "function_filter_hpf_peak", FILT: "function_filter_hpf_peak", DLY: "symbol_echo", REVERB: "symbol_spring", CHORUS: "symbol_waves",
SLICER: "symbol_grid", CHORD: "symbol_keyboard" };
/* WAVE / WAVE2 choices; phase-distortion shapes without a close glyph (SPLS, RSAW, RTRI, RTRP) get none */
const WAVE_IC = { SIN: "waveform_sine", TRI: "waveform_triangle_ac", SAW: "waveform_sawtooth_ac", SQR: "waveform_square",
PLS: "waveform_pulse_quarter", PWM: "waveform_pulse_eighth", "S&H": "waveform_noise_step", NOIS: "waveform_noise_white",
DSIN: "waveform_harmonic" };
/* options can hold an icon only where the browser draws the picker itself; a native menu would show a box */
const RICH_SELECT = typeof CSS !== "undefined" && CSS.supports && CSS.supports("appearance", "base-select");
function icon(name) { return el("span", { class: "ic", "aria-hidden": "true", text: String.fromCharCode(GLYPH[name]) }); }
function setLabel(e, txt) { e.replaceChildren(...(e.dataset.ic ? [icon(e.dataset.ic)] : []), txt); }
/* icons stay hidden (html:not(.fk)) until the face has loaded; on failure, or from file://, words only */
(async () => {
try {
const probe = "1em Fukiai", ch = String.fromCharCode(GLYPH.waveform_sine);
const faces = await document.fonts.load(probe, ch);
if (faces.length && faces.every((f) => f.status === "loaded") && document.fonts.check(probe, ch)) document.documentElement.classList.add("fk");
} catch (e) { /* no icons */ }
})();
const TEXT = {
ja: {
tabFm6: "6-OP FM", fm6Help: "FM6 エンジンの音色(6 オペレーター)をまるごと編集します。本体のノブはこの音色の上にかかるマクロです。SysEx を読み込み、音色を選んで編集し、トラックへ送るとすぐ鳴ります。トラックの音色はひとつで、読み込んだものがそのトラックの音色になります(SLOT は OWN)。",
fm6Source: "音色の出し入れ", fm6ReadBtn: "トラックから読む", fm6SendBtn: "トラックへ送る", fm6Live: "編集しながら送る",
fm6Import: "SysEx を読み込む", fm6Export: "SysEx に書き出し",
fm6Init: "初期音色", fm6Voice: "ボイス", fm6Ops: "オペレーター", fm6Carriers: "キャリア", fm6Feedback: "フィードバック",
fm6PitchEg: "ピッチ EG", fm6Freq: "周波数",
fm6Legend: "R1〜R4 / L1〜L4: EG のレートとレベル、BP LD RD LC RC: キーボードレベルスケーリング、RS: レートスケーリング、AMS: LFO 音量変調、KVS: ベロシティ、OL: 出力レベル、MODE: 比率 / 固定、FC FF: 周波数(粗・細)、DET: デチューン(7 が中央)。● はキャリア。",
fm6Pick: "読み込んだファイルの音色(押すと編集へ):", fm6Picked: "編集中:", fm6Sent: "トラックへ送りました:", fm6Read: "トラックから読みました",
fm6Loaded: "読み込みました", fm6BadSum: "チェックサム不一致あり",
fm6Keep: "残すには、トラックへ送ってから本体でユーザープリセット(SAVE)かプロジェクトに保存してください。",
fm6Short: "途中で切れたデータあり", fm6Skipped: "音色以外の {x} 件は無視",
fm6NoVoice: "6 オペレーター FM の音色が見つかりません(32 音色バンクか 1 音色の SysEx が必要です)",
fm6NotSysex: "SysEx ファイルではありません(6 オペレーター FM の 32 音色バンクか 1 音色の SysEx が必要です)",
fm6Is4op: "4 オペレーター FM の音色データです。FM6 は 6 オペレーターの音色だけ読み込めます",
fm6OtherBlocks: "6 オペレーターのファイル形式ですが、音色ではないデータ(パフォーマンスや補助データなど)だけでした",
fm6OtherMaker: "別のメーカーの SysEx です", fm6Universal: "音色ではない汎用 SysEx です",
fm6Factories: "ファクトリー音色",
fm6NeedDevice: "FM-1 を接続すると 6-OP FM の音色を編集してトラックへ送れます。",
fm6NoFw: "このファームウェアには 6-OP FM(FM6)がありません。ファームウェアを更新すると使えます。",
motion: "オートメーション", motionOn: "再生", motionClear: "オートメーションを消去", motionConfirm: "選択トラックのオートメーションを消しますか?", chance: "確率 %", ratchet: "ラチェット", flam: "フラム", cond: "条件", nudge: "ナッジ", motionStep: "ステップ", motionParam: "パラメーター", motionValue: "値", motionKind: "種類", motionLock: "ロック", motionAuto: "オート", motionRemoveConfirm: "%s を削除しますか?",
backupTitle: "全体バックアップ", backupExport: "バックアップ保存", backupImport: "バックアップ復元", backupHelp: "現在の曲・A〜D・音色バンク・ユーザーサンプル・設定を、このパソコンへ保存。", backupOld: "全体バックアップには対応版への更新が必要です。", backupConfirm: "全体バックアップを復元しますか? 現在の曲、保存データとサンプルを置き換えます。USBを抜かないでください。", backupWorking: "バックアップ処理中 ", backupDone: "バックアップを保存しました", backupRestored: "全体バックアップを復元しました",
deviceDisplay: "本体の画面",
deviceDisplayHelp: "FM-1 の画面に反映し、保存します。再生中の変更は停止後に保存されます。",
devicePresets: "本体のプリセット",
deviceFavHelp: "お気に入りと表示フィルターは FM-1 と同期します。パソコンのライブラリの音色は、本体のユーザースロットに保存してから登録してください。",
deviceList: "表示",
deviceAll: "すべてのプリセット",
deviceFavorites: "お気に入りのみ",
deviceEmpty: "お気に入りはまだありません。「すべてのプリセット」から追加してください。",
dxKitHelp: "DRUM-X のキット: すべての DRUM-X トラックで共通の 8 音で、プロジェクトと一緒に保存されます。EDIT の MORPH で A から B へ移ります。",
deviceTheme: "テーマ", deviceMenu: "本体のメニュー", deviceMenuHelp: "本体の MENU の設定です。変えるとすぐ本体に反映され、本体に保存されます。",
deviceFont: "フォント",
deviceMonitor: "MIDI モニター",
deviceRegular: "標準",
deviceBold: "太字",
deviceOff: "オフ",
deviceEvents: "イベント",
deviceNotes: "保持中の音・和音",
deviceStar: "お気に入りに追加",
deviceUnstar: "お気に入りから削除",
deviceUnsaved: "反映されましたが、本体に保存できませんでした。もう一度お試しください。",
deviceRejected: "本体がこの設定を受け付けませんでした。",
devicePending: "反映しました。再生を停止すると保存されます。",
other: "English", connect: "接続", disconnect: "切断", mock: "モック(実機なし)",
sound: "音色", engine: "エンジン", presets: "プリセット", initSound: "音色を初期化",
track: "トラック",
saveFile: "ファイルに保存", loadFile: "ファイルを読み込む", projects: "プロジェクト",
load: "読込", save: "保存", used: "使用中", empty: "空", unknown: "—",
steps: "ステップ", reload: "再読み込み", clearSeq: "シーケンスを消去",
notesHelp: "ノートは C4 E4 G4 のように入力(最大 4 音、C4 = 60)。ヒットは DRUM のレーン名(KICK >SNARE HATCL、> はアクセント)。",
notes: "ノート", hits: "ヒット", time: "タイム", acc: "アクセント", slide: "スライド", vel: "ベロシティ",
foot: "Chrome か Edge で使えます。", iconsCredit: "アイコン: Fukiai(MIT)Hügelton Instruments",
nomidi: "このブラウザでは使えません。Chrome か Edge で開いてください。",
denied: "MIDI(SysEx)の使用が許可されませんでした。",
nodevice: "FM-1 が見つかりません。USB で接続して、もう一度押してください。",
connecting: "接続中", reading: "読み込み中 ", steploading: "ステップを読み込み中 ",
ready: "接続しました", disconnected: "切断されました", lost: "FM-1 が外されました",
noreply: "応答がありません", error: "エラー: ", busy: "処理中",
applying: "書き込み中 ", applied: "読み込みました", badfile: "ファイルを読み込めません: ",
savedSlot: "保存しました: スロット ", loadedSlot: "読み込みました: スロット ", emptySlot: "空のスロットです: ",
renamedSlot: "名前を変更しました: スロット ", projName: "名前(保存と名前変更に使います。12 文字まで)",
noName: "(名前なし)", projNow: "現在", projChanged: "保存後に変更あり",
projRefused: "本体が受け付けませんでした(空のスロット、またはパターンがいっぱい)", projFailed: "本体での保存に失敗しました",
play: "再生", stop: "停止", playTitle: "再生(Shift+クリック: 頭から)", playing: "再生中", stopped: "停止中", countIn: "カウントイン",
sgTab: "ソング", sgHelp: "各トラックはリスト(A〜P)のエントリーを演奏し、各エントリーはプールのパターンを指します(本体の SEQ › SONG)。シーンとミュートは PERFORM と同じです。エントリーをクリックで編集、ダブルクリックで再生。停止中はすぐに、再生中は LAUNCH のタイミングで切り替わります。",
sgLists: "リスト", sgSong: "SONG(各トラックがリストを順に進む)", sgLaunch: "LAUNCH", sgCancel: "予約を取り消す",
sgPattern: "パターン", sgSet: "設定", sgCopy: "新しいパターンにコピー", sgPlay: "再生", sgClear: "クリア", sgEmptyEntry: "空",
sgScenes: "シーン", sgStore: "保存(次にクリックしたシーンに今のトラックを保存)",
sgPool: "パターンプール", sgPoolHelp: "全プロジェクト共通の 64 パターン(本体の SAVE › PATTERNS)。どこからも使われていないパターンだけ、停止中にクリアできます。",
sgUsedBy: "{n} か所で使用", sgUnused: "未使用(クリア可)", sgEmptyPat: "空",
sgConfirmEntry: "エントリー {e} をクリアしますか? {what} 元に戻せません。", sgGoesToo: "パターン {n} も消えます。", sgStays: "パターン {n} は残ります(ほかで使用中)。",
sgConfirmPat: "パターン {n} をクリアしますか? どこからも使われていません。元に戻せません。", sgConfirmScene: "シーン {n} に上書き保存しますか?",
sgEmpty: "空です", sgAutoFull: "完了(オートメーションなし: AUTOMATION FULL)", sgStopClear: "停止してからクリアしてください",
sgFull: "パターンがいっぱいです: プールで未使用のものをクリアしてください", sgFailed: "本体で失敗しました", sgNothing: "クリアするものがありません", sgInUse: "使用中です",
sgNoFw: "このファームウェアにはソングのコマンドがありません。Skiff を更新してください。",
confirmSave: "スロット {n} に上書き保存しますか?", confirmLoad: "スロット {n} を読み込みますか? すべてのトラックの音色とシーケンスが置き換わります(元に戻せません)。",
confirmLoadFile: "「{name}」を読み込みますか? 今の音色は置き換わります(本体の SAVE 長押しで元に戻せます)。",
confirmLoadFileSteps: "「{name}」を読み込みますか? 今の音色とシーケンス(64 ステップ)が置き換わります。",
lightRefused: "このトラックでは使えないエンジンです(T5、T6 は GRAIN と PHYS を使えません): ",
loadRefused: "本体が読み込みを断りました: スロット ",
confirmClear: "シーケンスを全部消しますか?", confirmInit: "音色を初期化しますか? シーケンスはそのままです(本体の SAVE 長押しで元に戻せます)。",
samples: "サンプル", smpHelp: "ファイルを選択、または入力から録音。波形の両端でトリム、ホイールで拡大。1枠に16音、合計約7秒。",
zones: "ゾーン", smpName: "名前", chooseFiles: "ファイルを選ぶ", upload: "書き込む", erase: "消去", clearList: "リストを消す",
file: "ファイル", root: "ルート", keys: "鍵盤", length: "長さ", remove: "外す",
record: "録音", stopRec: "停止", recInput: "入力", recDenied: "録音できません", recFull: "スロットがいっぱいです", recSilent: "無音でした。入力を確かめてください",
preview: "試聴", autoTrim: "自動トリム", trim: "切り取り",
smpTooBig: "大きすぎます", smpDecodeFail: "読み込めません: ", smpUploading: "書き込み中 USR", smpDone: "書き込みました USR",
smpFail: "サンプルの書き込みに失敗しました: ", smpErased: "消去しました USR",
confirmErase: "USR{n} を消去しますか?", confirmUpload: "USR{n} に書き込みますか? 今の内容は消えます。",
layout: "(ファームウェアのパラメーター数が想定と違うため、簡易表示にしています)",
ctlHelp: "スライダーはクリックしてからホイールか矢印キーで微調整(Shift で 10 ずつ)、ダブルクリックで初期値。",
live: "● リアルタイム", polling: "○ ポーリング(古いファームウェア)",
library: "ライブラリ", libSearch: "名前・タグで検索", allEngines: "全エンジン", allTags: "全タグ",
sortModified: "更新順", sortCreated: "作成順", sortName: "名前順", sortEngine: "エンジン順",
name: "名前", tagsCol: "タグ", date: "更新",
audition: "試聴", toSlot: "本体スロットへ", rename: "名前変更", tags: "タグ", duplicate: "複製", delete: "削除",
exportPatch: "書き出し", saveToLib: "今の音色をライブラリへ", import: "読み込み", exportLib: "ライブラリを書き出し",
factoryToLib: "ライブラリへコピー", libEmpty: "ライブラリは空です。「今の音色をライブラリへ」やファクトリープリセットのコピー、本体スロットからの取り込み、ファイルの読み込みで追加できます。",
noMatch: "該当なし", noLibDB: "(ブラウザに保存できません。再読み込みで消えます)",
bank: "本体のユーザープリセット", bankLoad: "読込", bankStore: "今の音色を保存", bankGet: "ライブラリへ",
exportBank: "バンクを書き出し", dndHelp: "ライブラリとスロットの間はドラッグでもコピーできます。",
confirmOverwrite: "スロット {n}({name})を上書きしますか?", confirmEraseSlot: "スロット {n}({name})を消去しますか?",
confirmDelete: "「{name}」をライブラリから削除しますか?",
promptName: "名前(本体では英数字 12 文字まで)", promptTags: "タグ(カンマ区切り)",
promptNameAuto: "名前(英数字 12 文字まで。空なら本体が自動で付けます)",
auditioning: "試聴の準備中 ", auditioned: "試聴中(音色だけ。シーケンスはそのまま。本体の SAVE 長押しで元の音色に戻せます): ",
savedLib: "ライブラリに保存しました: ", copiedLib: "ライブラリにコピーしました: ", imported: "読み込みました: ",
skippedN: " 件(読めないもの {n} 件)", patchesN: " 件",
putDone: "本体に書き込みました: スロット ", storedSlot: "本体に保存しました: スロット ", erasedSlot: "消去しました: スロット ",
loadedUser: "音色を読み込みました(シーケンスはそのまま。SAVE 長押しで元に戻せます): ", reloaded: "本体で音色が変わったので読み直しました", readingBank: "スロットを読み込み中",
badEngine: "このファームウェアにないエンジンです: ", flashFail: "書き込みに失敗しました(rc {rc})",
installer: "インストーラー",
tabSeq: "シーケンサー", tabTracks: "ミキサー", tabSettings: "設定", /* ((Skiff W5) the device's MIXER) */
needDevice: "FM-1 を接続すると編集できます。", smpNone: "このファームウェアにはユーザーサンプルのスロットがありません。",
bankConnect: "FM-1 を接続すると本体のユーザープリセットも扱えます。", bankNone: "このファームウェアにはユーザープリセットがありません。",
mixer: "ミキサー", mixHelp: "本体の MIXER ページと同じ全トラック。フェーダーはレベル。パンはどのトラックも選択を変えずに書き込みます(0.8 のファームウェアでは一瞬そのトラックを選びます)。REC は本体での録音待機の表示です。",
level: "レベル", pan: "パン", rev: "REV", mute: "ミュート", rec: "REC", selectTrack: "選択", selectedTrack: "選択中",
projHelp: "プロジェクト(A〜D)は、全トラックの音色、各トラックのリスト(どのパターンを何回)、シーン、DRUM-X キット、グローバル設定を保存します。パターンそのものは全プロジェクト共通の 64 個のプール(本体の SAVE › PATTERNS)にあり、プロジェクトには入りません。パターンを変えると、それを使うすべてのプロジェクトで変わります。",
slot: "スロット",
system: "システム", firmware: "ファームウェア", sync: "同期", tracksN: "トラック", stepsN: "ステップ数", enginesL: "エンジン",
smpSlots: "サンプルスロット", userBank: "ユーザープリセット", none: "なし",
},
en: {
tabFm6: "6-OP FM", fm6Help: "Edit the whole patch of the FM6 engine (six operators). The device's knobs are macros on top of it. Import a SysEx file, pick a voice, edit it and send it to a track: it plays at once. A track has one patch: whatever you load becomes it (SLOT shows OWN).",
fm6Source: "Patches in and out", fm6ReadBtn: "Read from track", fm6SendBtn: "Send to track", fm6Live: "Send while editing",
fm6Import: "Import SysEx", fm6Export: "Export SysEx",
fm6Init: "Init voice", fm6Voice: "Voice", fm6Ops: "Operators", fm6Carriers: "carriers", fm6Feedback: "feedback",
fm6PitchEg: "Pitch EG", fm6Freq: "Frequency",
fm6Legend: "R1..R4 / L1..L4: EG rates and levels; BP LD RD LC RC: keyboard level scaling; RS: rate scaling; AMS: LFO amplitude modulation; KVS: velocity; OL: output level; MODE: ratio / fixed; FC FF: coarse / fine frequency; DET: detune (7 = centre). ● = carrier.",
fm6Pick: "Voices of the imported file (click to edit):", fm6Picked: "Editing:", fm6Sent: "Sent to track", fm6Read: "Read from track",
fm6Loaded: "Loaded", fm6BadSum: "a checksum did not match",
fm6Keep: "To keep a voice, send it to a track, then save a user preset (SAVE) or a project on the device.",
fm6Short: "some data was cut short", fm6Skipped: "{x} non-voice blocks skipped",
fm6NoVoice: "No 6-operator FM voices found (expects a 32-voice bank or single-voice SysEx)",
fm6NotSysex: "Not a SysEx file (expects a 6-operator FM 32-voice bank or single-voice SysEx)",
fm6Is4op: "These are 4-operator FM voices: FM6 reads 6-operator voices only",
fm6OtherBlocks: "6-operator file format, but no voices (performance or supplement data only)",
fm6OtherMaker: "SysEx from another manufacturer", fm6Universal: "Universal SysEx, not voice data",
fm6Factories: "Factory patch",
fm6NeedDevice: "Connect the FM-1 to edit 6-OP FM voices and send them to a track.",
fm6NoFw: "This firmware has no 6-OP FM (FM6). Update the firmware to use it.",
motion: "Automation", motionOn: "Play automation", motionClear: "Clear automation", motionConfirm: "Clear this track's automation?", chance: "Chance %", ratchet: "Ratchet", flam: "Flam", cond: "Cond", nudge: "Nudge", motionStep: "Step", motionParam: "Parameter", motionValue: "Value", motionKind: "Kind", motionLock: "LOCK", motionAuto: "AUTO", motionRemoveConfirm: "Remove %s?",
backupTitle: "Complete backup", backupExport: "Save backup", backupImport: "Restore backup", backupHelp: "Save the current music, A–D, sound banks, user samples and settings to this computer.", backupOld: "Complete backups need firmware with archive support.", backupConfirm: "Restore this complete backup? Current music, saved data and samples will be replaced. Keep USB connected.", backupWorking: "Backing up / restoring ", backupDone: "Backup saved", backupRestored: "Complete backup restored",
deviceDisplay: "Device display",
deviceDisplayHelp: "Changes apply to the FM-1 screen and save. Changes made while playing save after STOP.",
devicePresets: "Device presets",
deviceFavHelp: "Stars and the favorites filter sync with the FM-1. Save computer-library sounds to a device user slot before starring them.",
deviceList: "Show",
deviceAll: "All presets",
deviceFavorites: "Favorites only",
deviceEmpty: "No favorites yet. Choose All presets to add some.",
dxKitHelp: "The DRUM-X kit: 8 sounds shared by every DRUM-X track, kept with the project. EDIT's MORPH moves each from A to B.",
deviceTheme: "Theme", deviceMenu: "Device menu", deviceMenuHelp: "The device's MENU settings. A change applies on the device at once and is kept there.",
deviceFont: "Font",
deviceMonitor: "MIDI monitor",
deviceRegular: "Regular",
deviceBold: "Bold",
deviceOff: "Off",
deviceEvents: "Events",
deviceNotes: "Held notes / chords",
deviceStar: "Add favorite",
deviceUnstar: "Remove favorite",
deviceUnsaved: "Applied, but could not save on the device. Try again.",
deviceRejected: "The device rejected that setting.",
devicePending: "Applied. Settings will save when playback stops.",
other: "日本語", connect: "Connect", disconnect: "Disconnect", mock: "Mock device (no hardware)",
sound: "Sound", engine: "Engine", presets: "Presets", initSound: "Init sound",
track: "Track",
saveFile: "Save to file", loadFile: "Load file", projects: "Projects",
load: "Load", save: "Save", used: "used", empty: "empty", unknown: "—",
steps: "Steps", reload: "Reload", clearSeq: "Clear sequence",
notesHelp: "Enter notes like C4 E4 G4 (up to 4, C4 = 60). Hits are DRUM lanes: KICK >SNARE HATCL (> = accent).",
notes: "Notes", hits: "Hits", time: "Time", acc: "Accent", slide: "Slide", vel: "Velocity",
foot: "Works in Chrome or Edge.", iconsCredit: "Icons: Fukiai (MIT), Hügelton Instruments",
nomidi: "This browser cannot do it. Open the page in Chrome or Edge.",
denied: "MIDI (SysEx) access was not allowed.",
nodevice: "FM-1 not found. Connect it by USB and press Connect again.",
connecting: "Connecting", reading: "Reading ", steploading: "Reading steps ",
ready: "Connected", disconnected: "Disconnected", lost: "The FM-1 was unplugged",
noreply: "No reply from the device", error: "Error: ", busy: "Busy",
applying: "Writing ", applied: "Loaded", badfile: "Cannot read the file: ",
savedSlot: "Saved to slot ", loadedSlot: "Loaded slot ", emptySlot: "Empty slot: ",
renamedSlot: "Renamed slot ", projName: "Name (Save and Rename use it; up to 12 letters)",
noName: "(no name)", projNow: "Now", projChanged: "changed since saved",
projRefused: "The device refused (an empty slot, or the patterns are full)", projFailed: "Saving failed on the device",
play: "Play", stop: "Stop", playTitle: "Play (Shift+click: from the top)", playing: "Playing", stopped: "Stopped", countIn: "Count-in",
sgTab: "Song", sgHelp: "Each track plays the entries of its list (A to P), each naming a pattern of the pool, as on SEQ › SONG; the scenes and mutes are PERFORM's. Click an entry to edit it, double-click to play it. Stopped, a change is at once; playing, at the LAUNCH point.",
sgLists: "Lists", sgSong: "SONG (each track moves through its list)", sgLaunch: "LAUNCH", sgCancel: "Cancel staged",
sgPattern: "Pattern", sgSet: "Set", sgCopy: "Copy to a new pattern", sgPlay: "Play", sgClear: "Clear", sgEmptyEntry: "empty",
sgScenes: "Scenes", sgStore: "Store (the next scene clicked keeps the tracks as they are)",
sgPool: "Pattern pool", sgPoolHelp: "The 64 patterns every project shares (SAVE › PATTERNS). Only a pattern nothing uses can be cleared, while stopped.",
sgUsedBy: "used by {n}", sgUnused: "unused: can be cleared", sgEmptyPat: "empty",
sgConfirmEntry: "Clear entry {e}? {what} It can't be undone.", sgGoesToo: "Its pattern {n} is erased too.", sgStays: "Pattern {n} stays: something else uses it.",
sgConfirmPat: "Clear pattern {n}? Nothing uses it. It can't be undone.", sgConfirmScene: "Store over scene {n}?",
sgEmpty: "Empty", sgAutoFull: "Done, without its automation (AUTOMATION FULL)", sgStopClear: "Stop to clear",
sgFull: "Patterns full: clear unused ones in the pool", sgFailed: "Failed on the device", sgNothing: "Nothing to clear", sgInUse: "In use",
sgNoFw: "This firmware has no song commands: update Skiff.",
confirmSave: "Overwrite slot {n}?", confirmLoad: "Load slot {n}? The sounds and sequences of every track are replaced (no undo).",
confirmLoadFile: "Load \"{name}\"? It replaces the current sound (hold SAVE on the device to undo).",
confirmLoadFileSteps: "Load \"{name}\"? It replaces the current sound and the sequence (64 steps).",
lightRefused: "This track can't play that engine (T5 and T6 can't play GRAIN or PHYS): ",
loadRefused: "The device refused to load slot ",
confirmClear: "Clear the whole sequence?", confirmInit: "Reset the sound to the engine defaults? The sequence stays (hold SAVE on the device to undo).",
samples: "Samples", smpHelp: "Choose files or record an input. Drag waveform ends to trim; wheel to zoom. Up to 16 sounds and about 7 s per slot.",
zones: "zones", smpName: "Name", chooseFiles: "Choose files", upload: "Upload", erase: "Erase", clearList: "Clear list",
file: "File", root: "Root", keys: "Keys", length: "Length", remove: "Remove",
record: "Record", stopRec: "Stop", recInput: "Input", recDenied: "Cannot record", recFull: "The slot is full", recSilent: "Silence: check the input",
preview: "Play", autoTrim: "Auto trim", trim: "Trim",
smpTooBig: "too large", smpDecodeFail: "Cannot read: ", smpUploading: "Uploading USR", smpDone: "Uploaded USR",
smpFail: "Sample upload failed: ", smpErased: "Erased USR",
confirmErase: "Erase USR{n}?", confirmUpload: "Write to USR{n}? Its current contents will be replaced.",
layout: "(The firmware has a different parameter count; showing a plain list.)",
ctlHelp: "Sliders: click, then fine-tune with the wheel or arrow keys (Shift: steps of 10); double-click resets.",
live: "● Live", polling: "○ Polling (older firmware)",
library: "Library", libSearch: "Search name or tag", allEngines: "All engines", allTags: "All tags",
sortModified: "Recently changed", sortCreated: "Recently added", sortName: "Name", sortEngine: "Engine",
name: "Name", tagsCol: "Tags", date: "Changed",
audition: "Audition", toSlot: "To device slot", rename: "Rename", tags: "Tags", duplicate: "Duplicate", delete: "Delete",
exportPatch: "Export", saveToLib: "Save current sound", import: "Import", exportLib: "Export library",
factoryToLib: "Copy to library", libEmpty: "The library is empty. Add sounds with \"Save current sound\", by copying a factory preset or a device slot, or by importing a file.",
noMatch: "No match", noLibDB: "(this browser cannot store it: it is gone after a reload)",
bank: "User presets on the device", bankLoad: "Load", bankStore: "Store current sound", bankGet: "To library",
exportBank: "Export bank", dndHelp: "You can also drag between the library and the slots.",
confirmOverwrite: "Overwrite slot {n} ({name})?", confirmEraseSlot: "Erase slot {n} ({name})?",
confirmDelete: "Delete \"{name}\" from the library?",
promptName: "Name (the device keeps 12 ASCII characters)", promptTags: "Tags (comma separated)",
promptNameAuto: "Name (12 ASCII characters; empty: the device names it)",
auditioning: "Preparing audition ", auditioned: "Auditioning (the sound only, the sequence stays; hold SAVE on the device to undo): ",
savedLib: "Saved to the library: ", copiedLib: "Copied to the library: ", imported: "Imported: ",
skippedN: " ({n} unreadable)", patchesN: " patches",
putDone: "Written to the device: slot ", storedSlot: "Stored on the device: slot ", erasedSlot: "Erased slot ",
loadedUser: "Sound loaded (the sequence stays; hold SAVE to undo): ", reloaded: "The sound changed on the device: read again", readingBank: "Reading the slots",
badEngine: "This firmware has no such engine: ", flashFail: "Write failed (rc {rc})",
installer: "Installer",
tabSeq: "Sequencer", tabTracks: "Mixer", tabSettings: "Settings", /* ((Skiff W5) the device's MIXER) */
needDevice: "Connect the FM-1 to edit.", smpNone: "This firmware has no user sample slots.",
bankConnect: "Connect the FM-1 to see its user presets too.", bankNone: "This firmware has no user presets.",
mixer: "Mixer", mixHelp: "Every track of the device's MIXER page. The fader is the level. Pan is written to any track without changing the selection (firmware 0.8: by selecting it for a moment). REC shows a track armed for live recording on the device.",
level: "Level", pan: "Pan", rev: "REV", mute: "Mute", rec: "REC", selectTrack: "Select", selectedTrack: "Selected",
projHelp: "A project (A to D) keeps every track's sound, each track's list (which patterns it plays, how many times), the scenes, the DRUM-X kit and the global settings. The patterns themselves live in one pool of 64 that every project shares (SAVE › PATTERNS on the device): a project doesn't hold them, and changing a pattern changes it in every project that uses it.",
slot: "Slot",
system: "System", firmware: "Firmware", sync: "Sync", tracksN: "Tracks", stepsN: "Steps", enginesL: "Engines",
smpSlots: "Sample slots", userBank: "User presets", none: "none",
},
};
let lang = (navigator.language || "en").toLowerCase().startsWith("ja") ? "ja" : "en";
const t = (k) => TEXT[lang][k] ?? k;
let lastKey = null, lastArg = "";
function sayK(k, arg = "") { lastKey = k; lastArg = arg; $("status").textContent = t(k) + arg; }
function applyLang() {
document.documentElement.lang = lang;
document.querySelectorAll("[data-t]").forEach((e) => setLabel(e, t(e.dataset.t)));
$("lang").textContent = t("other");
setLabel($("connect"), t(dev ? "disconnect" : "connect"));
if (lastKey) $("status").textContent = t(lastKey) + lastArg;
$("libq").placeholder = t("libSearch");
renderLive();
renderLib();
renderBank();
renderPreferences(true);
renderPanels();
if (dev) { renderSlots(); renderStepHead(); renderSamples(); renderTrackbar(); renderMixer(); renderSysinfo(); renderFm6(); renderSong(); }
}
$("lang").addEventListener("click", () => { lang = lang === "ja" ? "en" : "ja"; applyLang(); });
/* ---------------------------------------------------------------- tabs --- */
/* one panel at a time; the last one is remembered (localStorage) and in the URL hash (#sound ...) */
const TABS = ["sound", "fm6", "sequencer", "song", "tracks", "library", "samples", "projects", "settings"];
const TAB_KEY = "felucca-editor-tab";
const TRACK_TABS = new Set(["sound", "sequencer", "tracks"]);
let tab = (() => {
const h = location.hash.slice(1);
if (TABS.includes(h)) return h;
try { const v = localStorage.getItem(TAB_KEY); if (TABS.includes(v)) return v; } catch (e) { /* no storage */ }
return "sound";
})();
const hasTracks = () => !!dev && !!dev.info && !!dev.info.ntrk;
function showTab(name) {
if (!TABS.includes(name)) name = "sound";
const prev = tab;
tab = name;
try { localStorage.setItem(TAB_KEY, name); } catch (e) { /* no storage */ }
if (location.hash !== "#" + name) history.replaceState(null, "", location.pathname + location.search + "#" + name);
if (prev === "samples" && name !== "samples") samplesLeave(); /* no hidden recording or preview */
renderPanels();
if (name === "tracks" && prev !== "tracks" && hasTracks() && dev.dump) op(readMixer);
if (name === "sequencer" && prev !== "sequencer" && dev && dev.dump && dev.stepsStale) op(() => loadSteps()); /* ((Skiff W7)) */
if (name === "settings" && prev !== "settings" && dev && dev.dump && dev.info.menuCount) op(() => readMenu()); /* ((Skiff W3)) */
if (name === "sound" && prev !== "sound" && kitShown()) op(() => readKit());
if (name === "projects" && prev !== "projects" && dev && dev.dump && dev.info.skiff & 2) op(() => readProj()); /* ((Skiff W3)) */
if (name === "song" && prev !== "song" && dev && dev.dump && dev.info.skiff & 28) op(() => readSong()); /* ((Skiff W3) the kit as the device has it) */
if (name === "fm6" && prev !== "fm6" && dev && dev.dump && dev.info.fm6 && !fm6Listing) op(fm6Refresh);
}
function renderPanels() {
/* the Tracks tab only with a four-track firmware */
const tracksOk = !dev || hasTracks() || !dev.info;
const fm6Off = !!dev && !!dev.info && !dev.info.fm6; /* the 6-OP FM tab: a hint without FM6 firmware */
const want = tab === "tracks" && dev && dev.info && !hasTracks() ? "sound" : tab;
for (const b of $("tabs").querySelectorAll("button[data-tab]")) {
const on = b.dataset.tab === want;
b.setAttribute("aria-selected", on ? "true" : "false");
b.tabIndex = on ? 0 : -1;
if (b.dataset.tab === "tracks") b.hidden = !tracksOk;
}
const ready = !!dev && !!dev.dump;
let hint = "";
for (const p of document.querySelectorAll(".panel")) {
const mine = p.dataset.tab === want;
let show = mine && (!("dev" in p.dataset) || ready);
if (mine && "dev" in p.dataset && !dev) hint = want === "fm6" ? "fm6NeedDevice" : "needDevice"; /* (while connecting the status line says it) */
if (show && want === "fm6" && fm6Off) { show = false; hint = "fm6NoFw"; }
if (show && want === "samples" && !dev.smp) { show = false; hint = "smpNone"; }
if (show && want === "song" && !(dev.info.skiff & 28)) { show = false; hint = "sgNoFw"; } /* ((Skiff W3)) */
p.hidden = !show;
}
$("hint").hidden = !hint;
if (hint) $("hint").textContent = t(hint);
$("trackbar").hidden = !(ready && hasTracks() && TRACK_TABS.has(want));
/* the FM6 slot names: listed once the tab shows with a device (also when it was already open at connect) */
if (ready && want === "fm6" && dev.info.fm6 && !fm6List && !fm6Asked) { fm6Asked = true; op(fm6Refresh); }
renderTransport();
}
/* (Skiff W3) the transport in the header (INFO 57 bit 0): PLAY (Shift: from the top), STOP, REC as the device's button
(the selected track armed or not); the state read with each keep-alive (the device's own changes push nothing). A
request the audio has yet to take shows as done */
function renderTransport(x) {
const on = !!dev && !!dev.dump && !!dev.info && !!(dev.info.skiff & 1);
$("transport").hidden = $("tstate").hidden = !on;
if (!on) return;
if (x) dev.transport = x;
const s = dev.transport;
if (!s) return;
const playing = s.pending ? s.pending !== 2 : s.playing || s.counting;
$("tplay").setAttribute("aria-pressed", String(playing));
$("tplay").title = t("playTitle");
$("trec").setAttribute("aria-pressed", String(!!(s.rec >> s.sel & 1)));
const armed = Array.from({ length: dev.info.ntrk || 0 }, (_, i) => i).filter((i) => s.rec >> i & 1).map((i) => "T" + (i + 1));
$("tstate").textContent = [t(s.counting && !s.pending ? "countIn" : playing ? "playing" : "stopped"),
...(armed.length ? [`REC ${armed.join(" ")}`] : [])].join(" · ");
}
async function readTransport(d = dev) {
if (!d || !d.info || !(d.info.skiff & 1)) return;
const x = parse[CMD.TRANSPORT](await sessionRequest(d, req.transport()));
if (d === dev) renderTransport(x);
}
async function transportOp(n) {
const d = dev;
if (!d) return;
try { const x = parse[CMD.TRANSPORT](await sessionRequest(d, req.transport(n))); if (d === dev) renderTransport(x); }
catch (e) { report(e); }
}
$("tplay").addEventListener("click", (e) => transportOp(e.shiftKey ? 3 : 1));
/* ((Skiff W3) the Song tab (INFO 57 bits 2..4): each track's list (SEQ › SONG), the scenes and the staged mutes
(PERFORM), the pattern pool (SAVE › PATTERNS), as the device has them: read when the tab opens, then as the
keep-alive while it shows (with the transport; the pool each 4th time), and after each change. A change acts as the
device's control does (it says so on its screen); no retries: a COPY sent twice would copy twice) */
let sgPick = { k: 0, e: 0 }, poolPick = 0;
const ENTS = "ABCDEFGHIJKLMNOP", pat2 = (n) => String(n).padStart(2, "0");
const SG_RC = { list: [null, "sgEmpty", "sgAutoFull", "sgStopClear", "sgFull", "sgFailed"],
pool: [null, "sgNothing", "sgInUse", "sgStopClear", "sgFailed"], perf: [null, "sgEmpty", "sgAutoFull", null, "sgFull"] };
async function readSong(d = dev, pool = true, poll = false) {
if (!d || !d.info || !(d.info.skiff & 28)) return;
const o = poll ? { quiet: true, retries: 0 } : undefined, rqs = (r) => sessionRequest(d, r, o);
if (poll && d.info.skiff & 1) { const x = parse[CMD.TRANSPORT](await rqs(req.transport())); if (d === dev) renderTransport(x); }
const s = d.song = d.song || {};
if (d.info.skiff & 8) s.list = parse[CMD.LIST](await rqs(req.list()));
if (d.info.skiff & 16) s.perf = parse[CMD.PERFORM](await rqs(req.perform()));
if (d.info.skiff & 4 && (pool || !s.pool)) s.pool = parse[CMD.POOL](await rqs(req.pool()));
if (d === dev) renderSong();
}
function songOp(r, kind) {
const d = dev;
op(async () => {
const x = parse[r[0]](await sessionRequest(d, r, { timeout: 4000, retries: 0 }));
await readSong(d, true);
const k = !(kind === "perf" && x.op === 5) && SG_RC[kind][x.rc];
if (k) sayK(k);
});
}
/* a list redrawn keeps the focus on the same control (data-key) */
function keepFocus(box, draw) {
const k = box.contains(document.activeElement) && document.activeElement.dataset.key;
draw();
const n = k && box.querySelector(`[data-key="${k}"]`);
if (n) n.focus();
}
function renderSong() {
const d = dev, caps = d && d.info ? d.info.skiff : 0, s = d && d.song;
$("sg-lists").hidden = !(caps & 8);
$("sg-scenes").hidden = !(caps & 16);
$("sg-pool").hidden = !(caps & 4);
if (!s) return;
const sig = JSON.stringify([s.list, s.perf, s.pool, sgPick, poolPick, lang]);
if (sig === renderSong.sig) return;
renderSong.sig = sig;
const L = s.list, P = s.perf, Q = s.pool;
if (L) {
$("sgsong").checked = L.song;
$("sglaunch").disabled = $("sgcancel").disabled = !P;
if (P) $("sglaunch").value = String(P.launch);
keepFocus($("sglists"), () => $("sglists").replaceChildren(el("table", { class: "lists" },
el("thead", {}, el("tr", {}, el("th"), ...[...ENTS].map((c) => el("th", { text: c })), ...(P ? [el("th", { text: "M" })] : []))),
el("tbody", {}, ...L.tracks.map((x, k) => el("tr", {}, el("th", { text: `T${k + 1}` }),
...x.ent.map((en, e) => el("td", {}, el("button", {
type: "button", "data-key": `l${k}:${e}`, "aria-pressed": String(sgPick.k === k && sgPick.e === e),
class: [en.pat ? "" : "empty", x.cur === e ? "on" : "", x.next === e ? "next" : "", sgPick.k === k && sgPick.e === e ? "pick" : ""].filter(Boolean).join(" ") || null,
"aria-label": `T${k + 1} ${ENTS[e]}: ${en.pat ? pat2(en.pat) : t("sgEmptyEntry")}`,
onclick: () => { sgPick = { k, e }; renderSong(); }, ondblclick: () => songOp(req.list(3, k, e), "list"),
}, en.pat ? pat2(en.pat) : "·", ...(en.pat && en.reps > 1 ? [el("sub", { text: "×" + en.reps })] : [])))),
...(P && P.tracks[k] ? [el("td", {}, el("button", { type: "button", "data-key": `m${k}`, class: P.tracks[k].staged ? "tog next" : "tog",
"aria-pressed": String(P.tracks[k].muted), "aria-label": `MUTE T${k + 1}`, onclick: () => songOp(req.perform(3, k), "perf") }, "M"))] : [])))))));
renderEntry(L, Q);
}
if (P) keepFocus($("sgscenes"), () => $("sgscenes").replaceChildren(...Array.from({ length: 16 }, (_, i) => {
const kept = !!(P.scenes >> i & 1);
return el("button", { type: "button", "data-key": `s${i}`, class: kept ? "kept" : "empty", "aria-pressed": String(P.last === i),
onclick: () => sceneClick(i, kept) }, String(i + 1));
})));
if (Q) {
keepFocus($("sgpool"), () => $("sgpool").replaceChildren(...Q.pats.map((p, i) => el("button", {
type: "button", "data-key": `p${i}`, "aria-pressed": String(poolPick === i),
class: [p.len ? (p.refs ? "" : "unused") : "empty", poolPick === i ? "pick" : ""].filter(Boolean).join(" ") || null,
"aria-label": `${pat2(i + 1)}: ${p.len ? `LEN ${p.len}` : t("sgEmptyPat")}`, onclick: () => { poolPick = i; renderSong(); },
}, p.len ? pat2(i + 1) : "·"))));
const p = Q.pats[poolPick];
$("sgpoolpick").replaceChildren(el("strong", { text: pat2(poolPick + 1) }), " ",
el("span", { class: "dim", text: p.len ? `LEN ${p.len} · ${p.refs ? t("sgUsedBy").replace("{n}", p.refs) : t("sgUnused")}` : t("sgEmptyPat") }), " ",
el("button", { type: "button", disabled: !p.len || !!p.refs,
onclick: () => { if (confirm(t("sgConfirmPat").replace("{n}", pat2(poolPick + 1)))) songOp(req.pool(poolPick), "pool"); } }, t("sgClear")));
}
}
/* the entry picked: its pattern (the kept ones), SET, COPY, PLAY, REPS, CLEAR (left alone while one of them has focus) */
function renderEntry(L, Q) {
const box = $("sgentry"), { k, e } = sgPick, en = L.tracks[k] && L.tracks[k].ent[e];
if (!en || box.contains(document.activeElement)) return;
const kept = Q ? Q.pats.map((p, i) => (p.len ? i + 1 : 0)).filter(Boolean) : [];
const sel = el("select", { "aria-label": t("sgPattern") }, ...kept.map((i) => el("option", { value: i, text: pat2(i) })));
if (en.pat) sel.value = String(en.pat);
const reps = el("input", { type: "number", min: 1, max: 16, value: en.reps, "aria-label": "REPS", style: "width:4em" }); /* (1.2.1, #12: an empty entry's is a rest's length) */
reps.addEventListener("change", () => songOp(req.list(5, k, e, Math.max(1, Math.min(16, +reps.value | 0))), "list"));
const what = () => {
const r = Q && Q.pats[en.pat - 1];
return t(r && r.refs > 1 ? "sgStays" : "sgGoesToo").replace("{n}", pat2(en.pat));
};
box.replaceChildren(el("strong", { text: `T${k + 1} ${ENTS[e]}` }), " ",
el("label", {}, el("span", { class: "dim", text: t("sgPattern") }), " ", sel),
el("button", { type: "button", disabled: !kept.length, onclick: () => songOp(req.list(1, k, e, +sel.value), "list") }, t("sgSet")),
el("button", { type: "button", disabled: !en.pat, onclick: () => songOp(req.list(2, k, e), "list") }, t("sgCopy")),
el("button", { type: "button", disabled: !en.pat, onclick: () => songOp(req.list(3, k, e), "list") }, t("sgPlay")),
el("label", {}, el("span", { class: "dim", text: "REPS" }), " ", reps),
el("button", { type: "button", disabled: !en.pat, onclick: () => {
if (confirm(t("sgConfirmEntry").replace("{e}", `T${k + 1} ${ENTS[e]}`).replace("{what}", what()))) songOp(req.list(4, k, e), "list");
} }, t("sgClear")));
}
function sceneClick(i, kept) {
if (!$("sgstore").checked) { songOp(req.perform(2, i), "perf"); return; }
if (kept && !confirm(t("sgConfirmScene").replace("{n}", i + 1))) return;
$("sgstore").checked = false;
songOp(req.perform(1, i), "perf");
}
$("sgsong").addEventListener("change", () => songOp(req.list(6, $("sgsong").checked ? 1 : 0), "list"));
$("sglaunch").addEventListener("change", () => songOp(req.perform(5, +$("sglaunch").value), "perf"));
$("sgcancel").addEventListener("click", () => songOp(req.perform(4), "perf"));
$("tstop").addEventListener("click", () => transportOp(2));
$("trec").addEventListener("click", () => transportOp(4));
$("tabs").addEventListener("click", (e) => { const b = e.target.closest("button[data-tab]"); if (b) showTab(b.dataset.tab); });
$("tabs").addEventListener("keydown", (e) => { /* arrow keys move between the tabs */
const dir = { ArrowRight: 1, ArrowLeft: -1 }[e.key];
if (!dir) return;
const bs = [...$("tabs").querySelectorAll("button[data-tab]:not([hidden])")];
const i = bs.findIndex((b) => b.getAttribute("aria-selected") === "true");
const n = bs[(i + dir + bs.length) % bs.length];
e.preventDefault();
showTab(n.dataset.tab);
n.focus();
});
window.addEventListener("hashchange", () => { const h = location.hash.slice(1); if (TABS.includes(h) && h !== tab) showTab(h); });
const QS = new URLSearchParams(location.search);
const MOCK = QS.get("mock") === "1";
$("mock").hidden = !MOCK;
let mock = null;
/* -------------------------------------------------------------- state --- */
let access = null; /* MIDIAccess */
let dev = null; /* {link, input, output, info, pdesc[], gdesc[], names[][], dump, steps[], slotUsed[],
keys[] (paramKeys), watch (pushes on), bank ({total, slots[]} or null: no user bank)} */
let busy = 0; /* multi-request operations in progress: no polling */
/* A completion from an unplugged device must not release a new session's work. */
let busyEpoch = 0;
function beginBusy() {
const epoch = busyEpoch;
let released = false;
busy++;
return () => {
if (!released && epoch === busyEpoch) busy--;
released = true;
};
}
function resetBusy() { busyEpoch++; busy = 0; }
let dragging = null; /* key of the slider being dragged */
let wantConnected = false;
const ctl = new Map(); /* key "s:id" -> {input, out, desc, scope, id, row} */
const sets = new Map(); /* key -> {last: time of the user's last change, sent: the value last requested} */
let needReload = false; /* a RELOAD push came: re-read DESC, DUMP and steps when free */
let lastDump = 0; /* Date.now() of the last DUMP */
/* the device also pushes RELOAD after loads the editor asked for (PROJECT load, UP_LOAD; before INFO 53 bit 1
also SET of G_ENGSEL and PRESET); the editor re-reads after those anyway, so it skips that many RELOADs for a
moment. sound: a PRESET / G_ENGSEL load (no RELOAD comes from newer firmware: none to skip) */
const selfReload = { n: 0, until: 0 };
function selfLoad(sound = false) {
if (!dev || !dev.watch || (sound && dev.info && dev.info.syncCaps & 2)) return;
const now = Date.now();
selfReload.n = now < selfReload.until ? selfReload.n + 1 : 1;
selfReload.until = now + 1500;
}
const stepEdit = new Map(); /* index -> time of the last edit */
/* parameter ids (firmware/src/core.h); used only when P_COUNT / G_COUNT match */
const EXPECT = { pcount: 91, gcount: 27, pe0: 83 };
/* the same layout without the chord keys (P_COUNT 89, P_E0 81), the FM operator ENVs too (69, 61) or the matrix
(firmware 1.0: 57, 49) */
const knownLayout = (info) => info.gcount === EXPECT.gcount &&
[[135, 127], [125, 117], [103, 95], [100, 92], [99, 91], [91, 83], [89, 81], [69, 61], [57, 49]].some(([c, e]) => info.pcount === c && info.pe0 === e);
const P = { LEVEL: 0, SLEN: 29 };
const LAYOUT = (pe0) => [
{ t: "ENV", pages: [["ENV", 0, [1, 2, 3, 4]], ["ENV DEST", 0, pe0 >= 127 ? [5, 6, 7, P_ESYNC] : [5, 6, 7]], /* ((Skiff W5) P_ED_FX,
8: nothing reads it; (1.3) ENV SYNC) */
...(pe0 >= 117 ? [["ENV 2", 0, P_ENV2]] : [])] }, /* ((Skiff phase 9) ENV 2: the MOD matrix's ENV2) */
{ t: "LFO", pages: [["LFO", 0, [9, 10, 11, 12]], ...(pe0 >= 127 ? [["LFO 2", 0, P_LFO2]] : []), ["LFO DEST", 0, [13, 14, 15, 16]]] },
...(pe0 >= 61 ? [{ t: "MOD", mod: 49 }] : []), /* the matrix: P_M1SRC 49 .. P_M4AMT 60, one row per slot */
{ t: "EDIT", engine: true, pages: [["EDIT 1", 0, [pe0, pe0 + 1, pe0 + 2, pe0 + 3]], ["EDIT 2", 0, [pe0 + 4, pe0 + 5, pe0 + 6, pe0 + 7]],
...(pe0 >= 91 && ["DRUM", "DRUM-X"].includes(engName()) ? [["LANES", 0, P_LANES.slice(0, 4)], ["LANES 2", 0, P_LANES.slice(4)]] : []), /* lane levels 83..90 */
...(pe0 >= 117 && engName() === "DRUM" ? [["TUNE", 0, P_LTUNE.slice(0, 4)], ["TUNE 2", 0, P_LTUNE.slice(4)], /* ((Skiff phase 9) */
["DECAY", 0, P_LDECAY.slice(0, 4)], ["DECAY 2", 0, P_LDECAY.slice(4)]] : [])] },
...(pe0 >= 81 && engName() === "DIGITAL" ? [{ t: "OP ENV", pages: [ /* P_FM1_ATK 61: ATK DEC SUS REL LVL per operator (a
FELUCCA_FM4=1 firmware only: DIGITAL retired, its engine is "-") */
...[0, 1, 2, 3].map((k) => [`OP${k + 1}`, 0, [61 + 5 * k, 62 + 5 * k, 63 + 5 * k, 64 + 5 * k]]),
["OP LVL", 0, [65, 70, 75, 80]]] }] : []),
{ t: "VOICE", pages: [["LEVEL", 0, [0]], ["VOICE", 0, [37, 38, 41, 42]], ["VOICE 2", 0, [43, 44, 39, 40]],
...(pe0 >= 127 ? [["SPREAD", 0, [P_SPRD]]] : [])] }, /* ((1.3) the voices left and right of PAN) */
{ t: "FX", pages: [["FX", 0, [33, 34, 35, 36]], ...(pe0 >= 117 ? [["DRIVE", 0, [33, ...P_DRIVE]]] : []),
...(pe0 >= 127 ? [["INSERT", 0, P_INSERT], ["INSERT 2", 0, [P_IMIX]]] : []), /* ((1.3) the track's INSERT) */
["SLICER", 0, [45, 46, 47, 48]], ...(pe0 >= 95 ? [["DUCK", 0, P_DUCK]] : []), ["DLY", 1, [4, 5, 6, 7]], ["REVERB", 1, [24, 8, 9]], ["CHORUS", 1, pe0 >= 117 ? [10, 11, 25, 26] : [10, 11]]] }, /* G_RTYPE 24: ROOM / SPRING */
{ t: "SCALE", pages: [["SCALE", 0, [25, 26, 27, 28]], ...(pe0 >= 83 ? [["CHORD", 0, P_CHORD]] : [])] }, /* CHRD VOIC 81, 82 */
{ t: "ARP", pages: [["ARP", 0, [17, 18, 19, 20]], ["ARP 2", 0, [21, 22, 23, 24]]] },
{ t: "SEQ PATTERN", tab: "seqgroups", pages: [["PATTERN", 0, [29, 30, 31, 32]], ...(pe0 >= 92 ? [["PLAY", 0, [P_DIR]]] : [])] },
{ t: "GLOBAL", tab: "setgroups", pages: [["GLOBAL", 1, [0, 1, 2, 3]], ["SYSTEM", 1, [14]]] }, /* G_ROUTE: MIDI IN */
];
/* globals that are actions or placeholders on the device: buttons instead, or hidden */
const G_SKIP = new Set(["SLOT", "NAME", "LOAD", "SAVE", "ENG", "SET", "CLRSQ", "INIT", "MIDI", "SYNC", "CPU", "CLK"]);
const key = (s, id) => s + ":" + id;
const engName = () => (dev && dev.info && dev.dump ? dev.info.engines[dev.dump.engine] : "");
const gEng = () => { const i = dev.gdesc.findIndex((d) => d && (d.label === "ENGINE" || d.label === "ENG")); return i >= 0 ? i : 20; };
const pSlen = () => { const i = dev.pdesc.findIndex((d) => d && d.fmt === F.STEPS); return i >= 0 ? i : P.SLEN; };
/* mixer ids by DESC label (core.h: P_PAN 39, P_MUTE 40) */
const pById = (label, def) => { const i = dev.pdesc.findIndex((d, k) => d && k < dev.info.pe0 && d.label === label); return i >= 0 ? i : def; };
const pPan = () => pById("PAN", 39), pMute = () => pById("MUTE", 40), pRev = () => pById("REVERB", 36);
/* -------------------------------------------------------------- MIDI --- */
let connecting = false;
async function connect() {
if (connecting || dev) return;
connecting = true;
let connectedDevice = null;
wantConnected = true;
if (!MOCK && !navigator.requestMIDIAccess) { connecting = false; sayK("nomidi"); return; }
$("connect").disabled = true;
sayK("connecting");
try {
if (!access) {
if (MOCK) { mock = makeMockDevice({ legacy: QS.get("legacy") === "1" }); access = mock.access; }
else {
try { access = await navigator.requestMIDIAccess({ sysex: true }); }
catch (e) { sayK("denied"); return; }
}
access.onstatechange = onState;
}
const isF = (p) => /felucca/i.test(p.name || "") && p.state !== "disconnected";
const input = [...access.inputs.values()].find(isF);
const output = [...access.outputs.values()].find(isF);
if (!input || !output) { sayK("nodevice"); return; }
const link = new Link((d) => output.send(d), {
timeout: 300,
onUnknown: (f) => console.debug("ignored reply", f),
onTimeout: () => sayK("noreply"),
onPush: (f) => onPush(f),
onGap: () => { rewatch = true; },
});
input.onmidimessage = (e) => link.receive(e.data);
if (input.open) await input.open().catch(() => {});
dev = { link, input, output, info: null, pdesc: [], gdesc: [], names: [], dump: null, steps: [], slotUsed: [null, null, null, null],
keys: null, watch: false, bank: null };
connectedDevice = dev;
setLabel($("connect"), t("disconnect"));
await load(connectedDevice);
} catch (e) {
console.error(e);
if (connectedDevice && connectedDevice === dev) { /* an old connection must not close a replacement */
const timeout = /^timeout/.test(e.message);
disconnect();
sayK(timeout ? "noreply" : "error", timeout ? "" : e.message);
}
} finally {
connecting = false;
$("connect").disabled = false;
}
}
function disconnect(reasonKey = "disconnected") {
samplesLeave(); /* the Samples tab goes: so do the input and the preview */
if (dev) {
dev.link.close();
dev.input.onmidimessage = null;
}
dev = null;
resetBusy();
needReload = false;
renderPanels();
renderMixer();
renderSysinfo();
renderLive();
renderLib();
renderBank();
renderPreferences(true);
$("version").textContent = "";
setLabel($("connect"), t("connect"));
sayK(reasonKey);
}
function onState(e) {
const p = e.port;
if (!p || !/felucca/i.test(p.name || "")) return;
if (dev && p.state === "disconnected" && (p.id === dev.input.id || p.id === dev.output.id)) {
disconnect("lost");
} else if (!dev && wantConnected && p.state === "connected" && p.type === "output") {
clearTimeout(onState.tm); /* the device came back: reconnect */
onState.tm = setTimeout(() => { if (!dev && wantConnected) connect(); }, 800);
}
}
function assertSession(d) { if (!d || d !== dev) throw new Error("closed"); }
async function sessionRequest(d, r, opt) {
assertSession(d);
const reply = await d.link.request(r, opt);
assertSession(d);
return reply;
}
const rq = (r, opt) => sessionRequest(dev, r, opt);
async function getDesc(scope, id, d = dev) { return parse[CMD.DESC](await sessionRequest(d, req.desc(scope, id))); }
async function getDump(d = dev) { const reply = await sessionRequest(d, req.dump()); lastDump = Date.now(); return parse[CMD.DUMP](reply, d.info); }
async function getStep(i, d = dev) { return parse[CMD.STEP_GET](await sessionRequest(d, req.stepGet(i))); }
/* the whole connect sequence */
async function load(d) {
const releaseBusy = beginBusy();
try {
/* the first frame after opening the port can be lost: a few tries */
d.info = parse[CMD.INFO](await sessionRequest(d, req.info(), { timeout: 500, retries: 3 }));
$("version").textContent = d.info.version;
const total = d.info.pcount + d.info.gcount;
for (let i = 0; i < d.info.pcount; i++) { sayK("reading", `${i + 1}/${total}`); d.pdesc[i] = await getDescOrNull(0, i, d); }
for (let i = 0; i < d.info.gcount; i++) { sayK("reading", `${d.info.pcount + i + 1}/${total}`); d.gdesc[i] = await getDescOrNull(1, i, d); }
d.titles = [];
for (let e = 0; e < d.info.nengines; e++) {
const r = parse[CMD.NAMES](await sessionRequest(d, req.names(e)));
d.names[e] = r.names;
d.titles[e] = r.titles;
}
for (let k = 0; k < 4; k++) { /* PROJECT op 2: is the slot used */
try { d.slotUsed[k] = parse[CMD.PROJECT](await sessionRequest(d, req.project(2, k))).used; }
catch (e) { if (e.message === "closed") throw e; }
}
try { d.smp = parse[CMD.SMP_INFO](await sessionRequest(d, req.smpInfo())); }
catch (e) { if (e.message === "closed") throw e; d.smp = null; } /* older firmware, or no flash */
d.keys = paramKeys(d.pdesc, d.info.pe0, d.info.pcount);
await libAdopt(d);
assertSession(d);
if (d.info.ntrk) d.sel = parse[CMD.TRACK](await sessionRequest(d, req.track())).sel; /* v3: the selected track */
d.dump = await getDump(d);
buildUI();
renderPanels();
await loadStepsIfShown(d);
if (d.info.ntrk) await readMixer(d, true);
await readMenu(d); /* ((Skiff W3) the MENU settings) */
await readTransport(d); /* ((Skiff W3) the transport, the projects' names) */
await readProj(d);
/* protocol v2: live pushes and the user bank; older firmware: DUMP polling, no bank */
const rqd = (r, o) => sessionRequest(d, r, o);
d.watch = await startWatch(rqd);
d.v4 = d.watch === 3; /* TRACK_PARAM / TRACK_CHANGED */
if (d.watch) {
sayK("readingBank");
try { d.bank = await bank.list((r, o) => sessionRequest(d, r, { ...o, quiet: true })); }
catch (e) { if (e.message === "closed") throw e; d.bank = null; }
}
await syncPreferences(d);
renderLive();
renderLib();
renderBank();
renderSysinfo();
sayK("ready");
} finally { releaseBusy(); }
}
async function getDescOrNull(s, i, d = dev) { try { return await getDesc(s, i, d); } catch (e) { if (e.message === "closed") throw e; return null; } }
/* rebuilds the controls only when the engine or its parameters changed (a slider being dragged survives) */
async function rereadEngineDesc(d = dev) {
assertSession(d);
const pe0 = d.info.pe0, e = d.dump.engine, name = d.info.engines[e];
const before = JSON.stringify(d.pdesc.slice(pe0));
const keep = name !== "SAMPLE" && name !== "SLICE"; /* ((Skiff W7) cached per engine; not these: their names are the
user's samples, which change) */
d.descCache = d.descCache || {};
if (keep && d.descCache[e]) d.descCache[e].forEach((x, i) => { d.pdesc[pe0 + i] = x; });
else {
for (let i = 0; i < 8 && pe0 + i < d.info.pcount; i++) d.pdesc[pe0 + i] = await getDescOrNull(0, pe0 + i, d);
if (keep) d.descCache[e] = d.pdesc.slice(pe0, pe0 + 8);
}
if (d.built !== d.dump.engine || JSON.stringify(d.pdesc.slice(pe0)) !== before) buildGroups();
}
/* ((Skiff W7) the steps (64 requests) only where they are shown: off the Sequencer tab they wait (stepsStale), read when
it opens or a file is saved) */
async function loadStepsIfShown(d = dev) {
if (tab === "sequencer") return loadSteps(d);
d.steps = [];
d.stepsStale = true;
$("steptables").dataset.len = "";
renderSteps();
}
async function loadSteps(d = dev) {
assertSession(d);
d.stepsStale = false;
const n = d.info.nstep;
for (let i = 0; i < n; i++) {
if (i % 8 === 0) sayK("steploading", `${i}/${n}`);
d.steps[i] = await getStep(i, d);
}
renderSteps();
if (d.info.motionMax) await readMotion(d);
}
/* --------------------------------------------------------------- UI --- */
function buildUI() {
const sel = $("engine");
/* (engine 1, "-": DIGITAL retired, reserved: never offered) */
sel.replaceChildren(...engineOrder(dev.info.engines).map((i) => el("option", { value: i, text: dev.info.engines[i] }))); /* (shown order) */
dev.mix = null;
buildGroups();
updateBrowser();
renderSlots();
renderSamples();
renderSysinfo();
fm6List = null;
fm6Asked = false;
fm6Picked = -1;
renderFm6();
}
/* the track selector (v3): every track (INFO's count); the editor shows the selected one */
function renderTrackbar() {
const box = $("trackbtns");
const ntrk = hasTracks() ? dev.info.ntrk : 0;
if (box.children.length !== ntrk || box.dataset.lang !== lang) {
box.dataset.lang = lang;
box.replaceChildren(...Array.from({ length: ntrk }, (_, i) => el("button", { type: "button", "data-i": i,
onclick: () => selectTrack(i) }, String(i + 1))));
}
for (const b of box.children) b.setAttribute("aria-pressed", +b.dataset.i === (dev.sel || 0) ? "true" : "false");
document.documentElement.style.setProperty("--trk", `var(--t${(dev.sel || 0) + 1})`); /* (the selected track's colour) */
}
function selectTrack(i) {
if (!dev || !hasTracks() || i === dev.sel) return;
op(async () => {
dev.sel = parse[CMD.TRACK](await rq(req.track(i))).sel;
await afterSoundChange();
});
}
/* settings > system: what the device reported */
function renderSysinfo() {
const box = $("sysinfo");
if (!dev || !dev.info) { box.replaceChildren(); return; }
const i = dev.info;
const rows = [
["firmware", i.version], ["sync", t(dev.watch ? "live" : "polling")], ["enginesL", i.engines.join(", ")],
["tracksN", i.ntrk ? String(i.ntrk) : "1"], ["stepsN", String(i.nstep)],
["smpSlots", dev.smp ? `${dev.smp.nslots} × ${dev.smp.slotKiB} KiB` : t("none")],
["userBank", dev.bank ? String(dev.bank.total) : t("none")],
];
box.replaceChildren(...rows.map(([k, v]) => el("tr", {}, el("th", { text: t(k) }), el("td", { text: v }))));
}
/* (Skiff phase 6) engine e on the selected track: not on a light one (INFO 54: no GRAIN, no PHYS on T5, T6) */
const engineAllowed = (e) => !dev || !((dev.info.light.tracks >> (dev.sel ?? 0)) & 1) || !((dev.info.light.engines >> e) & 1);
function updateBrowser() {
const e = dev.dump.engine;
const sel = $("engine");
renderTrackbar();
for (const o of sel.options) o.disabled = !engineAllowed(+o.value); /* (greyed: the device refuses them there) */
if (document.activeElement !== sel) sel.value = String(e);
const ps = $("preset");
const names = dev.names[e] || [];
if (ps.dataset.engine !== String(e)) {
ps.replaceChildren(...names.map((n, i) => el("option", { value: i, text: n, hidden: aliasOf(names, i) !== i })));
ps.dataset.engine = String(e);
}
if (document.activeElement !== ps) ps.value = String(dev.dump.preset);
}
function visible(d) { return d && d.max > d.min && d.label !== "-"; }
/* a matrix destination E1..E8 by the engine's label of that parameter (as the device shows it) */
function modDst(d, txt) {
const m = d && /^DST\d$/.test(d.label) && /^E([1-8])$/.exec(txt);
const e = m && dev && dev.pdesc[dev.info.pe0 + +m[1] - 1];
return e && visible(e) ? e.label : txt;
}
function buildGroups() {
ctl.clear();
dev.built = dev.dump.engine;
/* Sound: the selected track's parameters; Sequencer: its pattern settings; Settings: globals */
const groups = { groups: [], seqgroups: [], setgroups: [] };
const { info } = dev;
if (knownLayout(info)) {
for (const g of LAYOUT(info.pe0)) {
const div = el("div", { class: "group" }, el("h2", { ic: HEAD_IC[g.t], text: g.engine ? `EDIT ${info.engines[dev.dump.engine] || ""}` : g.t }));
if (g.mod != null) { /* MOD: slot number, SRC, DST, AMT in one row */
for (let k = 0; k < 4; k++) {
const r = [0, 1, 2].map((j) => paramRow(0, g.mod + 3 * k + j));
if (r.some((x) => !x)) continue;
const row = el("div", { class: "row modrow" }, el("span", { text: String(k + 1) }), r[0].children[1], r[1].children[1],
r[2].children[1], r[2].children[2]);
for (let j = 0; j < 3; j++) ctl.get(key(0, g.mod + 3 * k + j)).row = row; /* (the push highlight) */
div.append(row);
}
groups.groups.push(div);
continue;
}
for (const [title, s, ids] of g.pages) {
const rows = ids.map((id) => paramRow(s, id)).filter(Boolean);
if (!rows.length) continue;
const tt = g.engine && (dev.titles[dev.dump.engine] || [])[g.pages.findIndex((x) => x[0] === title)];
if (g.pages.length > 1) div.append(el("h3", { ic: PAGE_IC[tt || title], text: tt || title }));
div.append(...rows);
}
groups[g.tab || "groups"].push(div);
}
} else {
/* unknown firmware layout: everything in id order */
const a = el("div", { class: "group" }, el("h2", { ic: HEAD_IC.INSTRUMENT, text: "INSTRUMENT" }), el("p", { class: "dim", text: t("layout") }));
const b = el("div", { class: "group" }, el("h2", { ic: HEAD_IC.EDIT, text: "EDIT" }));
const c = el("div", { class: "group" }, el("h2", { ic: HEAD_IC.GLOBAL, text: "GLOBAL" }));
for (let i = 0; i < info.pcount; i++) { const r = paramRow(0, i); if (r) (i >= info.pe0 ? b : a).append(r); }
for (let i = 0; i < info.gcount; i++) { const r = paramRow(1, i); if (r) c.append(r); }
groups.groups.push(a, b);
groups.setgroups.push(c);
}
if (kitShown()) groups.groups.push(kitGroup()); /* ((Skiff W3)) */
for (const [id, divs] of Object.entries(groups)) $(id).replaceChildren(...divs);
if (kitShown()) { renderKit(); op(() => readKit()); }
}
/* (Skiff W3) the DRUM-X kit on a DRUM-X track's Sound tab (INFO 4B): one kit for every DRUM-X track, the project's (as
the device's EDIT > SOUND). A lane picked, its sound read (KIT_GET) when shown and each time the tab opens (the
device's own edits push nothing), each change sent whole (KIT_PUT: the lane's latest wins) */
let kitLane = 0;
const kitShown = () => !!dev && !!dev.dump && !!dev.info.kitLanes && dev.info.engines[dev.dump.engine] === "DRUM-X";
function kitGroup() {
return el("div", { class: "group", id: "dxkit" }, el("h2", { ic: HEAD_IC.EDIT, text: "DRUM-X KIT" }),
el("p", { class: "dim", "data-t": "dxKitHelp", text: t("dxKitHelp") }),
el("p", { class: "bar" }, el("span", { class: "seg", role: "group", "aria-label": "DRUM-X KIT" },
...DX.lanes.map((n, i) => el("button", { type: "button", "data-i": i, onclick: () => { kitLane = i; renderKit(); op(() => readKit()); } }, n)))),
el("div", { id: "dxkitctl" }));
}
async function readKit(d = dev) {
if (!kitShown()) return;
const k = parse[CMD.KIT_GET](await sessionRequest(d, req.kitGet(kitLane)));
if (d === dev && k.lane === kitLane) { d.kit = k; renderKit(); }
}
async function kitSend(k) {
try { await sessionRequest(dev, req.kitPut(k), { key: "kit:" + k.lane }); } catch (e) { report(e); }
}
function renderKit() {
const box = $("dxkitctl"), k = dev && dev.kit;
if (!box) return;
for (const b of $("dxkit").querySelectorAll(".seg button")) b.setAttribute("aria-pressed", String(+b.dataset.i === kitLane));
if (!k || k.lane !== kitLane) { box.replaceChildren(); return; }
if (box.contains(document.activeElement) && box.dataset.lane === String(k.lane)) return; /* (being edited) */
box.dataset.lane = String(k.lane);
const pick = (label, names, f) => {
const s = el("select", { "aria-label": label }, ...names.map((n, i) => el("option", { value: i, text: n })));
s.value = String(k[f]);
s.addEventListener("change", () => { k[f] = +s.value; kitSend(k); });
return el("label", {}, el("span", { class: "dim", text: label }), " ", s);
};
const tog = (label, f) => {
const c = el("input", { type: "checkbox" });
c.checked = k[f];
c.addEventListener("change", () => { k[f] = c.checked; kitSend(k); });
return el("label", {}, c, " ", label);
};
const slider = (n, side, i) => {
const r = el("input", { type: "range", min: 0, max: 127, step: 1, "aria-label": `${n} ${side.toUpperCase()}` }), o = el("span", { class: "v" });
r.value = o.textContent = String(k[side][i]);
r.addEventListener("input", () => { k[side][i] = +r.value; o.textContent = r.value; kitSend(k); });
return [r, o];
};
box.replaceChildren(
el("p", { class: "bar" }, pick("WAVE", DX.waves, "wave"), pick("FILTER", DX.filters, "filt"), tog("SNAP", "snap"),
pick("P SHAPE", DX.shapes, "pmod"), tog("DRIVE", "drive")),
el("div", { class: "row kitrow dim" }, el("span"), el("span", { text: "A" }), el("span"), el("span", { text: "B" }), el("span")),
...DX.values.map((n, i) => el("div", { class: "row kitrow" }, el("span", { text: n }), ...slider(n, "a", i), ...slider(n, "b", i))));
}
function paramRow(s, id) {
const d = s ? dev.gdesc[id] : dev.pdesc[id];
if (!visible(d) || (s === 1 && G_SKIP.has(d.label))) return null;
const k = key(s, id);
let input;
if (d.fmt === F.ENUM || d.fmt === F.NOTE || d.fmt === F.ONOFF) {
const wave = RICH_SELECT && d.fmt === F.ENUM && /^WAVE2?$/.test(d.label);
input = el("select", { class: wave ? "wave" : null });
/* the closed select shows a copy of the chosen option (icon span included), not its bare text */
if (wave) input.append(el("button", {}, el("selectedcontent")));
for (const v of enumShown(d)) { /* (note divisions longest first: #48) */
const [txt] = fmtValue(d, v);
const name = d.fmt === F.ENUM && d.names[v - d.min] == null ? String(v) : modDst(d, txt);
const alias = d.fmt === F.ENUM && aliasOf(d.names, v - d.min) !== v - d.min; /* shown when set, not offered */
input.append(el("option", { value: v, ic: wave && WAVE_IC[name], hidden: alias }, name));
}
input.addEventListener("change", () => userSet(s, id, +input.value, true));
} else {
input = el("input", { type: "range", min: d.min, max: d.max, step: 1 });
input.addEventListener("pointerdown", () => { dragging = k; });
input.addEventListener("input", () => userSet(s, id, +input.value, false));
input.addEventListener("change", () => userSet(s, id, +input.value, true));
input.addEventListener("dblclick", () => { input.value = d.def; userSet(s, id, d.def, true); });
/* fine adjust: wheel over the focused slider, Shift+arrows in steps of 10 (plain arrows are native) */
const nudge = (dv) => {
const nv = Math.max(d.min, Math.min(d.max, +input.value + dv));
if (nv !== +input.value) { input.value = String(nv); userSet(s, id, nv, true); }
};
let acc = 0;
input.addEventListener("wheel", (e) => {
if (document.activeElement !== input) return;
e.preventDefault();
acc += (e.deltaMode === 1 ? 33 : 1) * (Math.abs(e.deltaY) >= Math.abs(e.deltaX) ? -e.deltaY : e.deltaX);
const n = Math.trunc(acc / 50);
if (n) { acc -= n * 50; nudge(n * (e.shiftKey ? 10 : 1)); }
}, { passive: false });
input.addEventListener("keydown", (e) => {
const dir = { ArrowUp: 1, ArrowRight: 1, ArrowDown: -1, ArrowLeft: -1 }[e.key];
if (!dir || !e.shiftKey) return;
e.preventDefault();
nudge(dir * 10);
});
}
input.title = d.label;
const out = el("span", { class: "v" });
const row = el("div", { class: "row" }, el("span", { text: d.label }), input, out);
ctl.set(k, { input, out, desc: d, scope: s, id, row });
showValue(k, s ? dev.dump.g[id] : dev.dump.p[id], true);
return row;
}
/* (Skiff 1.3) ENV SYNC on (P_ESYNC): ATTACK DECAY RELEASE are note values of the tempo (params.c ESYNC_NAMES: 0..127 split
evenly over them) */
const ESYNC_NAMES = ["0", "1/64T", "1/64", "1/32T", "1/64D", "1/32", "1/16T", "1/32D", "1/16", "1/8T", "1/16D", "1/8", "1/4T", "1/8D",
"1/4", "1/2T", "1/4D", "1/2", "1/1T", "1/2D", "1/1", "1/1D", "2BAR", "3BAR", "4BAR"];
const eSyncOn = (c) => !c.scope && [1, 2, 4].includes(c.id) && !!dev && !!dev.info && dev.info.pe0 >= 127 && !!dev.dump &&
!!dev.dump.p[P_ESYNC];
function showValue(k, v, force) {
const c = ctl.get(k);
if (!c || v == null) return;
let [txt0, unit] = fmtValue(c.desc, v), txt = modDst(c.desc, txt0);
if (eSyncOn(c)) { txt = ESYNC_NAMES[(v & 127) * ESYNC_NAMES.length >> 7]; unit = ""; } /* ((1.3) ENV SYNC: a note value) */
c.out.textContent = unit ? `${txt} ${unit}` : txt;
if (c.input.type === "range") c.input.setAttribute("aria-valuetext", c.out.textContent); /* ((Skiff W6) read as shown) */
if (force || !touched(k)) c.input.value = String(v);
}
/* the user is working on this control: polling and pushes must not move it */
function touched(k) {
const c = ctl.get(k), st = sets.get(k);
if (dragging === k) return true;
if (c && c.input.tagName === "SELECT" && document.activeElement === c.input) return true;
if (st && performance.now() - st.last < 600) return true;
return !!dev && (dev.link.hasQueued(k) || (!!dev.link.cur && dev.link.cur.key === k));
}
window.addEventListener("pointerup", () => { if (dragging) { const k = dragging; dragging = null; const c = ctl.get(k); if (c) userSet(c.scope, c.id, +c.input.value, true); } });
window.addEventListener("pointercancel", () => { dragging = null; });
/* SET as fast as the device answers: one SET per control in flight and at most one queued, which
always carries the latest value (Link coalesces by key), so a drag never builds a backlog */
function userSet(s, id, v, final) {
if (!dev) return;
const k = key(s, id);
(s ? dev.dump.g : dev.dump.p)[id] = v;
showValue(k, v, false);
mixFromDump();
let st = sets.get(k);
if (!st) sets.set(k, (st = { last: 0, sent: null }));
st.last = performance.now();
if (v === st.sent) return; /* the last request already carries it */
sendSet(s, id, k);
}
async function sendSet(s, id, k) {
if (!dev) return;
const st = sets.get(k);
const v = (s ? dev.dump.g : dev.dump.p)[id];
st.sent = v;
try {
const r = parse[CMD.SET](await rq(req.set(s, id, v), { key: k }));
if (dev && dragging !== k && st.sent === v && !dev.link.hasQueued(k)) { /* the device's value after clamping */
(s ? dev.dump.g : dev.dump.p)[id] = r.value;
showValue(k, r.value, false);
mixFromDump();
}
} catch (e) { if (e.message !== "closed") console.warn(e); }
}
/* engine / preset browser */
$("engine").addEventListener("change", () => choosePreset(+$("engine").value, 0));
$("preset").addEventListener("change", () => { if (dev) choosePreset(dev.dump.engine, +$("preset").value); });
async function choosePreset(e, p) {
if (!dev) return;
const releaseBusy = beginBusy();
try {
selfLoad(true);
parse[CMD.PRESET](await rq(req.preset(e, p)));
await afterSoundChange();
} catch (err) { report(err); } finally { releaseBusy(); }
}
async function afterSoundChange(msg = "ready", d = dev) {
assertSession(d);
needReload = false; /* this re-reads everything a RELOAD asks for */
d.dump = await getDump(d);
await rereadEngineDesc(d);
if (d === dev && kitShown()) await readKit(d); /* ((Skiff phase 9) a DRUM-X preset loads its own kit) */
updateBrowser();
refreshAll();
await loadStepsIfShown(d); /* (a sound load keeps them; read anyway after a RELOAD) */
if (hasTracks()) await readMixer(d); /* the sound names and the selected strip */
sayK(msg);
}
$("init").addEventListener("click", async () => {
if (!dev || !confirm(t("confirmInit"))) return;
const releaseBusy = beginBusy();
try { selfLoad(true); await rq(req.set(1, gEng(), dev.dump.engine)); await afterSoundChange(); }
catch (err) { report(err); } finally { releaseBusy(); }
});
function refreshAll() {
for (const [k, c] of ctl) showValue(k, c.scope ? dev.dump.g[c.id] : dev.dump.p[c.id], false);
renderSteps();
}
function report(err) { if (err && err.message !== "closed") { console.warn(err); sayK("error", err.message); } }
/* projects: the protocol cannot ask whether a slot is used without loading or saving it */
/* ((Skiff W3) PROJ_NAME, INFO 57 bit 1: the music now (its slot, its name, changed since), each slot's name; SAVE and
RENAME take the name field's (the music's until edited). Read at connect, when the tab opens and after each of these) */
async function readProj(d = dev) {
if (!d || !d.info || !(d.info.skiff & 2)) return;
setProj(d, parse[CMD.PROJ_NAME](await sessionRequest(d, req.projName())));
}
function setProj(d, p) {
d.proj = p;
p.slots.forEach((x, k) => { d.slotUsed[k] = x.used; });
if (d === dev) renderSlots();
}
const slotL = (i) => String.fromCharCode(65 + i);
function renderSlots() {
renderBackup();
const box = $("slots"), pn = dev.proj;
$("projnow").hidden = !pn;
if (pn) $("projnow").textContent = `${t("projNow")}: ${pn.cur >= 0 ? slotL(pn.cur) : "—"} · ${pn.name || t("noName")}` +
(pn.changed ? ` · ${t("projChanged")}` : "");
box.classList.toggle("named", !!pn);
$("projnamebar").hidden = !pn;
if (pn && !$("projname").dataset.edited) $("projname").value = pn.name;
box.replaceChildren();
for (let i = 0; i < 4; i++) {
const u = dev.slotUsed[i], x = pn && pn.slots[i];
box.append(el("span", { text: slotL(i) }),
el("span", { class: x && x.used ? null : "dim", text: x ? (x.used ? x.name || t("noName") : t("empty")) : u == null ? t("unknown") : t(u ? "used" : "empty") }),
el("button", { ic: "symbol_folder_open", onclick: () => project(0, i) }, t("load")),
el("button", { ic: "port_disk", onclick: () => project(1, i) }, t("save")),
...(pn ? [el("button", { disabled: !x.used, onclick: () => renameProject(i) }, t("rename"))] : []));
}
}
$("projname").addEventListener("input", () => { $("projname").dataset.edited = "1"; });
async function renameProject(slot) {
const d = dev, name = $("projname").value;
if (!d || !d.proj) return;
op(async () => {
const r = parse[CMD.PROJ_NAME](await sessionRequest(d, req.projName(2, slot, name), { timeout: 4000, retries: 0 }));
if (!r.rc) delete $("projname").dataset.edited;
setProj(d, r);
if (r.rc) throw new Error(t(r.rc === 1 ? "projRefused" : "projFailed"));
sayK("renamedSlot", slotL(slot));
});
}
async function project(op, slot) {
if (!dev) return;
const pn = op ? dev.proj : null, name = $("projname").value; /* ((Skiff W3) SAVE AS: the name field's) */
if ((!pn || pn.slots[slot].used) && !confirm(t(op ? "confirmSave" : "confirmLoad").replace("{n}", slotL(slot)))) return; /* ((W5) A..D) */
const releaseBusy = beginBusy();
try {
if (pn) {
const d = dev, r = parse[CMD.PROJ_NAME](await rq(req.projName(1, slot, name), { timeout: 4000, retries: 0 }));
if (!r.rc) delete $("projname").dataset.edited;
setProj(d, r);
if (r.rc) throw new Error(t(r.rc === 1 ? "projRefused" : "projFailed"));
sayK("savedSlot", slotL(slot));
return;
}
/* save writes flash: a long timeout and no retry */
if (!op) selfLoad();
const r = parse[CMD.PROJECT](await rq(req.project(op, slot), { timeout: 4000, retries: 0 }));
dev.slotUsed[slot] = r.used;
renderSlots();
if (!op && r.used) await afterSoundChange();
await readProj(); /* ((Skiff W3) the music's slot and name now) */
sayK(op ? "savedSlot" : r.used ? "loadedSlot" : "emptySlot", slotL(slot));
} catch (err) { report(err); } finally { releaseBusy(); }
}
/* Complete archives remain on this computer; no project or sample is uploaded to a server. */
function renderBackup() {
const caps = dev?.info?.backupCaps || 0;
$("backup-export").disabled = !(caps & 1);
$("backup-import").disabled = !(caps & 2);
$("backup-help").textContent = t(caps & 1 ? "backupHelp" : "backupOld");
}
const backupModule = () => import("./fm1backup.js");
const backupProgress = (done, total) => sayK("backupWorking", `${Math.round(done / Math.max(1, total) * 100)}%`);
$("backup-export").addEventListener("click", () => op(async () => {
const d = dev;
if (!(d?.info?.backupCaps & 1)) return;
const { captureBackup } = await backupModule();
assertSession(d);
const file = await captureBackup((r, o) => sessionRequest(d, r, o), d.info.version, backupProgress);
assertSession(d);
download(`Skiff-backup-${new Date().toISOString().slice(0, 10)}.json`, file);
sayK("backupDone");
}));
$("backup-import").addEventListener("click", () => { if (dev?.info?.backupCaps & 2) $("backup-file").click(); });
$("backup-file").addEventListener("change", () => {
const file = $("backup-file").files[0], d = dev; $("backup-file").value = "";
if (!file || !(d?.info?.backupCaps & 2)) return;
op(async () => {
if (file.size > 600000) throw new Error("Backup file too large");
const { readBackup, restoreBackup } = await backupModule();
const archive = readBackup(await file.text()); assertSession(d);
if (!confirm(t("backupConfirm"))) return;
await restoreBackup((r, o) => sessionRequest(d, r, o), archive, backupProgress);
await load(d); sayK("backupRestored");
});
});
async function readMotion(d = dev) {
assertSession(d);
if (!d.info.motionMax) { $("motion-panel").hidden = true; return; }
const selected = d.sel ?? 0;
const m = parse[CMD.MOTION](await sessionRequest(d, req.motion(selected, d.info.locks ? 7 : 0, {}, d.info.ntrk || 1)));
if (m.rc || m.track !== selected) throw new Error("Invalid motion state"); /* ((Skiff W1) with the kinds: a lock stays one) */
d.motion = m; renderMotion();
}
function renderMotion() {
const d = dev, m = d?.motion;
$("motion-panel").hidden = !d?.info?.motionMax;
if (!m) return;
$("motion-on").checked = m.on;
$("motion-count").textContent = `${m.count} / ${m.max}`;
$("motion-clear").disabled = !m.count;
const rows = $("motion-rows");
if (rows.contains(document.activeElement)) return;
rows.replaceChildren(el("tr", {}, ...(m.kinds ? ["motionKind"] : []).concat(["motionStep", "motionParam", "motionValue"]).map(k => el("th", {text:t(k)})), el("th")),
...m.events.map(e => {
const desc = d.pdesc[e.param], label = desc?.label || `P${e.param}`;
const value = el("input", {type:"number",min:desc?.min ?? -8192,max:desc?.max ?? 8191,value:e.value,"aria-label":`${e.step + 1} ${label}`});
value.addEventListener("change", () => op(async () => {
assertSession(d);
const r = parse[CMD.MOTION](await sessionRequest(d, req.motion(m.track, e.lock ? 5 : 3, {...e,value:+value.value}, d.info.ntrk || 1)));
if (r.rc) throw new Error("Automation edit refused"); /* ((Skiff W1) a lock edited as a lock: op 5) */
await readMotion(d);
}));
return el("tr", {}, ...(m.kinds ? [el("td", {text:t(e.lock ? "motionLock" : "motionAuto")})] : []),
el("td", {text:e.step + 1}), el("td", {text:label}), el("td", {}, value),
el("td", {}, el("button", {text:t("remove"),onclick:() => op(async () => {
if (!confirm(t("motionRemoveConfirm").replace("%s", `${e.step + 1} ${label}`))) return; /* ((Skiff W1) asked first) */
const r = parse[CMD.MOTION](await sessionRequest(d, req.motion(m.track, 4, e, d.info.ntrk || 1)));
if (r.rc) throw new Error("Automation edit refused");
await readMotion(d);
})})));
}));
}
$("motion-on").addEventListener("change", () => op(async () => {
const d = dev, track = d?.sel ?? 0;
if (!d?.info?.motionMax) return;
const r = parse[CMD.MOTION](await sessionRequest(d, req.motion(track, 1, {on:$("motion-on").checked}, d.info.ntrk || 1)));
if (r.rc) throw new Error("Automation edit refused"); await readMotion(d);
}));
$("motion-clear").addEventListener("click", () => op(async () => {
const d = dev;
if (!d?.info?.motionMax || !confirm(t("motionConfirm"))) return;
const r = parse[CMD.MOTION](await sessionRequest(d, req.motion(d.sel ?? 0, 2, {}, d.info.ntrk || 1)));
if (r.rc) throw new Error("Automation edit refused"); await readMotion(d);
}));
setInterval(async () => {
const d = dev;
if (!d?.info?.motionMax || busy || document.hidden || tab !== "sequencer" || !d.link.idle) return;
const release = beginBusy();
try { await readMotion(d); } catch (e) { report(e); } finally { release(); }
}, 1500);
/* ---------------------------------------------------------- steps --- */
const TIMES = ["NOTE", "TIE", "REST"];
function renderStepHead() { if (dev && dev.steps.length) renderSteps(); }
const stepLen = () => Math.max(1, Math.min(dev.info.nstep, dev.dump.p[pSlen()] || 16));
/* a step's notes as text */
const stepNotes = (s) => s.notes.slice(0, s.n).map(noteName).join(" ");
const stepOn = (s) => !!s && s.time === 0 && (s.n > 0 || (s.hit | 0) > 0);
function renderSteps() {
if (!dev || !dev.steps.length) return;
const len = stepLen();
const box = $("steptables");
const shape = String(len);
$("noteshelp").textContent = t("notesHelp");
renderGrid();
/* keep the rows the user is typing in */
if (box.contains(document.activeElement) && box.dataset.len === shape) { updateStepRows(); return; }
box.dataset.len = shape;
const tables = [];
for (let b = 0; b < len; b += 16) {
const tb = el("table", {}, el("tr", {}, el("th"), el("th", { text: t("notes") }), el("th", { text: t("hits") }), el("th", { text: t("time") }),
el("th", { text: t("acc") }), el("th", { text: t("slide") }), el("th", { text: t("vel") }), ...(dev.info.chance ? [el("th", { text: t("chance") })] : []),
...(dev.info.ratchet ? [el("th", { text: t("ratchet") })] : []),
...(dev.info.stepx ? [el("th", { text: t("flam") }), el("th", { text: t("cond") }), el("th", { text: t("nudge") })] : [])));
for (let i = b; i < Math.min(len, b + 16); i++) tb.append(stepRow(i));
tables.push(tb);
}
box.replaceChildren(...tables);
}
function stepRow(i) {
const lab = (k) => ({ "aria-label": `${t(k)} ${i + 1}` }); /* ((Skiff W6) each named, with its step) */
const notes = el("input", { type: "text", placeholder: "—", spellcheck: "false", ...lab("notes") });
const hits = el("input", { type: "text", placeholder: "—", spellcheck: "false", class: "hits", ...lab("hits") });
const time = el("select", lab("time"), ...TIMES.map((n, k) => el("option", { value: k, text: n })));
const acc = el("input", { type: "checkbox", ...lab("acc") });
const sl = el("input", { type: "checkbox", ...lab("slide") });
const vel = el("input", { type: "number", min: 0, max: 127, ...lab("vel") });
const chance = dev.info.chance ? el("input", { type: "number", min: 0, max: 100, "aria-label": `${t("chance")} ${i + 1}` }) : null;
const ratchet = dev.info.ratchet ? el("select", { "aria-label": `${t("ratchet")} ${i + 1}` },
...Array.from({ length: dev.info.ratchet }, (_, k) => el("option", { value: k + 1, text: `x${k + 1}` }))) : null;
const sx = !!(dev.info.stepx && chance && ratchet); /* (Skiff W1) a step's FLAM, COND, NUDGE */
const flam = sx ? el("input", { type: "checkbox", "aria-label": `${t("flam")} ${i + 1}` }) : null;
const cond = sx ? el("select", { "aria-label": `${t("cond")} ${i + 1}` }, ...TC_NAMES.map((n, k) => el("option", { value: k, text: n }))) : null;
const nudge = sx ? el("input", { type: "number", min: -32, max: 31, "aria-label": `${t("nudge")} ${i + 1}` }) : null;
const tr = el("tr", { "data-i": i }, el("td", { class: "i", text: String(i + 1) }),
el("td", {}, notes), el("td", {}, hits), el("td", {}, time), el("td", {}, acc), el("td", {}, sl), el("td", {}, vel), ...(chance ? [el("td", {}, chance)] : []),
...(ratchet ? [el("td", {}, ratchet)] : []), ...(sx ? [el("td", {}, flam), el("td", {}, cond), el("td", {}, nudge)] : []));
tr._c = { notes, hits, time, acc, sl, vel, chance, ratchet, flam, cond, nudge };
fillStep(tr, dev.steps[i]);
const send = () => writeStep(i, tr);
notes.addEventListener("change", send);
hits.addEventListener("change", send);
time.addEventListener("change", send);
acc.addEventListener("change", send);
sl.addEventListener("change", send);
vel.addEventListener("change", send);
if (chance) chance.addEventListener("change", send);
if (ratchet) ratchet.addEventListener("change", send);
for (const x of [flam, cond, nudge]) if (x) x.addEventListener("change", send);
return tr;
}
function fillStep(tr, s) {
const c = tr._c;
if (!s) return;
c.notes.value = stepNotes(s);
c.notes.classList.remove("bad");
c.hits.value = hitsText(s.hit | 0, s.acc | 0);
c.hits.classList.remove("bad");
c.time.value = String(s.time);
c.acc.checked = !!(s.flags & 1);
c.sl.checked = !!(s.flags & 2);
c.vel.value = String(s.vel);
if (c.chance) c.chance.value = String(s.chance ?? 100);
if (c.ratchet) c.ratchet.value = String(s.ratchet ?? 1);
if (c.cond) { c.flam.checked = !!s.flam; c.cond.value = String(s.cond | 0); c.nudge.value = String(s.nudge | 0); }
tr.classList.toggle("off", !stepOn(s));
}
function updateStepRows() {
for (const tr of $("steptables").querySelectorAll("tr[data-i]")) {
if (tr.contains(document.activeElement)) continue;
fillStep(tr, dev.steps[+tr.dataset.i]);
}
renderGrid();
}
/* the step grid: one cell per step up to LEN; a cell jumps to its row in the table */
function renderGrid() {
const box = $("stepgrid");
if (!dev || !dev.steps.length) { box.replaceChildren(); return; }
const len = stepLen();
if (box.children.length !== len) {
box.replaceChildren(...Array.from({ length: len }, (_, i) => el("button", { type: "button", "data-i": i, onclick: () => focusStep(i) })));
}
for (const b of box.children) {
const i = +b.dataset.i, s = dev.steps[i];
const on = stepOn(s), tie = !!s && s.time === 1;
const txt = on ? [stepNotes(s), hitsText(s.hit | 0, s.acc | 0)].filter(Boolean).join(" ") : tie ? "—" : "";
const marks = s && on ? (s.flags & 1 ? " >" : "") + (s.flags & 2 ? " ~" : "") + (s.ratchet > 1 ? " x" + s.ratchet : "") +
(s.flam ? " f" : "") + (s.cond ? " " + TC_NAMES[s.cond] : "") + (s.nudge ? " " + (s.nudge > 0 ? "+" : "") + s.nudge : "") : "";
b.className = [on && "on", tie && "tie", on && s.flags & 1 && "acc", i % 4 === 0 && "beat"].filter(Boolean).join(" ");
b.title = `${i + 1}: ${on ? txt : tie ? "TIE" : "REST"}${marks}`;
b.replaceChildren(el("span", { class: "n", text: String(i + 1) + marks }), el("span", { class: "x", text: txt }));
}
}
function focusStep(i) {
const tr = $("steptables").querySelector(`tr[data-i="${i}"]`);
if (!tr) return;
tr.scrollIntoView({ block: "center", behavior: "smooth" });
tr._c.notes.focus({ preventScroll: true });
tr.classList.add("hl");
setTimeout(() => tr.classList.remove("hl"), 1200);
}
async function writeStep(i, tr) {
const c = tr._c;
const notes = parseNotes(c.notes.value), hits = parseHits(c.hits.value);
c.notes.classList.toggle("bad", !notes);
c.hits.classList.toggle("bad", !hits);
if (!notes || !hits) return;
const old = dev.steps[i];
const all = notes.concat(old.notes.slice(notes.length)).slice(0, 4);
let time = +c.time.value;
if ((notes.length || hits.hit) && !old.n && !old.hit && time === 2) time = 0; /* typing notes / hits into an empty step makes it play */
const s = { n: notes.length, notes: all, time, flags: (c.acc.checked ? 1 : 0) | (c.sl.checked ? 2 : 0),
vel: Math.max(0, Math.min(127, +c.vel.value || 0)), hit: hits.hit, acc: hits.acc };
if (c.chance) s.chance = Math.max(0, Math.min(100, Math.round(+c.chance.value || 0)));
if (c.ratchet && c.chance) s.ratchet = Math.max(1, Math.min(4, +c.ratchet.value || 1));
if (c.cond) { s.flam = c.flam.checked; s.cond = +c.cond.value || 0; s.nudge = Math.max(-32, Math.min(31, Math.round(+c.nudge.value || 0))); }
if ((s.n || s.hit) && !s.vel) s.vel = 96;
stepEdit.set(i, performance.now());
try {
dev.steps[i] = parse[CMD.STEP_SET](await rq(req.stepSet(i, s)));
if (!tr.contains(document.activeElement) || document.activeElement === c.notes) fillStep(tr, dev.steps[i]);
} catch (err) { report(err); }
}
$("reloadsteps").addEventListener("click", async () => {
if (!dev) return;
const releaseBusy = beginBusy();
try { await loadSteps(); sayK("ready"); } catch (err) { report(err); } finally { releaseBusy(); }
});
$("clearseq").addEventListener("click", async () => {
if (!dev || !confirm(t("confirmClear"))) return;
const releaseBusy = beginBusy();
try {
for (let i = 0; i < dev.info.nstep; i++) {
if (i % 8 === 0) sayK("applying", `${i}/${dev.info.nstep}`);
dev.steps[i] = parse[CMD.STEP_SET](await rq(req.stepSet(i, { n: 0, notes: [0, 0, 0, 0], time: 2, flags: 0, vel: 0, hit: 0, acc: 0, ...(dev.info.chance ? {chance:100} : {}), ...(dev.info.ratchet ? {ratchet:1} : {}),
...(dev.info.stepx ? {flam:0, cond:0, nudge:0} : {}) }))); /* ((Skiff W1) no COND or NUDGE left hidden) */
}
if (dev.info.motionMax) { dev.motion = parse[CMD.MOTION](await rq(req.motion(dev.sel ?? 0, 2, {}, dev.info.ntrk || 1))); renderMotion(); }
$("steptables").dataset.len = "";
renderSteps();
sayK("ready");
} catch (err) { report(err); } finally { releaseBusy(); }
});
/* ---------------------------------------------------------- samples --- */
const smpDraft = [0, 1, 2].map(() => ({ name: "", files: [] }));
let smpBusy = false;
const SMP_RC = { 1: "size", 2: "header", 3: "data CRC", 4: "flash", 5: "zones" };
const kib = (n) => (n / 1024).toFixed(1);
/* auto key split, as in buildSlot (for the preview) */
function splitKeys(files) {
const z = files.map((f, i) => ({ i, root: f.root })).sort((a, b) => a.root - b.root);
const out = [];
z.forEach((x, j) => {
out[x.i] = [j === 0 ? 0 : Math.floor((z[j - 1].root + x.root) / 2) + 1, j === z.length - 1 ? 127 : Math.floor((x.root + z[j + 1].root) / 2)];
});
return out;
}
const draftBytes = (d) => d.files.reduce((a, f) => a + ((f.s.length + 1) >> 1), 0);
async function decodeFile(f) {
const buf = await f.arrayBuffer();
let x;
try {
const w = parseWav(buf);
x = resample(w.x, w.sr, SMP.RATE);
} catch (e) { /* not a plain WAV: let the browser decode it */
const Ctx = window.OfflineAudioContext || window.webkitOfflineAudioContext;
const ab = await new Ctx(1, 1, SMP.RATE).decodeAudioData(buf.slice(0));
x = new Float64Array(ab.length);
for (let c = 0; c < ab.numberOfChannels; c++) { const d = ab.getChannelData(c); for (let i = 0; i < d.length; i++) x[i] += d[i] / ab.numberOfChannels; }
}
if (!x.length) throw new Error("no audio");
const raw = Float64Array.from(x); /* kept for trimming: s is raw[a, b) (takeSample) */
return { fname: f.name, raw, a: 0, b: raw.length, s: takeSample(raw, 0, raw.length),
root: rootFromName(f.name.replace(/\.[^.]*$/, "")) };
}
/* ---- recording: the computer's input (getUserMedia, no echo cancelling / noise suppression / AGC),
* raw PCM through an AudioWorklet, mixed to mono; it stops by itself when the slot is full */
const REC_WORKLET = `registerProcessor("felucca-rec", class extends AudioWorkletProcessor {
process(inputs) {
const i = inputs[0];
if (i && i.length && i[0].length) {
const n = i[0].length, m = new Float32Array(n);
for (let c = 0; c < i.length; c++) for (let k = 0; k < n; k++) m[k] += i[c][k] / i.length;
this.port.postMessage(m, [m.buffer]);
}
return true;
}
});`;
let rec = null; /* the recording: { k, ctx, stream, chunks, n, max, peak } */
let recDevice = "", recInputs = []; /* the chosen input (deviceId, "" = default), the inputs */
async function listInputs() {
try { recInputs = (await navigator.mediaDevices.enumerateDevices()).filter((d) => d.kind === "audioinput"); }
catch (e) { recInputs = []; }
}
let recStarting = false, recEpoch = 0; /* cancel a pending permission / worklet on leave */
const recActive = () => !!rec || recStarting; /* the draft must not change: Upload, files, trims off */
async function recStart(k) {
const d = smpDraft[k], left = SMP.MAX_DATA - draftBytes(d); /* bytes: two samples each */
if (!dev || tab !== "samples" || rec || recStarting || smpBusy) return;
const session = dev, epoch = ++recEpoch;
const current = () => epoch === recEpoch && dev === session && tab === "samples";
const check = () => { if (!current()) throw new Error("closed"); };
if (left < 1024 || d.files.length >= SMP.MAX_ZONES) { sayK("recFull"); return; }
let stream = null, ctx = null;
recStarting = true;
renderSamples(); /* (the controls go off during the prompt) */
try {
stream = await navigator.mediaDevices.getUserMedia({ audio: {
deviceId: recDevice ? { exact: recDevice } : undefined,
echoCancellation: false, noiseSuppression: false, autoGainControl: false } });
check();
ctx = new AudioContext();
await ctx.resume(); /* (made after the permission prompt: it may start suspended) */
check();
const url = URL.createObjectURL(new Blob([REC_WORKLET], { type: "text/javascript" }));
try { await ctx.audioWorklet.addModule(url); } finally { URL.revokeObjectURL(url); }
check();
const node = new AudioWorkletNode(ctx, "felucca-rec"), mute = ctx.createGain();
mute.gain.value = 0; /* pulled by the graph, but nothing is heard */
ctx.createMediaStreamSource(stream).connect(node).connect(mute).connect(ctx.destination);
rec = { k, ctx, stream, chunks: [], n: 0, max: Math.floor(left * 2 * ctx.sampleRate / SMP.RATE), peak: 0 };
node.port.onmessage = (e) => {
const r = rec;
if (!r || r.ctx !== ctx || r.stopping) return;
const chunk = e.data.subarray(0, Math.max(0, r.max - r.n));
r.chunks.push(chunk);
r.n += chunk.length;
for (const v of e.data) r.peak = Math.max(r.peak, Math.abs(v));
if (r.n >= r.max) recStop();
};
await listInputs(); /* the labels come with the permission */
check();
recStarting = false;
renderSamples();
requestAnimationFrame(recTick);
} catch (e) { /* nothing stays open: the input, the context */
if (epoch === recEpoch) recStarting = false;
if (rec && rec.ctx === ctx) rec = null;
if (stream) stream.getTracks().forEach((tr) => tr.stop());
if (ctx) ctx.close().catch(() => {});
if (e.message !== "closed" && current()) sayK("recDenied", ": " + e.message);
renderSamples();
}
}
/* the time and the level while recording (no re-render) */
function recTick() {
if (!rec) return;
const box = $("smpslots").querySelector(`[data-k="${rec.k}"]`);
const lv = box && box.querySelector("progress.rec"), tm = box && box.querySelector(".rectime");
if (lv) lv.value = Math.min(1, rec.peak);
if (tm) tm.textContent = `${(rec.n / rec.ctx.sampleRate).toFixed(1)} / ${(rec.max / rec.ctx.sampleRate).toFixed(1)} s`;
rec.peak *= 0.8;
requestAnimationFrame(recTick);
}
/* rec stays set (stopping) until the recording is in the draft: Upload and Record stay off meanwhile */
async function recStop() {
const r = rec;
if (!r || r.stopping) return;
r.stopping = true;
r.stream.getTracks().forEach((tr) => tr.stop());
await r.ctx.close().catch(() => {});
if (rec === r) rec = null;
const x = new Float64Array(Math.min(r.n, r.max));
let o = 0;
for (const c of r.chunks) {
const n = Math.min(c.length, x.length - o);
x.set(c.subarray(0, n), o);
o += n;
}
const raw = Float64Array.from(resample(x, r.ctx.sampleRate, SMP.RATE));
const d = smpDraft[r.k];
let pk = 0;
for (const v of raw) pk = Math.max(pk, Math.abs(v));
if (pk < 1e-4) { /* nothing came in: a muted or wrong input */
sayK("recSilent");
renderSamples();
return;
}
if (raw.length > 1 && d.files.length < SMP.MAX_ZONES) {
const [a, b] = autoTrim(raw);
d.files.push({ fname: `REC ${d.files.length + 1}`, raw, a, b, s: takeSample(raw, a, b), root: 60 });
if (!d.name) d.name = "REC";
}
renderSamples();
}
/* ---- trimming: the waveform of raw with its two ends, dragged with a pointer; the wheel zooms
* (at the pointer); zoomed in, a drag away from the ends (or shift + wheel) moves the view; a double
* click shows it all. The view, [v0, v1)
* of raw, is kept in the file (the list is drawn again after every trim). */
function drawTrim(cv, f) {
const w = cv.width, h = cv.height - 4, g = cv.getContext("2d"), cs = getComputedStyle(cv);
const fg = cs.getPropertyValue("--fg").trim() || "#000", line = cs.getPropertyValue("--line").trim() || "#ccc";
const n = f.raw.length, v0 = f.v0 ?? 0, v1 = f.v1 ?? n, span = v1 - v0;
const xa = (f.a - v0) / span * w, xb = (f.b - v0) / span * w;
if (f.pk === undefined) { /* raw never changes: its peak, once */
f.pk = 1e-9;
for (const v of f.raw) f.pk = Math.max(f.pk, Math.abs(v));
}
const pk = f.pk;
g.clearRect(0, 0, w, cv.height);
for (let x = 0; x < w; x++) { /* per column: the smallest and largest sample */
const i0 = v0 + Math.floor(x / w * span), i1 = Math.max(i0 + 1, v0 + Math.floor((x + 1) / w * span));
let lo = 0, hi = 0;
for (let i = i0; i < i1 && i < n; i++) { lo = Math.min(lo, f.raw[i]); hi = Math.max(hi, f.raw[i]); }
g.fillStyle = x >= xa && x < xb ? fg : line;
g.fillRect(x, h / 2 - hi / pk * (h / 2 - 2), 1, Math.max(1, (hi - lo) / pk * (h / 2 - 2)));
}
g.fillStyle = fg;
if (xa >= 0 && xa <= w) g.fillRect(Math.min(w - 2, xa), 0, 2, h);
if (xb >= 0 && xb <= w) g.fillRect(Math.max(0, xb - 2), 0, 2, h);
g.fillStyle = line; /* where the view is in the whole */
g.fillRect(0, cv.height - 2, w, 2);
g.fillStyle = fg;
g.fillRect(v0 / n * w, cv.height - 3, Math.max(3, span / n * w), 3);
}
function trimCanvas(f) {
const cv = el("canvas", { class: "trim", width: 600, height: 60, title: t("trim") });
let end = null; /* "a" or "b": the end being dragged */
const frac = (e) => { const r = cv.getBoundingClientRect(); return Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)); };
const at = (e) => {
const v0 = f.v0 ?? 0, v1 = f.v1 ?? f.raw.length;
return Math.round(v0 + frac(e) * (v1 - v0));
};
cv.addEventListener("wheel", (e) => {
e.preventDefault();
const v = [f.v0 ?? 0, f.v1 ?? f.raw.length];
const d = e.deltaY || e.deltaX;
if (!d) return;
[f.v0, f.v1] = e.shiftKey || (!e.deltaY && e.deltaX)
? zoomView(f.raw.length, v[0], v[1], frac(e), 1, (d > 0 ? 0.1 : -0.1))
: zoomView(f.raw.length, v[0], v[1], frac(e), d > 0 ? 1.25 : 0.8, 0);
drawTrim(cv, f);
}, { passive: false });
cv.addEventListener("dblclick", () => { f.v0 = 0; f.v1 = f.raw.length; drawTrim(cv, f); });
/* a press within GRAB px of an end drags that end; elsewhere it drags the view (zoomed), or moves
* the nearer end (the whole input shown: nothing to scroll) */
const GRAB = 10;
let pan = null; /* dragging the view: { x, v0, span } */
const zoomed = () => (f.v1 ?? f.raw.length) - (f.v0 ?? 0) < f.raw.length;
const near = (e) => { /* the end within GRAB px of the pointer, or null */
const r = cv.getBoundingClientRect(), v0 = f.v0 ?? 0, span = (f.v1 ?? f.raw.length) - v0;
const da = Math.abs(e.clientX - (r.left + (f.a - v0) / span * r.width));
const db = Math.abs(e.clientX - (r.left + (f.b - v0) / span * r.width));
return Math.min(da, db) > GRAB ? null : da <= db ? "a" : "b";
};
cv.addEventListener("pointerdown", (e) => {
if (smpBusy || recActive() || e.button !== 0 || !e.isPrimary || end || pan) return; /* one primary pointer */
const p = at(e);
end = near(e);
if (!end && zoomed()) {
pan = { x: e.clientX, v0: f.v0 ?? 0, span: (f.v1 ?? f.raw.length) - (f.v0 ?? 0) };
cv.style.cursor = "grabbing";
cv.setPointerCapture(e.pointerId);
return;
}
end = end || (Math.abs(p - f.a) <= Math.abs(p - f.b) ? "a" : "b");
cv.setPointerCapture(e.pointerId);
cv.dispatchEvent(new PointerEvent("pointermove", e));
});
cv.addEventListener("pointermove", (e) => {
if (pan) {
const r = cv.getBoundingClientRect();
const a = Math.round(pan.v0 - (e.clientX - pan.x) / r.width * pan.span);
f.v0 = Math.max(0, Math.min(f.raw.length - pan.span, a));
f.v1 = f.v0 + pan.span;
drawTrim(cv, f);
return;
}
if (!end) { /* hovering: what a press would do */
cv.style.cursor = near(e) || !zoomed() ? "ew-resize" : "grab";
return;
}
const p = at(e), min = Math.round(SMP.RATE * 0.01); /* at least 10 ms */
if (end === "a") f.a = Math.max(0, Math.min(p, f.b - min));
else f.b = Math.min(f.raw.length, Math.max(p, f.a + min));
drawTrim(cv, f);
});
const done = () => {
if (pan) { /* the view moved: nothing else changes */
pan = null;
cv.style.cursor = "grab";
return;
}
if (!end) return;
end = null;
f.s = takeSample(f.raw, f.a, f.b);
renderSamples(); /* the length and the slot size change */
};
cv.addEventListener("pointerup", done);
cv.addEventListener("pointercancel", done);
requestAnimationFrame(() => drawTrim(cv, f)); /* (once it is in the page: its colours) */
return cv;
}
/* leaving the Samples tab or disconnecting: a recording is stopped (it stays in the draft), the
* preview stops and its audio context closes */
function samplesLeave() {
++recEpoch;
recStarting = false;
if (rec) recStop();
if (previewSrc) try { previewSrc.stop(); } catch (e) { /* already ended */ }
previewSrc = null;
if (previewCtx) previewCtx.close().catch(() => {});
previewCtx = null;
}
/* play the trimmed sample as it will be stored (22050 Hz) */
let previewSrc = null, previewCtx = null;
function preview(f) {
try {
if (previewSrc) previewSrc.stop();
previewCtx = previewCtx || new AudioContext();
previewCtx.resume().catch(() => {});
const buf = previewCtx.createBuffer(1, f.s.length, SMP.RATE), ch = buf.getChannelData(0);
for (let i = 0; i < f.s.length; i++) ch[i] = f.s[i] / 32768;
previewSrc = previewCtx.createBufferSource();
previewSrc.buffer = buf;
previewSrc.connect(previewCtx.destination);
previewSrc.start();
} catch (e) { /* no audio output: nothing to play */ }
}
async function addFiles(k, list) {
const d = smpDraft[k];
for (const f of list) {
try {
const z = await decodeFile(f);
if (d.files.length >= SMP.MAX_ZONES) break;
d.files.push(z);
if (!d.name) d.name = f.name.replace(/\.[^.]*$/, "").toUpperCase().replace(/[^\x20-\x7E]/g, "").slice(0, 8);
} catch (e) { sayK("smpDecodeFail", `${f.name} (${e.message})`); }
}
renderSamples();
}
/* a slot's recording row: Record / Stop, the input, the time and the level */
function recRow(k) {
const on = rec && rec.k === k;
const sel = el("select", { title: t("recInput"), disabled: !!rec },
el("option", { value: "", text: t("recInput") }),
...recInputs.map((d, i) => el("option", { value: d.deviceId, text: d.label || `${t("recInput")} ${i + 1}` })));
sel.value = recDevice;
sel.addEventListener("change", () => { recDevice = sel.value; });
return el("div", { class: "head" },
el("button", { ic: on ? "control_stop_f" : "control_rec_f", disabled: smpBusy || recStarting || (!!rec && (!on || rec.stopping)),
onclick: () => (on ? recStop() : recStart(k)) }, t(on ? "stopRec" : "record")),
recInputs.length ? sel : "",
on ? el("progress", { class: "rec", max: 1, value: 0 }) : "",
on ? el("span", { class: "rectime dim" }) : "");
}
function renderSamples() {
const box = $("smpslots"); /* the tab says when there are no slots (renderPanels) */
if (!dev || !dev.smp) { box.replaceChildren(); return; }
const max = SMP.MAX_DATA;
box.replaceChildren(...dev.smp.slots.map((u, k) => {
const d = smpDraft[k];
const status = u.zones ? `${u.name || "—"}, ${u.zones} ${t("zones")}, ${u.kib} KiB` : t("empty");
const bar = el("progress", { max: dev.smp.slotKiB, value: u.kib, title: `${u.kib} / ${dev.smp.slotKiB} KiB` });
const file = el("input", { type: "file", accept: ".wav,audio/wav,audio/x-wav,audio/*", multiple: true, hidden: true });
file.addEventListener("change", () => { addFiles(k, [...file.files]); file.value = ""; });
const name = el("input", { type: "text", class: "name", maxlength: 8, value: d.name, spellcheck: "false", placeholder: "NAME" });
name.addEventListener("input", () => {
const v = name.value.toUpperCase().replace(/[^\x20-\x7E]/g, "").slice(0, 8);
if (v !== name.value) name.value = v;
d.name = v;
});
const bytes = draftBytes(d), tooBig = bytes > max;
const size = el("span", { class: tooBig ? "bad" : "dim",
text: d.files.length ? `${kib(bytes)} / ${kib(max)} KiB` + (tooBig ? " " + t("smpTooBig") : "") : "" });
const prog = el("progress", { max: 1, value: 0, hidden: true });
const blk = el("div", { class: "smp", "data-k": k },
el("div", { class: "head" }, el("b", { text: `USR${k + 1}` }), el("span", { text: status }), bar,
el("button", { ic: "symbol_trash", disabled: smpBusy || !u.zones, onclick: () => smpErase(k) }, t("erase"))),
el("div", { class: "head" }, el("span", { text: t("smpName") }), name,
el("button", { ic: "symbol_folder_open", disabled: smpBusy || recActive(), onclick: () => file.click() }, t("chooseFiles")), file,
el("button", { ic: "symbol_upload", disabled: smpBusy || recActive() || !d.files.length || tooBig || !d.name, onclick: () => smpUpload(k, prog) }, t("upload")),
d.files.length ? el("button", { text: t("clearList"), disabled: smpBusy || recActive(), onclick: () => { d.files = []; renderSamples(); } }) : "",
size, prog),
recRow(k));
if (d.files.length) {
const keys = splitKeys(d.files);
const tb = el("table", {}, el("tr", {}, el("th", { text: t("file") }), el("th", { text: t("root") }),
el("th", { text: t("keys") }), el("th", { text: t("length") }), el("th")));
d.files.forEach((f, i) => {
const root = el("input", { type: "text", class: "root", value: noteName(f.root), spellcheck: "false" });
root.addEventListener("change", () => {
const n = parseNote(root.value.trim());
if (n == null) { root.classList.add("bad"); return; }
f.root = n;
renderSamples();
});
tb.append(el("tr", {}, el("td", { text: f.fname }), el("td", {}, root),
el("td", { text: `${noteName(keys[i][0])}–${noteName(keys[i][1])}` }),
el("td", { text: `${(f.s.length / SMP.RATE).toFixed(2)} s` }),
el("td", {}, el("button", { text: t("remove"), disabled: smpBusy || recActive(), onclick: () => { d.files.splice(i, 1); renderSamples(); } }))));
if (f.raw) /* the waveform: drag its ends to trim */
tb.append(el("tr", { class: "trimrow" }, el("td", { colspan: 4 }, trimCanvas(f)),
el("td", {},
el("button", { text: t("preview"), onclick: () => preview(f) }),
el("button", { text: t("autoTrim"), disabled: smpBusy || recActive(), onclick: () => {
[f.a, f.b] = autoTrim(f.raw);
f.s = takeSample(f.raw, f.a, f.b);
renderSamples();
} }))));
});
blk.append(tb);
}
blk.addEventListener("dragover", (e) => { e.preventDefault(); blk.classList.add("over"); });
blk.addEventListener("dragleave", () => blk.classList.remove("over"));
blk.addEventListener("drop", (e) => {
e.preventDefault();
blk.classList.remove("over");
if (!smpBusy && !recActive() && e.dataTransfer.files.length) addFiles(k, [...e.dataTransfer.files]); /* (the recording sized itself to the slot) */
});
return blk;
}));
}
async function smpInfo(d = dev) { d.smp = parse[CMD.SMP_INFO](await sessionRequest(d, req.smpInfo())); }
async function smpUpload(k, prog) {
const d = smpDraft[k];
let built;
try { built = buildSlot(d.name, d.files.map((f) => ({ s: f.s, root: f.root }))); }
catch (e) { sayK("smpFail", e.message); return; }
if (!confirm(t("confirmUpload").replace("{n}", k + 1))) return;
const { hdr, data } = built;
const session = dev;
const releaseBusy = beginBusy();
smpBusy = true;
renderSamples();
prog = $("smpslots").querySelector(`[data-k="${k}"] progress[max="1"]`);
prog.hidden = false;
try {
const t0 = performance.now();
let r = parse[CMD.SMP_BEGIN](await rq(req.smpBegin(k), { timeout: 1000, retries: 0 }));
if (r.rc) throw new Error("begin rc " + r.rc);
for (let off = 0; off < data.length; off += 256) {
const a = SMP.DATA_OFF + off;
const w = parse[CMD.SMP_WRITE](await rq(req.smpWrite(k, a, data.subarray(off, off + 256)), { timeout: 1000, retries: 1 }));
if (w.rc) throw new Error(`write at 0x${a.toString(16)} rc ${w.rc}`);
prog.value = (off + 256) / data.length;
sayK("smpUploading", `${k + 1} ${kib(Math.min(data.length, off + 256))} / ${kib(data.length)} KiB`);
}
r = parse[CMD.SMP_END](await rq(req.smpEnd(k, hdr), { timeout: 2000, retries: 0 }));
if (r.rc) throw new Error(`end rc ${r.rc} (${SMP_RC[r.rc] || "?"})`);
sayK("smpDone", `${k + 1} ${((performance.now() - t0) / 1000).toFixed(1)} s`);
} catch (e) {
if (e.message !== "closed") sayK("smpFail", e.message);
} finally {
try { if (session === dev) await smpInfo(session); } catch (e) { /* shown by the next action */ }
smpBusy = false;
releaseBusy();
renderSamples();
}
}
async function smpErase(k) {
if (!dev || !confirm(t("confirmErase").replace("{n}", k + 1))) return;
const session = dev;
const releaseBusy = beginBusy();
smpBusy = true;
renderSamples();
try {
const r = parse[CMD.SMP_ERASE](await rq(req.smpErase(k), { timeout: 2500, retries: 0 }));
if (r.rc) throw new Error("erase rc " + r.rc);
sayK("smpErased", String(k + 1));
} catch (e) {
if (e.message !== "closed") sayK("smpFail", e.message);
} finally {
try { if (session === dev) await smpInfo(session); } catch (e) { /* ignore */ }
smpBusy = false;
releaseBusy();
renderSamples();
}
}
/* ---------------------------------------------------------- mixer (v3) --- */
/* dev.mix = TRACK reply + pan per track ({sel, ntrk, tracks: [{engine, preset, level, mute, armed, pan}]}).
Read on connect, after every RELOAD / sound change, with the slow safety DUMP and when the tab opens.
The selected track's level / pan / mute are also Sound parameters: both views follow each other. */
let mixDrag = null; /* "lv:i" / "pan:i" while a strip control is dragged */
const mixEdit = new Map(); /* "lv:i" / "pan:i" -> time of the user's last change */
const mixCtl = []; /* per track: the strip's elements */
let panning = false; /* v3 firmware: another track is selected for a moment (pan of a track that is not selected) */
const mixTouched = (kind, i) => mixDrag === `${kind}:${i}` || performance.now() - (mixEdit.get(`${kind}:${i}`) || 0) < 600
|| (!!dev && kind === "lv" && dev.link.hasQueued("mix:" + i))
|| (kind === "pan" && (panWant.has(i) || (!!dev && dev.link.hasQueued("pan:" + i))));
function trackName(x) {
return [dev.info.engines[x.engine], (dev.names[x.engine] || [])[x.preset]].filter(Boolean).join(" ");
}
async function readMixer(d = dev, full = tab === "tracks") {
assertSession(d);
if (!d || !hasTracks()) return; /* ((Skiff W7) the pans whole only for the Mixer tab: a track's own, no sound load moves one) */
const m = await mixer.read((r, o) => sessionRequest(d, r, o), d.info, { pan: pPan(), rev: pRev() }, full || !d.mix ? null : d.mix.tracks);
if (d !== dev) return;
if (d.mix) m.tracks.forEach((x, i) => { /* what the user is moving stays */
const o = d.mix.tracks[i];
if (!o) return;
if (mixTouched("lv", i)) { x.level = o.level; x.mute = o.mute; }
if (mixTouched("pan", i)) x.pan = o.pan;
if (mixTouched("rev", i)) x.rev = o.rev;
});
d.mix = m;
if (m.sel !== d.sel && !panning) { d.sel = m.sel; needReload = true; } /* selected on the device, push missed */
renderMixer();
}
/* the Sound view's values of the selected track -> the strips */
function mixFromDump() {
if (!dev || !dev.mix || !dev.dump || panning) return;
const m = dev.mix, x = m.tracks[dev.sel];
if (x) {
if (!mixTouched("lv", dev.sel)) {
x.level = dev.dump.p[P.LEVEL];
x.mute = dev.dump.p[pMute()] ? 1 : 0;
}
if (!mixTouched("pan", dev.sel)) x.pan = dev.dump.p[pPan()];
}
if (mixCtl.length === m.ntrk) m.tracks.forEach((_, i) => updateStrip(i));
}
/* a strip's values -> the Sound view (the selected track) */
function mixToSound(i) {
const x = dev.mix.tracks[i];
const put = (s, id, v) => { if (v == null) return; (s ? dev.dump.g : dev.dump.p)[id] = v; showValue(key(s, id), v, false); };
if (i !== dev.sel) return;
put(0, P.LEVEL, x.level);
put(0, pMute(), x.mute ? 1 : 0);
put(0, pPan(), x.pan);
}
function renderMixer() {
const box = $("mixer");
if (!dev || !dev.mix) { box.replaceChildren(); mixCtl.length = 0; return; }
const m = dev.mix;
if (mixCtl.length !== m.ntrk || box.dataset.lang !== lang) {
box.dataset.lang = lang;
mixCtl.length = 0;
box.replaceChildren(...m.tracks.map((_, i) => buildStrip(i)));
}
m.tracks.forEach((_, i) => updateStrip(i));
}
function buildStrip(i) {
const lvDesc = dev.pdesc[P.LEVEL] || { fmt: F.INT, min: 0, max: 127, def: 100 };
const pDesc = dev.pdesc[pPan()] || { fmt: F.BIPCT, min: -64, max: 63, def: 0 };
const fader = el("input", { type: "range", class: "fader", min: 0, max: 127, step: 1, "aria-label": `${t("level")} ${i + 1}` });
fader.addEventListener("pointerdown", () => { mixDrag = "lv:" + i; });
fader.addEventListener("input", () => setLevel(i, +fader.value));
fader.addEventListener("change", () => setLevel(i, +fader.value));
fader.addEventListener("dblclick", () => setLevel(i, Math.max(0, Math.min(127, lvDesc.def))));
const pan = el("input", { type: "range", class: "pan", min: pDesc.min, max: pDesc.max, step: 1, "aria-label": `${t("pan")} ${i + 1}` });
pan.addEventListener("pointerdown", () => { mixDrag = "pan:" + i; });
pan.addEventListener("input", () => setPan(i, +pan.value, false));
pan.addEventListener("change", () => setPan(i, +pan.value, true));
pan.addEventListener("dblclick", () => setPan(i, pDesc.def, true));
const rDesc = dev.pdesc[pRev()] || { fmt: F.PCT, min: 0, max: 127, def: 0 }; /* ((Skiff W3) REV) */
const rev = el("input", { type: "range", class: "pan", min: rDesc.min, max: rDesc.max, step: 1, "aria-label": `${t("rev")} ${i + 1}` });
rev.addEventListener("pointerdown", () => { mixDrag = "rev:" + i; });
rev.addEventListener("input", () => setRev(i, +rev.value, false));
rev.addEventListener("change", () => setRev(i, +rev.value, true));
rev.addEventListener("dblclick", () => setRev(i, rDesc.def, true));
const c = {
lvDesc, pDesc, rDesc, fader, pan, rev, revOut: el("span", { class: "v" }),
num: el("button", { type: "button", class: "tog num", title: t("selectTrack"), onclick: () => selectTrack(i) }, String(i + 1)),
snd: el("div", { class: "snd" }),
rec: el("span", { class: "rec", ic: "control_rec_f", title: t("rec") }, t("rec")),
lvOut: el("span", { class: "v lv" }),
mute: el("button", { type: "button", class: "tog", ic: "control_speaker_mute", onclick: () => setMute(i, !dev.mix.tracks[i].mute) }, t("mute")),
panOut: el("span", { class: "v" }),
selb: el("button", { type: "button", class: "selb", onclick: () => selectTrack(i) }),
};
c.strip = el("div", { class: "strip", role: "group", "aria-label": `${t("track")} ${i + 1}` },
c.num, c.snd, c.rec, fader, c.lvOut, c.mute, el("span", { class: "v dim", ic: "symbol_pan" }, t("pan")), pan, c.panOut,
el("span", { class: "v dim" }, t("rev")), rev, c.revOut, c.selb);
mixCtl[i] = c;
return c.strip;
}
function updateStrip(i) {
const c = mixCtl[i], x = dev && dev.mix && dev.mix.tracks[i];
if (!c || !x) return;
const sel = i === dev.sel;
c.strip.classList.toggle("sel", sel);
c.num.setAttribute("aria-pressed", sel ? "true" : "false");
const nm = trackName(x);
c.snd.textContent = nm;
c.snd.title = nm;
if (!mixTouched("lv", i)) c.fader.value = String(x.level);
const [lt, lu] = fmtValue(c.lvDesc, x.level);
c.lvOut.textContent = lu ? `${lt} ${lu}` : lt;
c.mute.setAttribute("aria-pressed", x.mute ? "true" : "false");
c.strip.classList.toggle("muted", !!x.mute || !x.level);
c.pan.disabled = x.pan == null;
if (x.pan != null) {
if (!mixTouched("pan", i)) c.pan.value = String(x.pan);
const [pt, pu] = fmtValue(c.pDesc, x.pan);
c.panOut.textContent = pu ? `${pt} ${pu}` : pt;
}
c.rev.disabled = x.rev == null || (!dev.v4 && i !== dev.sel); /* ((Skiff W3) another track's: TRACK_PARAM, v4) */
if (x.rev != null) {
if (!mixTouched("rev", i)) c.rev.value = String(x.rev);
const [rt, ru] = fmtValue(c.rDesc, x.rev);
c.revOut.textContent = ru ? `${rt} ${ru}` : rt;
}
c.rec.classList.toggle("on", !!x.armed);
c.selb.disabled = sel;
c.selb.textContent = t(sel ? "selectedTrack" : "selectTrack");
}
window.addEventListener("pointerup", () => { mixDrag = null; });
window.addEventListener("pointercancel", () => { mixDrag = null; });
/* level and mute: TRACK_MIX, one in flight per track and one queued with the latest values (as SET) */
function setLevel(i, v) {
if (!dev || !dev.mix) return;
dev.mix.tracks[i].level = v;
mixEdit.set("lv:" + i, performance.now());
updateStrip(i);
mixToSound(i);
sendMix(i);
}
function setMute(i, on) {
if (!dev || !dev.mix) return;
dev.mix.tracks[i].mute = on ? 1 : 0;
mixEdit.set("lv:" + i, performance.now());
updateStrip(i);
mixToSound(i);
sendMix(i);
}
async function sendMix(i) {
const d = dev, x = d.mix.tracks[i];
try {
const r = await mixer.setMix(rq, i, x.level, x.mute, { key: "mix:" + i });
if (d !== dev || !d.mix || mixDrag === "lv:" + i || d.link.hasQueued("mix:" + i)) return;
const y = d.mix.tracks[i]; /* the device's values after clamping */
y.level = r.level; y.mute = r.mute;
updateStrip(i);
mixToSound(i);
} catch (e) { report(e); }
}
/* pan: the selected track as any Sound parameter; another track with TRACK_PARAM (v4: while dragging, one in
flight and one queued with the latest value), or with v3 firmware on release (it is selected for a moment) */
const panWant = new Map();
function setPan(i, v, final) {
if (!dev || !dev.mix) return;
dev.mix.tracks[i].pan = v;
mixEdit.set("pan:" + i, performance.now());
updateStrip(i);
if (i === dev.sel) { userSet(0, pPan(), v, final); return; }
if (dev.v4) panTrack(i, v);
else if (final) panOther(i, v);
}
function setRev(i, v, final) { /* ((Skiff W3) as PAN: the selected track's a SET, another's TRACK_PARAM) */
if (!dev || !dev.mix) return;
dev.mix.tracks[i].rev = v;
mixEdit.set("rev:" + i, performance.now());
updateStrip(i);
if (i === dev.sel) { userSet(0, pRev(), v, final); return; }
if (dev.v4) revTrack(i, v);
}
async function revTrack(i, v) {
const d = dev;
try {
const r = await mixer.setPan(rq, i, d.sel, pRev(), v, true, "rev:" + i);
if (d !== dev || !d.mix || mixDrag === "rev:" + i || d.link.hasQueued("rev:" + i)) return;
d.mix.tracks[i].rev = r;
updateStrip(i);
} catch (e) { report(e); }
}
async function panTrack(i, v) {
const d = dev;
try {
const r = await mixer.setPan(rq, i, d.sel, pPan(), v, true);
if (d !== dev || !d.mix || mixDrag === "pan:" + i || d.link.hasQueued("pan:" + i)) return;
d.mix.tracks[i].pan = r; /* the device's value after clamping */
updateStrip(i);
if (i === d.sel) mixToSound(i);
} catch (e) { report(e); }
}
async function panOther(i, v) {
panWant.set(i, v);
if (panOther.run) return;
panOther.run = true;
const d = dev;
try {
while (busy && d === dev) await sleep(20); /* not in the middle of another multi-request operation */
assertSession(d);
const releaseBusy = beginBusy();
panning = true;
try {
while (panWant.size && d === dev) {
const [tr, val] = panWant.entries().next().value;
panWant.delete(tr);
const r = await mixer.setPan(rq, tr, d.sel, pPan(), val);
if (d.mix && !panWant.has(tr)) { d.mix.tracks[tr].pan = r; updateStrip(tr); }
}
} finally { panning = false; releaseBusy(); }
} catch (e) { report(e); } finally { panOther.run = false; panWant.clear(); }
}
/* ------------------------------------------------- live sync / polling --- */
/* With WATCH (protocol v2) the device pushes CHANGED / RELOAD / STEP_CHANGED; the editor PINGs about
once a second so the watch stays on (it ends 3 s after the last request), and DUMPs every 5 s as a
safety net. Older firmware: DUMP every 400 ms and two steps per round. */
function onPush(f) {
const d = dev;
if (!d || !d.dump || !d.info) return;
try {
if (f.cmd === CMD.CHANGED) {
const c = parse[CMD.CHANGED](f.a);
if (panning && !c.scope) return; /* about the track selected for a moment, not ours */
const arr = c.scope ? d.dump.g : d.dump.p;
if (c.id >= arr.length) return;
const k = key(c.scope, c.id);
if (touched(k)) return; /* the user's value wins; their SET follows */
const old = arr[c.id];
arr[c.id] = c.value;
showValue(k, c.value, false);
blink(k);
mixFromDump();
if (!c.scope && c.id === pSlen() && old !== c.value) { $("steptables").dataset.len = ""; renderSteps(); }
} else if (f.cmd === CMD.RELOAD) {
d.sel = parse[CMD.RELOAD](f.a).track; /* v3: another track may be selected on the device */
if (selfReload.n > 0 && Date.now() < selfReload.until) { selfReload.n--; return; }
needReload = true;
maybeReload();
} else if (f.cmd === CMD.STEP_CHANGED) {
const { index } = parse[CMD.STEP_CHANGED](f.a);
if (index < d.info.nstep) refreshStep(index);
} else if (f.cmd === CMD.TRACK_CHANGED) { /* v4: level / pan / mute of a track that is not selected */
const c = parse[CMD.TRACK_CHANGED](f.a), x = d.mix && d.mix.tracks[c.track];
if (!x || c.track === d.sel) return;
if (c.id === pPan()) { if (!mixTouched("pan", c.track)) x.pan = c.value; }
else if (c.id === pMute()) { if (!mixTouched("lv", c.track)) x.mute = c.value ? 1 : 0; }
else if (c.id === P.LEVEL) { if (!mixTouched("lv", c.track)) x.level = c.value; }
else return;
updateStrip(c.track);
}
} catch (e) { console.warn("bad push", f, e); }
}
function blink(k) {
const c = ctl.get(k);
if (!c || !c.row) return;
c.row.classList.add("pushed");
clearTimeout(c.blink);
c.blink = setTimeout(() => c.row.classList.remove("pushed"), 400);
}
async function refreshStep(i) {
const d = dev;
if (!d || !d.steps.length) return; /* ((Skiff W7) read when their tab opens) */
try {
const s = parse[CMD.STEP_GET](await rq(req.stepGet(i), { key: "step:" + i }));
if (d !== dev || s.index !== i) return;
d.steps[i] = s;
updateStepRows();
} catch (err) { report(err); }
}
function maybeReload() {
if (!dev || busy || !needReload || !dev.dump) return;
op(() => afterSoundChange("reloaded"));
}
/* one multi-request operation; polling waits for it */
async function op(fn) {
if (!dev) return;
const releaseBusy = beginBusy();
try { await fn(); } catch (err) { report(err); } finally { releaseBusy(); }
}
function renderLive() {
$("live").textContent = !dev || !dev.dump ? "" : t(dev.watch ? "live" : "polling");
}
/* keep-alive: PING when nothing else went out for ~1 s; after a longer gap (hidden tab, a long flash
write: Link.onGap) the watch may have ended: WATCH again and re-read what may have been missed */
let rewatch = false;
async function keepAlive() {
const d = dev;
if (!d || !d.watch || !d.dump || document.hidden) return;
const gap = Date.now() - d.link.lastSent;
if (rewatch || gap > 2500) {
if (keepAlive.run) return;
keepAlive.run = true;
try {
const on = await startWatch((r, o) => sessionRequest(d, r, o));
assertSession(d);
rewatch = false; /* (this WATCH itself may have flagged the gap) */
if (on) { d.v4 = on === 3; needReload = true; maybeReload(); }
else if (d === dev) { d.watch = false; renderLive(); }
} catch (e) { /* closed */ } finally { keepAlive.run = false; }
} else if (gap > 850 && d.link.idle) {
if (tab === "song" && d.info.skiff & 28) { /* ((Skiff W3) on the Song tab: it as the keep-alive, the pool each 4th) */
if (!keepAlive.song) {
keepAlive.song = true;
keepAlive.n = (keepAlive.n | 0) + 1;
readSong(d, keepAlive.n % 4 === 0, true).catch(() => {}).finally(() => { keepAlive.song = false; });
}
} else if (d.info.skiff & 1) { /* ((Skiff W3) the transport's state as the keep-alive) */
d.link.request(req.transport(), { key: "ping", quiet: true, retries: 0 })
.then((a) => { if (d === dev) renderTransport(parse[CMD.TRANSPORT](a)); }).catch(() => {});
} else d.link.request(req.ping(), { key: "ping", quiet: true, retries: 0 }).catch(() => {});
}
}
setInterval(keepAlive, 1000);
document.addEventListener("visibilitychange", () => { if (!document.hidden && dev && dev.watch) { rewatch = true; keepAlive(); } });
let stepRR = 0;
setInterval(async () => {
if (!dev || busy || dragging || document.hidden || !dev.dump || !dev.link.idle) return;
if (needReload) { maybeReload(); return; }
if (dev.watch && Date.now() - lastDump < 5000) return;
const releaseBusy = beginBusy();
const d = dev;
try {
const dump = await getDump();
if (d !== dev) return;
const soundChanged = dump.engine !== d.dump.engine || dump.preset !== d.dump.preset;
const engineChanged = dump.engine !== d.dump.engine;
const oldLen = d.dump.p[pSlen()];
for (const [k, c] of ctl) {
const v = c.scope ? dump.g[c.id] : dump.p[c.id];
if (touched(k)) { (c.scope ? dump.g : dump.p)[c.id] = c.scope ? d.dump.g[c.id] : d.dump.p[c.id]; continue; }
showValue(k, v, false);
}
d.dump = dump;
if (engineChanged) await rereadEngineDesc();
if (hasTracks()) await readMixer(); /* the strips (other tracks push nothing) */
if (soundChanged) { updateBrowser(); await loadStepsIfShown(); sayK("ready"); return; }
if (dump.p[pSlen()] !== oldLen) { $("steptables").dataset.len = ""; renderSteps(); }
if (d.watch || !d.steps.length) return; /* steps come as STEP_CHANGED; ((Skiff W7) or wait for their tab) */
/* steps are not in DUMP: follow them two at a time */
const len = Math.max(1, Math.min(d.info.nstep, dump.p[pSlen()] || 16));
for (let n = 0; n < 2; n++) {
stepRR = (stepRR + 1) % len;
if (performance.now() - (stepEdit.get(stepRR) || 0) < 1500) continue;
const s = await getStep(stepRR);
const o = d.steps[stepRR];
d.steps[stepRR] = s;
if (JSON.stringify(o) !== JSON.stringify(s)) updateStepRows();
}
} catch (err) { report(err); } finally { releaseBusy(); }
}, 400);
/* ------------------------------------------------ device preferences --- */
async function syncPreferences(d) {
if (!d || !d.info || !d.info.uiCaps) { renderPreferences(); return; }
const preferences = await readDevicePreferences((r, o) => sessionRequest(d, r, o), d.info, d.names, d.preferences);
if (dev !== d) return;
d.preferences = preferences;
if (preferences.slots) { d.bank = preferences.slots; renderBank(); }
renderPreferences();
}
function preferenceResult(rc) {
if (rc === 4) sayK("devicePending");
else if (rc === 3) sayK("deviceUnsaved");
else if (rc) throw new Error(t("deviceRejected"));
}
async function changePreference(id, value) {
const d = dev;
if (!d) return;
while (busy && d === dev) await sleep(20);
if (d !== dev) return;
await op(async () => {
const result = parse[CMD.UI_SET](await sessionRequest(d, req.uiSet(id, value), FLASH_OPT));
if (d !== dev) return;
await syncPreferences(d); preferenceResult(result.rc);
});
}
async function changeFavorite(row) {
const d = dev;
if (!d) return;
while (busy && d === dev) await sleep(20);
if (d !== dev) return;
await op(async () => {
const result = parse[CMD.FAV_SET](await sessionRequest(d, req.favSet(row.engine, row.preset, !row.favorite), FLASH_OPT));
if (d !== dev) return;
await syncPreferences(d); preferenceResult(result.rc);
});
}
/* (Skiff W3) the device's MENU settings under Settings, by its tabs (DISPLAY, CONTROL, AUDIO, SYSTEM); THEME is the
display group's above. Read at connect and when the tab opens (the device's own changes push nothing) */
async function readMenu(d = dev) {
if (!d || !d.info || !d.info.menuCount) return;
d.menu = await readDeviceMenu((r, o) => sessionRequest(d, r, o), d.info);
if (d === dev) renderMenu();
}
function renderMenu() {
const d = dev, items = d && d.menu;
$("device-menu").hidden = !items || !items.length;
if (!items) return;
const box = $("device-menu-controls");
if (box.contains(document.activeElement)) return;
const tabs = [...new Set(items.map((x) => x.tabName || ""))];
box.replaceChildren(...tabs.flatMap((tn) => [
...(tn ? [el("h3", { text: tn })] : []),
...items.filter((x) => (x.tabName || "") === tn && x.id !== 0).map((x) => {
const ctl = x.kind === 0
? el("select", { "aria-label": x.name }, ...x.names.map((n, k) => el("option", { value: x.min + k, text: n })))
: el("input", { type: "number", min: x.min, max: x.max, "aria-label": x.name });
ctl.value = String(x.value);
ctl.addEventListener("change", () => op(async () => {
const r = parse[CMD.MENU_SET](await sessionRequest(d, req.menuSet(x.id, +ctl.value)));
if (r.rc) throw new Error(t("deviceRejected"));
x.value = r.value;
ctl.value = String(r.value);
}));
return el("label", { class: "bar" }, el("span", { text: x.name + (x.unit ? ` (${x.unit})` : "") }), ctl);
})]));
}
function renderPreferences(force = false) {
const d = dev, p = d && d.preferences;
const look = p && { SKIFF: "dark", "HI-CON": "dark", PAPER: "light", CRYPT: "crypt", NEON: "neon", /* (Skiff 1.0) the */
QUARK: "quark" }[p.palettes[p.state.palette]]; /* unit's THEME; none: the system's */
if (look) document.documentElement.dataset.theme = look;
else delete document.documentElement.dataset.theme;
$("device-display").hidden = !p || !(p.state.caps & 7);
$("device-presets").hidden = !p || !(p.state.caps & 8);
if (!p) { renderPreferences.sig = null; return; }
const sig = JSON.stringify([p.state, p.palettes, lang, d.dump && d.dump.engine, d.sel]); /* ((phase 6) the track: what it may play) */
if (!force && sig === renderPreferences.sig) return;
renderPreferences.sig = sig;
const defs = [
[0, "deviceTheme", p.palettes, p.state.palette],
[1, "deviceFont", [t("deviceRegular"), t("deviceBold")], p.state.font],
[2, "deviceMonitor", [t("deviceOff"), t("deviceEvents"), t("deviceNotes")], p.state.monitor],
];
const controls = [];
for (const [id, key, options, value] of defs) {
if (!(p.state.caps & (1 << id))) continue;
const select = el("select", { "aria-label": t(key) });
select.replaceChildren(...options.map((text, i) => el("option", { value: i, text })));
select.value = value;
select.addEventListener("change", () => changePreference(id, +select.value));
controls.push(el("label", { class: "bar" }, el("span", { text: t(key) }), select));
}
$("device-display-controls").replaceChildren(...controls);
if (!(p.state.caps & 8)) return;
const filter = $("device-filter");
filter.setAttribute("aria-label", t("deviceList"));
filter.replaceChildren(el("option", { value: 0, text: t("deviceAll") }), el("option", { value: 1, text: t("deviceFavorites") }));
filter.value = p.state.filter;
const rows = devicePresetRows(d.info, d.names, p);
const table = el("table");
table.append(el("colgroup", {}, el("col", { style: "width:40px" }), el("col"), el("col", { style: "width:110px" })));
for (const row of rows) {
const name = row.user ? slotName(row.preset) + " " + row.name : row.name;
const star = el("button", { text: row.favorite ? "\u2605" : "\u2606", "aria-label": t(row.favorite ? "deviceUnstar" : "deviceStar") + ": " + name, "aria-pressed": String(row.favorite) });
star.addEventListener("click", () => changeFavorite(row));
const load = el("button", { text: name, disabled: !row.user && !engineAllowed(row.engine) }); /* (phase 6: a light
* track's greyed engines) */
load.addEventListener("click", () => { if (!dev || busy) return; row.user ? bankLoad(row.preset) : choosePreset(row.engine, row.preset); });
table.append(el("tr", {}, el("td", {}, star), el("td", {}, load), el("td", { text: row.user ? t("bank") : d.info.engines[row.engine] })));
}
$("device-preset-list").replaceChildren(rows.length ? table : el("p", { class: "dim", text: t("deviceEmpty") }));
}
$("device-filter").addEventListener("change", () => changePreference(3, +$("device-filter").value));
setInterval(() => {
if (!dev || !dev.preferences || busy || document.hidden || !["settings", "library"].includes(tab)) return;
const d = dev;
op(() => syncPreferences(d));
}, 1000);
/* ------------------------------------------------------------ files --- */
$("savefile").addEventListener("click", () => op(async () => {
if (!dev) return;
if (dev.stepsStale) await loadSteps(); /* ((Skiff W7) read for it) */
const engine = dev.dump.engine, preset = dev.dump.preset;
const data = { format: "felucca-patch", version: 1, firmware: dev.info.version,
engineName: dev.info.engines[engine], presetName: (dev.names[engine] || [])[preset],
engine, preset, p: dev.dump.p.slice(), g: dev.dump.g.slice(),
steps: dev.steps.map((s) => ({ n: s.n, notes: s.notes.slice(), time: s.time, flags: s.flags, vel: s.vel, /* ((Skiff W1) */
hit: s.hit | 0, acc: s.acc | 0, chance: s.chance ?? 100, ratchet: s.ratchet ?? 1, flam: s.flam | 0, cond: s.cond | 0, /* whole) */
nudge: s.nudge | 0 })) };
download(`skiff-${fileSlug(data.engineName || "patch")}-${fileSlug(data.presetName || preset)}.json`, data);
}));
$("loadfile").addEventListener("click", () => { $("file").value = ""; $("file").click(); });
$("file").addEventListener("change", async () => {
const f = $("file").files[0];
if (!f || !dev) return;
const session = dev;
let data;
try {
data = JSON.parse(await f.text());
assertSession(session);
if (!Number.isInteger(data.engine) || !Number.isInteger(data.preset) || !Array.isArray(data.p)) throw new Error("engine / preset / p");
if (data.engine < 0 || data.engine >= dev.info.nengines) throw new Error("engine " + data.engine);
} catch (e) { if (e.message !== "closed") sayK("badfile", e.message); return; }
if (lightRefuses(dev.info, dev.sel ?? 0, data.engine)) { /* ((Skiff W4) said, nothing written) */
sayK("lightRefused", `${dev.info.engines[data.engine]} T${(dev.sel ?? 0) + 1}`);
return;
}
if (!confirm(t(Array.isArray(data.steps) ? "confirmLoadFileSteps" : "confirmLoadFile").replace("{name}", f.name))) return; /* ((Skiff W1)) */
const releaseBusy = beginBusy();
try {
selfLoad(true);
await rq(req.preset(data.engine, data.preset));
dev.dump = await getDump();
await rereadEngineDesc();
const n = Math.min(data.p.length, dev.info.pcount);
for (let i = 0; i < n; i++) {
const d = dev.pdesc[i];
if (!visible(d) || !Number.isFinite(data.p[i])) continue;
if (i % 8 === 0) sayK("applying", `${i}/${n}`);
await rq(req.set(0, i, data.p[i]));
}
if (Array.isArray(data.steps)) {
const m = Math.min(data.steps.length, dev.info.nstep);
for (let i = 0; i < m; i++) {
const s = data.steps[i] || {};
if (i % 8 === 0) sayK("applying", `steps ${i}/${m}`);
dev.steps[i] = parse[CMD.STEP_SET](await rq(req.stepSet(i, { /* ((Skiff W1) whole: nothing of before left hidden) */
n: s.n | 0, notes: Array.isArray(s.notes) ? s.notes : [0, 0, 0, 0], time: s.time ?? 2, flags: s.flags | 0, vel: s.vel | 0,
...(dev.info.chance ? { hit: s.hit | 0, acc: s.acc | 0, chance: s.chance ?? 100 } : {}),
...(dev.info.chance && dev.info.ratchet ? { ratchet: s.ratchet ?? 1 } : {}),
...(dev.info.chance && dev.info.ratchet && dev.info.stepx ? { flam: s.flam | 0, cond: s.cond | 0, nudge: s.nudge | 0 } : {}) })));
}
}
dev.dump = await getDump();
updateBrowser();
$("steptables").dataset.len = "";
refreshAll();
sayK("applied");
} catch (err) { report(err); } finally { releaseBusy(); }
});
/* ----------------------------------------------------------- library --- */
/* Patches live in IndexedDB "felucca-editor": store "patches" (by id), store "meta" ("layout": the
parameter keys / engine names the stored values are in). Without IndexedDB (some private windows)
the library is kept in memory only. */
const store = (() => {
let dbp = null;
const open = () => dbp || (dbp = new Promise((res) => {
try {
const r = indexedDB.open("felucca-editor", 1);
r.onupgradeneeded = () => { r.result.createObjectStore("patches", { keyPath: "id" }); r.result.createObjectStore("meta"); };
r.onsuccess = () => res(r.result);
r.onerror = r.onblocked = () => res(null);
} catch (e) { res(null); }
}));
const tx = async (name, mode, fn) => {
const db = await open();
if (!db) return undefined;
return new Promise((res, rej) => {
const x = db.transaction(name, mode);
let out;
const r = fn(x.objectStore(name));
if (r) r.onsuccess = () => { out = r.result; };
x.oncomplete = () => res(out);
x.onerror = x.onabort = () => rej(x.error || new Error("IndexedDB"));
});
};
return {
ok: async () => !!(await open()),
all: () => tx("patches", "readonly", (os) => os.getAll()),
putMany: (ps) => tx("patches", "readwrite", (os) => { ps.forEach((p) => os.put(p)); }),
del: (id) => tx("patches", "readwrite", (os) => os.delete(id)),
getMeta: (k) => tx("meta", "readonly", (os) => os.get(k)),
setMeta: (k, v) => tx("meta", "readwrite", (os) => os.put(v, k)),
};
})();
let lib = []; /* patches (cleanPatch + id) */
let libMeta = { keys: null, engines: null, pe0: null };
let libPersistent = false;
let libSel = null, bankSel = null;
let libBusy = false; /* a library / bank operation is running */
const newId = () => (self.crypto && crypto.randomUUID ? crypto.randomUUID() : Date.now().toString(36) + Math.random().toString(36).slice(2));
const nowIso = () => new Date().toISOString();
const slotName = (i) => "U" + String(i + 1).padStart(2, "0");
const libCtx = () => (dev && dev.keys ? { keys: dev.keys, engines: dev.info.engines, firmware: dev.info.version, pe0: dev.info.pe0 }
: { keys: libMeta.keys, engines: libMeta.engines, firmware: "", pe0: libMeta.pe0 });
async function libInit() {
try {
libPersistent = await store.ok();
if (libPersistent) {
lib = ((await store.all()) || []).filter((p) => p && p.id);
libMeta = (await store.getMeta("layout")) || libMeta;
}
} catch (e) { console.warn(e); libPersistent = false; }
renderLib();
}
async function libWrite(ps) {
try { await store.putMany(ps); } catch (e) { console.warn(e); sayK("error", "IndexedDB: " + e.message); }
}
async function libAdd(patches) {
const add = patches.map((p) => ({ ...cleanPatch(p), id: newId() }));
lib.push(...add);
if (add.length) libSel = add[add.length - 1].id;
await libWrite(add);
renderLib();
return add;
}
async function libUpdate(p) {
p.modified = nowIso();
await libWrite([p]);
renderLib();
}
/* the device's parameter layout becomes the library's; patches stored with another layout are mapped by key.
A device without DIGITAL (engine 1 "-", retired in 1.0): the library's DIGITAL sounds become FM6 (fromDigital,
as readLibraryFile does), also when the layout itself is unchanged; so do its SAMPLE PERC sounds (the set retired
after 1.0.2): DRUM's kit (fromPerc) */
async function libAdopt(d) {
const keys = d.keys, engines = d.info.engines, changed = [];
const relayout = (libMeta.keys && !sameKeys(libMeta.keys, keys)) || (libMeta.engines && !sameKeys(libMeta.engines, engines));
const noFm4 = (engines || [])[1] === "-";
for (const p of lib) {
const name = p.engineName || (libMeta.engines || [])[p.engine];
const digital = noFm4 && !p.fm6 && (name === "DIGITAL" || ((!name || name === "-") && p.engine === 1));
const pe0 = () => (keys && p.p.length === keys.length ? d.info.pe0 : p.p.length - 8); /* (E1..E8: the last 8) */
const perc = !digital && !!fromPerc({ ...p, engineName: name }, engines, p.p.length - 8);
if (!relayout && !digital && !perc) continue;
if (relayout) p.p = remapParams(p.p, libMeta.keys, keys);
const pt = digital ? fromDigital(p, engines, pe0()) : perc ? fromPerc({ ...p, engineName: name }, engines, pe0()) : null;
if (pt) Object.assign(p, cleanPatch(pt));
else {
const e = name ? engines.indexOf(name) : p.engine;
if (e >= 0) { p.engine = e; p.engineName = engines[e]; }
}
changed.push(p);
}
libMeta = { keys, engines, pe0: d.info.pe0 };
if (changed.length) await libWrite(changed);
try { await store.setMeta("layout", libMeta); } catch (e) { console.warn(e); }
renderLib();
}
const engineOk = (p) => !!dev && p.engine < dev.info.nengines && (!p.engineName || dev.info.engines[p.engine] === p.engineName);
/* a full parameter set for UP_PUT: unknown values get the DESC default where it is known, else 0 */
function fullParams(p) {
const out = [];
for (let i = 0; i < dev.info.pcount; i++) {
let v = p.p[i];
if (v == null) {
const d = dev.pdesc[i];
v = d && (i < dev.info.pe0 || p.engine === dev.dump.engine) ? d.def : 0;
}
out.push(v);
}
return out;
}
const engRank = (n) => { const k = ENGINE_ORDER.indexOf(n); return k < 0 ? ENGINE_ORDER.length : k; };
function libView() {
const q = $("libq").value.trim().toLowerCase(), fe = $("libeng").value, ft = $("libtag").value;
const by = {
name: (a, b) => a.name.localeCompare(b.name),
engine: (a, b) => engRank(a.engineName) - engRank(b.engineName) || (a.engineName || "").localeCompare(b.engineName || "") ||
a.name.localeCompare(b.name), /* (the device's order: ENGINE_ORDER) */
created: (a, b) => b.created.localeCompare(a.created),
modified: (a, b) => b.modified.localeCompare(a.modified),
}[$("libsort").value] || ((a, b) => b.modified.localeCompare(a.modified));
return lib.filter((p) => (!q || p.name.toLowerCase().includes(q) || p.tags.some((x) => x.toLowerCase().includes(q)))
&& (!fe || p.engineName === fe) && (!ft || p.tags.includes(ft))).sort(by);
}
function fillSelect(sel, opts) {
const v = sel.value;
sel.replaceChildren(...opts.map(([val, txt]) => el("option", { value: val, text: txt })));
if (opts.some(([val]) => val === v)) sel.value = v;
}
function renderLib() {
const all = [...new Set([...(dev ? dev.info.engines : libMeta.engines || []), ...lib.map((p) => p.engineName).filter(Boolean)])];
const engs = engineOrder(all).map((i) => all[i]);
fillSelect($("libeng"), [["", t("allEngines")], ...engs.map((e) => [e, e])]);
const tags = [...new Set(lib.flatMap((p) => p.tags))].sort();
fillSelect($("libtag"), [["", t("allTags")], ...tags.map((x) => [x, x])]);
fillSelect($("libsort"), [["modified", t("sortModified")], ["created", t("sortCreated")], ["name", t("sortName")], ["engine", t("sortEngine")]]);
const v = libView();
if (libSel && !lib.some((p) => p.id === libSel)) libSel = null;
const box = $("liblist");
if (!lib.length) box.replaceChildren(el("div", { class: "none", text: t("libEmpty") }));
else {
const tb = el("table", {}, el("colgroup", {}, el("col"), el("col", { class: "e" }), el("col"), el("col", { class: "d" })),
el("tr", {}, el("th", { text: t("name") }), el("th", { text: t("engine") }), el("th", { text: t("tagsCol") }), el("th", { text: t("date") })));
for (const p of v) {
const tr = el("tr", { "data-id": p.id, class: p.id === libSel ? "sel" : null, draggable: "true", title: p.name },
el("td", {}, p.pattern || p.grid ? icon("note_eight") : "", p.name),
el("td", { text: p.engineName || String(p.engine) }),
el("td", { text: p.tags.join(", ") }),
el("td", { text: new Date(p.modified).toLocaleDateString(lang) }));
tr.addEventListener("click", () => { libSel = p.id; renderLib(); });
tr.addEventListener("dblclick", () => libAudition(p.id));
tr.setAttribute("aria-selected", String(p.id === libSel));
rowKeys(tr, "lib", p.id, () => { libSel = p.id; renderLib(); }, () => { libSel = p.id; renderLib(); libAudition(p.id); });
tr.addEventListener("dragstart", (e) => { libSel = p.id; e.dataTransfer.setData("text/x-felucca-lib", p.id); e.dataTransfer.effectAllowed = "copy"; });
tb.append(tr);
}
box.replaceChildren(tb, ...(v.length ? [] : [el("div", { class: "none", text: t("noMatch") })]));
rowRefocus("lib", box, "data-id");
}
$("libcount").textContent = `${v.length} / ${lib.length}` + (libPersistent ? "" : " " + t("noLibDB"));
const sel = lib.find((p) => p.id === libSel);
for (const id of ["libren", "libtags", "libdup", "libdel", "libexp1"]) $(id).disabled = !sel;
$("libaud").disabled = !sel || !dev || libBusy;
$("libput").disabled = !sel || !dev || !dev.bank || bankSel == null || libBusy;
$("libsave").disabled = !dev || libBusy;
$("libexport").disabled = !lib.length;
}
["libq", "libeng", "libtag", "libsort"].forEach((id) => $(id).addEventListener(id === "libq" ? "input" : "change", renderLib));
function renderBank() {
const pane = $("bankpane");
$("bankhint").hidden = !!(dev && dev.bank);
$("bankhint").textContent = t(!dev || !dev.dump ? "bankConnect" : "bankNone");
if (!dev || !dev.bank) { pane.hidden = true; return; }
pane.hidden = false;
const b = dev.bank, used = b.slots.filter((x) => x.used).length;
$("bankhead").textContent = `${used} / ${b.total} ${t("used")}`;
const tb = el("table", {}, el("colgroup", {}, el("col", { class: "n" }), el("col"), el("col", { class: "e" })),
el("tr", {}, el("th", { text: "#" }), el("th", { text: t("name") }), el("th", { text: t("engine") })));
for (const x of b.slots) {
const tr = el("tr", { "data-slot": x.slot, class: [x.slot === bankSel ? "sel" : "", x.used ? "" : "empty"].filter(Boolean).join(" ") || null,
draggable: x.used ? "true" : null },
el("td", { text: slotName(x.slot) }), el("td", { text: x.used ? x.name : t("empty") }),
el("td", { text: x.used ? engineLabel(dev.info.engines, x.engine) : "" }));
tr.addEventListener("click", () => { bankSel = x.slot; renderBank(); renderLib(); });
tr.addEventListener("dblclick", () => { if (x.used) bankLoad(x.slot); });
tr.setAttribute("aria-selected", String(x.slot === bankSel));
rowKeys(tr, "bank", x.slot, () => { bankSel = x.slot; renderBank(); renderLib(); }, () => { if (x.used) bankLoad(x.slot); });
tr.addEventListener("dragstart", (e) => { e.dataTransfer.setData("text/x-felucca-slot", String(x.slot)); e.dataTransfer.effectAllowed = "copy"; });
tr.addEventListener("dragover", (e) => { if (e.dataTransfer.types.includes("text/x-felucca-lib")) { e.preventDefault(); tr.classList.add("over"); } });
tr.addEventListener("dragleave", () => tr.classList.remove("over"));
tr.addEventListener("drop", (e) => {
e.preventDefault();
tr.classList.remove("over");
const id = e.dataTransfer.getData("text/x-felucca-lib");
if (id) { bankSel = x.slot; libPut(id, x.slot); }
});
tb.append(tr);
}
$("banklist").replaceChildren(tb);
rowRefocus("bank", $("banklist"), "data-slot");
const s = bankSel == null ? null : b.slots[bankSel];
const idle = !libBusy;
$("bkload").disabled = !s || !s.used || !idle;
$("bkstore").disabled = !s || !idle;
$("bkget").disabled = !s || !s.used || !idle;
$("bkerase").disabled = !s || !s.used || !idle;
$("bkrefresh").disabled = !idle;
$("bkexport").disabled = !used || !idle;
}
/* a slot dropped on the library: copy it there */
$("liblist").addEventListener("dragover", (e) => { if (e.dataTransfer.types.includes("text/x-felucca-slot")) { e.preventDefault(); $("liblist").classList.add("over"); } });
$("liblist").addEventListener("dragleave", () => $("liblist").classList.remove("over"));
$("liblist").addEventListener("drop", (e) => {
e.preventDefault();
$("liblist").classList.remove("over");
const s = e.dataTransfer.getData("text/x-felucca-slot");
if (s !== "") bankGet(+s);
});
/* library operations that talk to the device: one at a time, buttons off meanwhile */
async function libOp(fn) {
if (!dev || libBusy) return;
const d = dev;
libBusy = true;
const releaseBusy = beginBusy();
renderLib(); renderBank();
try { await fn(d, (r, o) => sessionRequest(d, r, o)); } catch (err) { report(err); } finally { releaseBusy(); libBusy = false; renderLib(); renderBank(); }
}
const checkRc = (rc) => { if (rc) throw new Error(t("flashFail").replace("{rc}", rc)); };
async function refreshSlot(slot, d = dev) {
const r = parse[CMD.UP_LIST](await sessionRequest(d, req.upList(slot, 1)));
if (d.bank && r.slots[0]) d.bank.slots[slot] = r.slots[0];
}
function libAudition(id) {
const p = lib.find((x) => x.id === id);
if (!p || !dev || libBusy) return;
libOp(async (d, rqf) => {
if (!engineOk(p)) throw new Error(t("badEngine") + (p.engineName || p.engine));
sayK("auditioning", p.name);
selfLoad(true);
await auditionPatch(rqf, dev.info, p, { gEng: gEng(), track: dev.sel ?? 0,
progress: (i, n) => { if (i % 8 === 0) sayK("auditioning", `${p.name} ${i}/${n}`); } });
await afterSoundChange("ready", d);
sayK("auditioned", p.name);
});
}
$("libaud").addEventListener("click", () => libAudition(libSel));
$("libsave").addEventListener("click", () => libOp(async (d, rqf) => {
const def = upName((dev.names[dev.dump.engine] || [])[dev.dump.preset] || dev.info.engines[dev.dump.engine]);
const name = prompt(t("promptName"), def);
if (name == null) return;
const { patch } = await capturePatch(rqf, dev.info, name.trim() || def);
await libAdd([patch]);
sayK("savedLib", patch.name);
}));
/* factory preset -> library: PRESET (the sound only), then DUMP; no pattern (the steps are the track's,
not the preset's) */
$("factlib").addEventListener("click", () => libOp(async (d, rqf) => {
const e = dev.dump.engine, pi = $("preset").value === "" ? dev.dump.preset : +$("preset").value;
const name = (dev.names[e] || [])[pi] || "PRESET";
const was = { engine: dev.dump.engine, preset: dev.dump.preset }, keep = (await capturePatch(rqf, dev.info, "")).patch;
selfLoad(true);
await rqf(req.preset(e, pi));
const { patch } = await capturePatch(rqf, dev.info, name);
patch.pattern = null;
patch.grid = null;
patch.tags = ["factory"];
await rqf(req.preset(was.engine, was.preset)); /* ((Skiff W1) the sound as it was, edits and all: the preset it */
await auditionPatch(rqf, dev.info, keep, { gEng: gEng(), track: dev.sel ?? 0 }); /* came from, its values over it) */
await libAdd([patch]);
await afterSoundChange("ready", d);
sayK("copiedLib", `${dev.info.engines[e]} ${name}`);
}));
function libPut(id, slot) {
const p = lib.find((x) => x.id === id);
if (!p || !dev || !dev.bank || slot == null || libBusy) return;
const s = dev.bank.slots[slot];
if (!engineOk(p)) { sayK("badEngine", p.engineName || p.engine); return; }
if (s.used && !confirm(t("confirmOverwrite").replace("{n}", slotName(slot)).replace("{name}", s.name))) return;
libOp(async (d, rqf) => {
const keep4 = p.fm4 && dev.info.engines[1] === "-" && p.fm4.length === dev.info.pcount; /* a converted DIGITAL sound:
its DIGITAL values as engine 1 (the device converts them on load) */
checkRc(await bank.put(rqf, slot, keep4 ? { ...p, engine: 1, name: upName(p.name), p: fullParams({ ...p, p: p.fm4 }) }
: { ...p, name: upName(p.name), p: fullParams(p) }, dev.info));
await refreshSlot(slot, d);
sayK("putDone", `${slotName(slot)} ${upName(p.name)}`);
});
}
$("libput").addEventListener("click", () => libPut(libSel, bankSel));
$("libren").addEventListener("click", () => {
const p = lib.find((x) => x.id === libSel);
if (!p) return;
const v = prompt(t("promptName"), p.name);
if (v == null || !v.trim()) return;
p.name = v.trim().slice(0, 32);
libUpdate(p);
});
$("libtags").addEventListener("click", () => {
const p = lib.find((x) => x.id === libSel);
if (!p) return;
const v = prompt(t("promptTags"), p.tags.join(", "));
if (v == null) return;
p.tags = [...new Set(v.split(",").map((x) => x.trim()).filter(Boolean))];
libUpdate(p);
});
$("libdup").addEventListener("click", () => {
const p = lib.find((x) => x.id === libSel);
if (p) libAdd([{ ...p, name: (p.name + " 2").slice(0, 32), created: nowIso(), modified: nowIso() }]);
});
$("libdel").addEventListener("click", async () => {
const p = lib.find((x) => x.id === libSel);
if (!p || !confirm(t("confirmDelete").replace("{name}", p.name))) return;
lib = lib.filter((x) => x !== p);
libSel = null;
try { await store.del(p.id); } catch (e) { console.warn(e); }
renderLib();
});
function download(name, obj) {
const blob = new Blob([JSON.stringify(obj, null, 1)], { type: "application/json" });
const a = el("a", { href: URL.createObjectURL(blob), download: name });
document.body.append(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
}
const fileSlug = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "patch";
const today = () => new Date().toISOString().slice(0, 10);
$("libexp1").addEventListener("click", () => {
const p = lib.find((x) => x.id === libSel);
if (p) download(`felucca-patch-${fileSlug(p.name)}.json`, libraryFile("patch", [p], libCtx()));
});
$("libexport").addEventListener("click", () => download(`felucca-library-${today()}.json`, libraryFile("library", lib, libCtx())));
$("libimport").addEventListener("click", () => { $("libfile").value = ""; $("libfile").click(); });
$("libfile").addEventListener("change", async () => {
let n = 0, skipped = 0;
for (const f of [...$("libfile").files]) {
try {
const obj = JSON.parse(await f.text());
const ctx = libCtx();
const r = readLibraryFile(obj, ctx);
if (!ctx.keys && r.keys) { /* no layout yet: the file's becomes the library's */
libMeta = { keys: r.keys, engines: Array.isArray(obj.engines) ? obj.engines : null, pe0: obj.pE0 ?? null };
try { await store.setMeta("layout", libMeta); } catch (e) { console.warn(e); }
}
if (obj.kind === "bank") r.patches.forEach((p) => { if (!p.tags.includes("bank")) p.tags.push("bank"); });
await libAdd(r.patches);
n += r.patches.length;
skipped += r.skipped;
} catch (e) { sayK("badfile", `${f.name}: ${e.message}`); return; }
}
sayK("imported", n + (skipped ? t("skippedN").replace("{n}", skipped) : t("patchesN")));
});
/* ((Skiff W6) a list's row from the keyboard: focusable, Space selects it, Enter acts (audition, load), the arrows
move to the row above / below; rowFocus: the row to focus again after the list is drawn anew */
let rowFocus = null;
function rowKeys(tr, list, key, select, act) {
tr.tabIndex = 0;
tr.addEventListener("keydown", (e) => {
if (e.key === " " || e.key === "Enter") {
e.preventDefault();
rowFocus = { list, key };
if (e.key === " ") select(); else act();
} else if (e.key === "ArrowDown" || e.key === "ArrowUp") {
const n = e.key === "ArrowDown" ? tr.nextElementSibling : tr.previousElementSibling;
if (n && n.tabIndex === 0) { e.preventDefault(); n.focus(); }
}
});
}
function rowRefocus(list, box, attr) {
if (!rowFocus || rowFocus.list !== list) return;
const tr = box.querySelector(`tr[${attr}="${CSS.escape(String(rowFocus.key))}"]`);
rowFocus = null;
if (tr) tr.focus();
}
/* device bank */
function bankLoad(slot) {
if (!dev || !dev.bank || slot == null || libBusy) return;
const s = dev.bank.slots[slot];
if (s && s.used && lightRefuses(dev.info, dev.sel ?? 0, s.engine)) { /* ((Skiff W4) refused, said why: the device's */
sayK("lightRefused", `${dev.info.engines[s.engine]} T${(dev.sel ?? 0) + 1}`); /* rc is 1 for an empty slot too) */
return;
}
libOp(async (d, rqf) => {
selfLoad();
const rc = await bank.load(rqf, slot);
if (rc) { sayK(s && s.used ? "loadRefused" : "emptySlot", slotName(slot)); return; }
await afterSoundChange("ready", d);
sayK("loadedUser", `${slotName(slot)} ${s.name}`);
});
}
$("bkload").addEventListener("click", () => bankLoad(bankSel));
$("bkstore").addEventListener("click", () => {
const slot = bankSel;
if (!dev || !dev.bank || slot == null) return;
const s = dev.bank.slots[slot];
const name = prompt(t("promptNameAuto"), s.used ? s.name : "");
if (name == null) return;
if (s.used && !confirm(t("confirmOverwrite").replace("{n}", slotName(slot)).replace("{name}", s.name))) return;
libOp(async (d, rqf) => {
checkRc(await bank.store(rqf, slot, name.trim()));
await refreshSlot(slot, d);
sayK("storedSlot", `${slotName(slot)} ${dev.bank.slots[slot].name}`);
});
});
function bankGet(slot) {
if (!dev || !dev.bank || slot == null || libBusy) return;
libOp(async (d, rqf) => {
const u = await bank.get(rqf, dev.info, slot);
if (!u.used) { sayK("emptySlot", slotName(slot)); return; }
const pt = { name: u.name, engine: u.engine, engineName: dev.info.engines[u.engine], p: u.p, pattern: u.pattern, grid: u.grid, tags: ["device"],
fm6: u.fm6 };
await libAdd([reservedFm4(dev.info.engines, u.engine) ? fromDigital(pt, dev.info.engines, dev.info.pe0) : pt]);
sayK("copiedLib", u.name);
});
}
$("bkget").addEventListener("click", () => bankGet(bankSel));
$("bkerase").addEventListener("click", () => {
const slot = bankSel;
if (!dev || !dev.bank || slot == null) return;
const s = dev.bank.slots[slot];
if (!s.used || !confirm(t("confirmEraseSlot").replace("{n}", slotName(slot)).replace("{name}", s.name))) return;
libOp(async (d, rqf) => {
checkRc(await bank.erase(rqf, slot));
await refreshSlot(slot, d);
sayK("erasedSlot", slotName(slot));
});
});
$("bkrefresh").addEventListener("click", () => libOp(async (d, rqf) => {
sayK("readingBank");
dev.bank = await bank.list(rqf);
sayK("ready");
}));
$("bkexport").addEventListener("click", () => libOp(async (d, rqf) => {
const out = [];
for (const x of dev.bank.slots) {
if (!x.used) continue;
sayK("readingBank", ` ${slotName(x.slot)}`);
const u = await bank.get(rqf, dev.info, x.slot);
if (u.used) out.push({ name: u.name, engine: u.engine, p: u.p, pattern: u.pattern, grid: u.grid, slot: x.slot, fm6: u.fm6,
engineName: reservedFm4(dev.info.engines, u.engine) ? "DIGITAL" : dev.info.engines[u.engine] }); /* (DIGITAL's values) */
}
download(`felucca-bank-${today()}.json`, libraryFile("bank", out, libCtx()));
sayK("ready");
}));
/* ------------------------------------------------------------------ FM6 --- */
/* The 6-OP FM tab (firmware with FM6: INFO's fm6 tag): the whole patch of an FM6 track, which the device
only reaches through its macros. Import the generic 155-byte single-voice and 4096-byte 32-voice SysEx files,
pick a voice, edit it, send it to a track (live while editing); read a track's patch or a factory one; export a
voice. The track keeps it (SLOT OWN); a user preset (SAVE) or a project on the device keeps it after that.
The patch bank of 1.0..1.0.2 (B1..B27) is not offered, whatever the firmware (retired in 1.0.3). */
let fm6v = FM6.init(); /* the patch being edited (155 bytes) */
let fm6Imported = []; /* voices of the last imported file: [{name, v}] */
let fm6Picked = -1; /* the imported voice last clicked (now in fm6v) */
let fm6List = null; /* FM6_LIST of the device */
let fm6Listing = false; /* FM6_LIST on its way */
let fm6Asked = false; /* FM6_LIST asked once for this connection (renderPanels) */
let fm6Timer = null;
const fm6Ok = () => !!dev && !!dev.info && !!dev.info.fm6;
const fm6Track = () => +$("fm6trk").value || 0;
const fm6SlotName = (i) => "F" + (i + 1); /* the factory patches */
const FM6_WAVES = ["TRI", "SAW-", "SAW+", "SQR", "SIN", "S&H"];
const FM6_CURVES = ["-LIN", "-EXP", "+EXP", "+LIN"];
function fm6Set(i, val) {
fm6v[i] = Math.max(0, Math.min(FM6.max(i), Math.round(+val || 0)));
if ($("fm6live").checked && fm6Ok()) {
clearTimeout(fm6Timer);
fm6Timer = setTimeout(() => op(() => fm6Send(true)), 150);
}
}
function fm6Num(i, title) {
return el("input", { type: "number", min: 0, max: FM6.max(i), value: fm6v[i], title, class: "fm6n",
onchange: (e) => { fm6Set(i, e.target.value); e.target.value = fm6v[i]; renderFm6Ops(); } });
}
function fm6Sel(i, names, title) {
const s = el("select", { title, onchange: (e) => { fm6Set(i, e.target.value); renderFm6(); } },
...names.map((n, k) => el("option", { value: k, text: n })));
s.value = fm6v[i];
return s;
}
function renderFm6Voice() {
const V = FM6.VI, alg = fm6v[V.ALG], fb = FM6.feedbackOp(alg);
const nm = el("input", { type: "text", maxlength: 10, value: FM6.name(fm6v), size: 11,
onchange: (e) => { FM6.setName(fm6v, e.target.value); fm6Set(0, fm6v[0]); e.target.value = FM6.name(fm6v); } });
const row = (label, ...kids) => el("tr", {}, el("th", { text: label }), el("td", {}, ...kids));
$("fm6voice").replaceChildren(el("table", {},
row(t("name"), nm),
row("ALG", fm6Sel(V.ALG, Array.from({ length: 32 }, (_, k) => String(k + 1)), "ALG"),
el("span", { class: "dim", text: ` ${t("fm6Carriers")} ${FM6.carriers(alg).join(" ")}, ${t("fm6Feedback")} OP${fb}` })),
row("FB", fm6Num(V.FB, "FB"), " OKS ", fm6Num(V.OKS, "OKS"), " TRNSP ", fm6Num(V.TRNSP, "TRNSP")),
row("LFO", fm6Sel(V.LFW, FM6_WAVES, "WAVE"), " SPD ", fm6Num(V.LFS, "SPEED"), " DLY ", fm6Num(V.LFD, "DELAY"),
" PMD ", fm6Num(V.LPMD, "PMD"), " AMD ", fm6Num(V.LAMD, "AMD"), " PMS ", fm6Num(V.LPMS, "PMS"), " SYNC ", fm6Num(V.LKS, "SYNC")),
row(t("fm6PitchEg"), "R ", ...[0, 1, 2, 3].map((k) => fm6Num(V.PR1 + k, "R" + (k + 1))),
" L ", ...[0, 1, 2, 3].map((k) => fm6Num(V.PL1 + k, "L" + (k + 1))))));
}
function renderFm6Ops() {
const car = FM6.carriers(fm6v[FM6.VI.ALG]);
const head = el("tr", {}, el("th", { text: "OP" }), ...FM6.OP.map(([n]) => el("th", { text: n })), el("th", { text: t("fm6Freq") }));
const rows = [1, 2, 3, 4, 5, 6].map((n) => el("tr", {},
el("th", { text: (car.includes(n) ? "● " : "") + n }),
...FM6.OP.map(([f]) => el("td", {}, f === "LC" || f === "RC" ? fm6Sel(FM6.at(n, f), FM6_CURVES, f)
: f === "MODE" ? fm6Sel(FM6.at(n, f), ["RATIO", "FIXED"], f) : fm6Num(FM6.at(n, f), `OP${n} ${f}`))),
el("td", { class: "dim", text: FM6.freqText(fm6v, n) })));
$("fm6ops").replaceChildren(el("div", { class: "fm6ops" }, el("table", {}, head, ...rows)), el("p", { class: "dim", text: t("fm6Legend") }));
}
function renderFm6Imported() {
const box = $("fm6imported");
if (!fm6Imported.length || !fm6Ok()) { box.replaceChildren(); return; }
box.replaceChildren(el("p", { class: "dim", text: t("fm6Pick") }),
el("p", { class: "bar" }, ...fm6Imported.map((x, k) => el("button", { text: `${k + 1} ${x.name}`,
"aria-pressed": k === fm6Picked ? "true" : "false",
onclick: () => { fm6v = Uint8Array.from(x.v); fm6Picked = k; renderFm6(); sayK("fm6Picked", ` ${x.name}`); } }))));
}
function renderFm6() {
if (!fm6Ok()) return;
const ts = $("fm6trk"), keepT = ts.value, ss = $("fm6slot"), keepS = ss.value;
ts.replaceChildren(...Array.from({ length: dev.info.ntrk || 1 }, (_, i) => el("option", { value: i, text: String(i + 1) })));
ts.value = keepT || (dev.sel ?? 0);
const nf = dev.info.fm6.factory; /* the factory patches only (names once FM6_LIST is in) */
ss.replaceChildren(...Array.from({ length: nf }, (_, i) => {
const x = fm6List && fm6List.slots[i];
return el("option", { value: i, text: `${fm6SlotName(i)} ${x && x.used ? x.name : ""}`.trim() });
}));
ss.value = keepS !== "" && +keepS < nf ? keepS : "0";
renderFm6Voice();
renderFm6Ops();
renderFm6Imported();
}
async function fm6Refresh(d = dev) {
fm6Listing = true;
try { fm6List = parse[CMD.FM6_LIST](await sessionRequest(d, req.fm6List())); } finally { fm6Listing = false; }
renderFm6();
}
async function fm6Send(quiet) {
const r = parse[CMD.FM6_PUT](await sessionRequest(dev, req.fm6Put(FM6.TARGET.TRACK, fm6Track(), FM6.pack(fm6v))));
checkRc(r.rc);
if (!quiet) sayK("fm6Sent", ` ${fm6Track() + 1}`);
}
$("fm6read").addEventListener("click", () => op(async () => {
const r = parse[CMD.FM6_GET](await sessionRequest(dev, req.fm6Get(FM6.TARGET.TRACK, fm6Track())));
checkRc(r.rc);
fm6v = FM6.unpack(r.packed);
renderFm6();
sayK("fm6Read", ` ${fm6Track() + 1}: ${FM6.name(fm6v)}`);
}));
$("fm6send").addEventListener("click", () => op(() => fm6Send(false)));
$("fm6load").addEventListener("click", () => op(async () => { /* a factory patch into the editor */
const i = +$("fm6slot").value;
const r = parse[CMD.FM6_GET](await sessionRequest(dev, req.fm6Get(FM6.TARGET.FACTORY, i)));
checkRc(r.rc);
fm6v = FM6.unpack(r.packed);
fm6Picked = -1;
renderFm6();
sayK("fm6Loaded", ` ${fm6SlotName(i)}: ${FM6.name(fm6v)}`);
}));
$("fm6init").addEventListener("click", () => { fm6v = FM6.init(); renderFm6(); });
$("fm6import").addEventListener("click", () => $("fm6file").click());
$("fm6file").addEventListener("change", async (e) => {
const f = e.target.files[0];
e.target.value = "";
if (!f) return;
const r = FM6.parseSysex(new Uint8Array(await f.arrayBuffer()));
if (!r.voices.length) { const [k, x] = fm6Why(r); sayK(k, `${x}: ${f.name}`); return; }
fm6Imported = r.voices;
fm6Picked = r.voices.length === 1 ? 0 : -1;
if (r.voices.length === 1) fm6v = Uint8Array.from(r.voices[0].v);
renderFm6();
const notes = [r.badSum && t("fm6BadSum"), r.short && t("fm6Short"), r.skipped && t("fm6Skipped").replace("{x}", r.skipped)].filter(Boolean);
sayK("imported", `${f.name}: ${r.voices.length}` + (notes.length ? ` (${notes.join(", ")})` : ""));
});
/* why a file had no 6-operator voice: [message key, what to add before the file name] */
function fm6Why(r) {
const mk = r.kinds.find((k) => k.startsWith("maker:"));
if (r.kinds.includes("fm4")) return ["fm6Is4op", ""];
if (r.kinds.includes("other43")) return ["fm6OtherBlocks", ""];
if (mk) return ["fm6OtherMaker", ` (ID ${mk.slice(6)})`];
if (r.kinds.includes("universal")) return ["fm6Universal", ""];
return [r.sysex ? "fm6NoVoice" : "fm6NotSysex", ""];
}
function downloadBytes(name, bytes) {
const a = el("a", { href: URL.createObjectURL(new Blob([bytes], { type: "application/octet-stream" })), download: name });
document.body.append(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
}
$("fm6export").addEventListener("click", () => downloadBytes(`${fileSlug(FM6.name(fm6v))}.syx`, FM6.singleSysex(fm6v)));
$("connect").addEventListener("click", () => {
if (dev) { wantConnected = false; disconnect(); } else connect();
});
applyLang();
showTab(tab);
libInit();
if (!MOCK && !navigator.requestMIDIAccess) sayK("nomidi");
})();
</script>
</body>
</html>