Files
JIANT/web/editor.html
T

4768 lines
289 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
Portions Copyright (C) 2026 Juan Ignacio Antonucci (Juan Jiant) -->
<!-- Felucca web editor. 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>JIANT 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; }
:root { --bg: #fff; --fg: #000; --dim: #777; --line: #ccc; }
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) { --bg: #000; --fg: #fff; --dim: #888; --line: #444; }
}
:root[data-theme="dark"] { --bg: #000; --fg: #fff; --dim: #888; --line: #444; }
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: 46px 1fr 70px; gap: 6px; align-items: center; min-height: 22px; }
.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; }
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 { columns: 470px; column-gap: 24px; }
.stepcols table { break-inside: avoid; }
@media (max-width: 600px) {
.stepcols { columns: auto; overflow-x: auto; }
#steps input[type=text] { width: 84px; }
#steps input[type=number] { width: 42px; }
#steps th, #steps td { padding-right: 3px; }
}
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: four channel strips as on the device's TRACKS page */
.mixer { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; max-width: 640px; margin: 6px 0; }
.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; }
[hidden] { display: none !important; }
</style>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Michroma&amp;family=IBM+Plex+Mono:wght@400;500;600&amp;family=Instrument+Sans:wght@400;500;600&amp;family=Noto+Sans+JP:wght@400;500&amp;display=swap">
<style id="jiant-brand">/*JIANT_UI*/</style>
</head>
<body class="jiant-editor">
<main>
<button class="lang" id="lang"></button>
<h1 class="jiant-wordmark"><a href="https://juanjiant-bit.github.io/JIANT/" aria-label="JIANT FM home">JIANT<span class="fm">FM</span></a><span class="jiant-tool">EDITOR</span></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 id="mock" class="dim" hidden data-t="mock"></span>
</div>
<div id="status"></div>
<details id="midiports"><summary data-t="midiPorts"></summary><p id="midiportcounts" class="dim"></p><p class="dim" data-t="midiPortHelp"></p><p class="bar">
<label><span data-t="midiInput"></span> <select id="midiinput"><option value="">Auto</option></select></label>
<label><span data-t="midiOutput"></span> <select id="midioutput"><option value="">Auto</option></select></label>
</p></details>
<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="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="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>
<div class="group" id="lyricbox" hidden><h3 data-t="lyricT"></h3>
<p class="dim" data-t="lyricHelp"></p>
<p class="bar"><label><span data-t="lyricLang"></span> <select id="lyrlang"></select></label>
<label><span data-t="lyricSrc"></span> <select id="lyrsrc"></select></label></p>
<p class="bar"><input id="lyric" maxlength="256" size="56" autocomplete="off" spellcheck="false">
<button id="lyricsend" data-t="lyricSend"></button></p>
<p class="dim" id="lyric-preview" aria-live="polite"></p>
<p class="dim">RU: transliteración automática / automatic transliteration. ZH: pinyin.
SEQ → LYRIC STEP: STEP, WORD, SYLLABLE, OCT+ PLACE. TEXT FIXED + POS repite la sílaba elegida / repeats the selected syllable. SYLLABLE 0 = AUTO.</p></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-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-projects" data-tab="projects" data-dev hidden>
<h2 data-t="projects" data-ic="symbol_folder"></h2>
<p class="dim" data-t="projHelp"></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>
<div class="group" id="songchain" hidden style="margin-top:16px">
<h2 data-t="songTitle"></h2>
<p class="dim" data-t="songHelp"></p>
<p class="bar"><button id="songplay"></button><button id="songadd" data-t="songAdd"></button>
<button id="songremove" data-t="songRemove"></button><span id="songstatus" aria-live="polite"></span></p>
<div id="songrows"></div>
</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" style="margin-top:12px">
<h2 data-t="system" data-ic="symbol_cog"></h2>
<table id="sysinfo"></table>
</div>
</section>
<p class="kofi" style="margin-top:24px;border-left:3px solid #ec6e50;padding:4px 0 4px 12px">If you resonate with my work, consider supporting me on <a href="https://ko-fi.com/juanjiant" target="_blank" rel="noopener" style="color:inherit;font-weight:600">Ko-fi</a> (in Argentina: <a href="https://cafecito.app/juanjiant" target="_blank" rel="noopener" style="color:inherit;font-weight:600">Cafecito</a>). Thanks for all the good energy, hope you enjoy this little beast 🫶✨🎹</p>
<footer>JIANT FM by Juan Jiant. 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,
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, LYRIC: 39,
MOTION: 64, BACKUP_LIST: 65, BACKUP_GET: 66, BACKUP_PUT: 67,
FM6_GET: 68, FM6_PUT: 69, FM6_LIST: 70, FM6_ERASE: 71,
FM6B_BEGIN: 74, FM6B_WRITE: 75, FM6B_END: 76, FM6B_LIST: 77, /* (JIANT 0.6.11, Felucca 1.4.1) FM6's voice bank */
};
/* 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 };
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];
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");
if (r.i + 8 <= r.a.length) { /* (0.8.5, INFO 4F 01 07) each DRUM lane's mode 0..6; older firmware: none */
o.lanes = [];
for (let l = 0; l < 8; l++) { const m = r.b(); if (m > 6) throw new Error("Invalid step lane mode"); o.lanes.push(m); }
}
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.fm6Bank = 0; /* (JIANT 0.6.11) FM6's voice bank: its voices (cmds 74..77), 0 = none */
o.laneModes = 0; /* (JIANT 0.8.5) a step's DRUM lane modes (7: none x2 x4 x8 SHORT GHOST FLAM) */
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) r += 3; /* and the MENU settings (1.0.4) */
if (o.syncCaps && trailer[r] === 0x52 && trailer[r + 1] === 1) { o.ratchet = trailer[r + 2]; r += 3; } /* RATCH: max hits */
if (trailer[r] === 0x4C && trailer[r + 1] === 1) r += 3; /* parameter locks (1.1) */
if (trailer[r] === 0x56 && trailer[r + 1] === 1) o.fm6Bank = trailer[r + 2]; /* (0.6.11) the voice bank's size */
for (let k = r; k + 2 < trailer.length; k += 3) /* (0.8.5) 'O': the steps' lane modes */
if (trailer[k] === 0x4F && trailer[k + 1] === 1) { o.laneModes = trailer[k + 2]; break; }
}
/* (JIANT 0.8.5) 'Y' 1 n, the last tag: LYRIC (cmd 39), a track's lyric of at most n bytes; 0 = none */
const ty = trailer.length - 3;
o.lyric = ty >= 0 && trailer[ty] === 0x59 && trailer[ty + 1] === 1 ? trailer[ty + 2] : 0;
return o;
},
[CMD.LYRIC](a) { const r = new Reader(a); return { track: r.b(), rc: r.b(), text: r.s() }; },
[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 { scope: r.b(), id: 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 = { scope: r.b(), id: 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 < 32; i++) o.names.push(r.s()); /* (0.7.0: 32, was 24) */
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() }; },
[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: [] };
if (o.count > o.max || o.max !== 64 || a.length !== 5 + o.count * 4) throw new Error("Invalid motion reply");
for (let i = 0; i < o.count; i++) o.events.push({ step: r.b(), param: r.b(), value: r.v() });
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.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) { const r = new Reader(a); return { slot: r.b(), rc: r.b() }; },
[CMD.UP_STORE](a) { return parse[CMD.UP_PUT](a); },
[CMD.UP_LOAD](a) { return parse[CMD.UP_PUT](a); },
[CMD.UP_ERASE](a) { return parse[CMD.UP_PUT](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); return { track: r.b(), id: r.b(), value: r.v() }; },
[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] }; },
/* (JIANT 0.6.11, Felucca 1.4.1) FM6's voice bank, EDITOR_PROTOCOL.md "FM6 voice bank (74-77)" */
[CMD.FM6B_BEGIN](a) { return { rc: a[0] }; },
[CMD.FM6B_WRITE](a) { return { index: a[0], rc: a[1] }; },
[CMD.FM6B_END](a) { return { rc: a[0], voices: a[1] }; },
[CMD.FM6B_LIST](a) {
const r = new Reader(a), o = { n: r.b(), valid: !!r.b(), name: r.s(), voices: [] };
for (let i = 0; i < o.n; i++) { const used = !!r.b(); o.voices.push({ used, name: r.s() }); }
return o;
},
};
/* (JIANT 0.8.5) a lyric the device takes: printable ASCII, at most 63 characters; accents dropped (the device has none:
stress is not marked in singing), the enye as "ny" (as the device reads it: sing.c sy_es) */
function lyricText(s, language = "") {
let text = String(s ?? "").replace(/[’‘]/g, "'");
if (language === "RU") {
const abc = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
const latin = ["a","b","v","g","d","e","yo","zh","z","i","y","k","l","m","n","o","p","r","s","t","u","f","kh","ts","ch","sh","shch","","y","","e","yu","ya"];
text = text.replace(/[а-яё]/gi, c => latin[abc.indexOf(c.toLowerCase())]);
}
if (language === "DE") text = text.replace(/[äöüß]/gi, c => ({ä:"ae",ö:"oe",ü:"ue",ß:"ss"})[c.toLowerCase()]);
if (language === "ZH") text = text.replace(/[üǖǘǚǜ]/gi, "v");
if (language === "FR") text = text.replace(/[é]/gi, "ei").replace(/[èê]/gi, "eh").replace(/[œ]/gi, "oe")
.replace(/(?:an|en)(?=[^aeiouy]|$)/gi,"a~").replace(/on(?=[^aeiouy]|$)/gi,"o~").replace(/(?:in|ain)(?=[^aeiouy]|$)/gi,"e~");
if (language === "PT" || language === "GN") text = text.normalize("NFD").replace(/([aeiouy])\u0303/gi,"$1~");
text = text.replace(/[çÇ]/g,"s").replace(/[ñÑ]/g, c => c === "ñ" ? "ny" : "NY").normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[¿¡]/g, "");
if (language && /[^\x20-\x7E\r\n\t]/.test(text)) throw new Error("Usá letras latinas / Use Latin transliteration (ZH: pinyin).");
text = text.replace(/[\r\n\t]/g," ").replace(/[^\x20-\x7E]/g, " ");
if (language && text.length > 63) throw new Error(`${text.length}/63: acortá la letra transliterada / shorten the transliterated lyric.`);
return text.slice(0,63);
}
/* a name the device accepts: printable ASCII, 1..12 characters */
function upName(s) { return String(s ?? "").replace(/[^\x20-\x7E]/g, "").trim().slice(0, UP.NAME_MAX) || "PATCH"; }
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]],
lyric: (track, text) => [CMD.LYRIC, text == null ? [track] : [track, ...strEnc(lyricText(text))]], /* (0.8.5) */
info: () => [CMD.INFO, []],
get: (scope, id) => [CMD.GET, [scope, id]],
set: (scope, id, v) => [CMD.SET, [scope, id, ...v14enc(v)]],
dump: () => [CMD.DUMP, []],
desc: (scope, id) => [CMD.DESC, [scope, id]],
stepGet: (i, lanes) => [CMD.STEP_GET, lanes ? [i, 1] : [i]], /* (0.8.5: lanes, INFO 4F 01: the lanes' modes too) */
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.lanes ? [] : /* (0.8.5) the lanes' modes: only after the ratchet, */
Array.from({ length: 8 }, (_, l) => Math.max(0, Math.min(6, st.lanes[l] | 0))))]]; /* read from a device that has them */
},
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 > 64)) 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 = {}) => {
if (!Number.isInteger(track) || track < 0 || track > 5 || ![0, 1, 2, 3, 4].includes(op)) throw new Error("Invalid motion request");
return [CMD.MOTION, [track, ...(op === 0 ? [] : op === 1 ? [op, arg.on ? 1 : 0] : op === 2 ? [op] :
[op, arg.step & 63, arg.param & 127, ...(op === 3 ? v14enc(arg.value) : [])])]];
},
names: (e) => [CMD.NAMES, [e & 0x7F]],
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, lanes) => [CMD.TRACK_STEP, st ? [tr & 0x7F, ...req.stepSet(i, st)[1]] : lanes ? [tr & 0x7F, i & 0x7F, 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, v == null ? [tr & 0x7F, id & 0x7F] : [tr & 0x7F, id & 0x7F, ...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]],
/* (0.6.11) the voice bank: BEGIN, a WRITE per voice (index, the 128-byte record), END (name, the CRC of the records
written, in index order: 5 x 7 bits), LIST */
fm6bBegin: () => [CMD.FM6B_BEGIN, []],
fm6bWrite: (i, packed) => [CMD.FM6B_WRITE, [i & 0x7F, ...packed.map((x) => x & 0x7F)]],
fm6bEnd: (name, crc) => [CMD.FM6B_END, [...String(name ?? "").padEnd(10, " ").slice(0, 10)].map((c) => c.charCodeAt(0) & 0x7F)
.concat([0, 7, 14, 21, 28].map((sh) => (crc >>> sh) & 0x7F))],
fm6bList: () => [CMD.FM6B_LIST, []],
};
/* 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.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.LYRIC: return a[0] === args[0];
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: return a[0] === args[0];
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.FM6B_WRITE: 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"));
}
}
/* the names an FM-1 shows under (the installer's fm1ota.js PORT_RE: JIANT, Felucca, Skiff, the stock firmware's, the
USB composite's, and the generic names Windows gives a USB MIDI device whose name it cached or never read) */
const editorPort = (p) => /felucca|jiant|skiff|fm[ _-]*1|m[ _-]*vave|cuvave|composite|sinco|usb[ _-]*midi|usb audio/i.test(p.name || "") && p.state !== "disconnected";
/* (2026-10-30) never asked: software ports and other makers' synths a user is likely to have plugged in */
const notEditorPort = (p) => /wavetable|iac driver|midi through|loopmidi|loopbe|virtual|rtpmidi|network|bluetooth/i.test(p.name || "");
let seenPorts = "";
async function openEditorMidi(access, hooks = {}, selected = {}) {
const live = (ports) => [...ports.values()].filter(p => p.state !== "disconnected");
const select = (ports, id) => live(ports).filter(p => id ? p.id === id : editorPort(p));
let inputs = select(access.inputs, selected.input), outputs = select(access.outputs, selected.output);
seenPorts = [...new Set([...live(access.inputs), ...live(access.outputs)].map(p => p.name || p.id))].join(", ");
/* none under a name we know: every other port is asked (INFO, then the reply's "JIANT" / "FELUCCA" decides): a host
that shows the FM-1 under a name of its own still finds it */
if ((!inputs.length || !outputs.length) && !selected.input && !selected.output) {
inputs = live(access.inputs).filter(p => !notEditorPort(p));
outputs = live(access.outputs).filter(p => !notEditorPort(p));
}
if (!inputs.length || !outputs.length) throw new Error("no MIDI ports");
const pairs = inputs.flatMap(input => outputs.map(output => ({ input, output,
score: (input.name === output.name ? 2 : 0) + (input.manufacturer && input.manufacturer === output.manufacturer ? 1 : 0) })));
pairs.sort((a,b) => b.score-a.score);
let last;
for (const {input, output} of pairs) {
const link = new Link(d => output.send(d), { ...hooks, timeout: 600 });
try {
if (input.open) await input.open();
if (output.open) await output.open();
input.onmidimessage = e => link.receive(e.data);
const info = parse[CMD.INFO](await link.request(req.info(), { timeout: 800, retries: 2, quiet: true }));
if (!/^(?:JIANT|FELUCCA)\b/i.test(info.version || "")) throw new Error("Not a JIANT editor device");
return {input, output, link, info};
} catch (e) {
last = e; link.close(); input.onmidimessage = null;
await Promise.allSettled([input.close?.(), output.close?.()]);
}
}
throw last;
}
/* ------------------------------------------------------------- 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 || d.max === 120 ? v : Math.trunc((v * 100 + 63) / 127)), "%"]; /* 0..100 (SWG): the value */
case F.BIPCT: return [sign(Math.trunc(v * 100 / 64)), "%"];
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: {
if (v < 0) return [["4BAR", "2BAR", "1BAR", "1/2", "1/4", "1/8D", "1/4T", "1/8", "1/8T", "1/16", "1/16T", "1/32", "8BAR", "16BAR"][(-v - 1) % 14], ""]; /* (0.6.51) in time; V10.27: 8BAR 16BAR */
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"];
default: return d.label === "PHASE" && v < 0 ? ["FREE", ""] : [String(v), d.unit || ""]; /* (0.6.51) the LFO's PHASE */
}
}
/* -------------------------------------------------------------- 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": ["LVL", "ATK", ...], one key per parameter id: the DESC label, "#2", "#3" appended to
a repeated label (PIT, PIT#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]);
/* values by fromKeys -> values by toKeys (null where the source has no such key) */
/* (JIANT 0.6.24) the labels made readable (LVL -> LEVEL, SWG -> SWING, ...): a file's keys from before, renamed and
numbered again in their order, as paramKeys numbers today's */
const LEGACY_LABEL = { LVL: "LEVEL", FLT: "FILTER", PIT: "PITCH", SHP: "SHAPE", PHS: "PHASE", SWG: "SWING", ORD: "ORDER",
SCL: "SCALE", QNT: "QUANT", TRN: "TRANS", DST: "DIST", CHO: "CHORUS", VCE: "VOICE", GLD: "GLIDE", GLMOD: "MODE",
DPTH: "DEPTH", OFS: "OFFSET", DTUNE: "DETUNE", DST1: "DEST1", DST2: "DEST2", DST3: "DEST3", DST4: "DEST4" };
function legacyKeys(keys) {
if (!keys) return keys;
const seen = {};
return keys.map((k) => {
if (/^E[0-7]$/.test(k)) return k;
let b = String(k).split("#")[0];
b = LEGACY_LABEL[b] || b;
seen[b] = (seen[b] || 0) + 1;
return seen[b] > 1 ? `${b}#${seen[b]}` : b;
});
}
function remapParams(p, fromKeys, toKeys, pe0) {
if (!fromKeys && toKeys && pe0 && p.length !== toKeys.length) return tailParams(p, toKeys.length, pe0);
fromKeys = legacyKeys(fromKeys);
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 === "SAMPLE" && ctx.engines.indexOf(nm) < 0) return 4; /* (JIANT: retired; its PERC sounds still become DRUM) */
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 = Array.isArray(obj.paramLabels) && obj.paramLabels.length ? obj.paramLabels.map(String) : null;
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) */
/* zlib's CRC-32 (the voice bank's END: of the records written, in index order) */
function crc32(bytes, c = 0xFFFFFFFF) {
for (const x of bytes) { c ^= x; for (let k = 0; k < 8; k++) c = (c >>> 1) ^ (0xEDB88320 & -(c & 1)); }
return (c ^ 0xFFFFFFFF) >>> 0;
}
/* (JIANT 0.6.11, Felucca 1.4.1) FM6's voice bank on the device: 32 voices in flash, SLOT B1..B32 picks them. A 32-voice
.syx is sent whole (fm6_vbank.c: the old bank stays until END answers 0, a power cut leaves one or the other) */
const fm6Bank = {
N: 32,
/* the voices of an import ({name, v} or 155-byte voices; null: an empty slot) -> 128-byte records */
fromVoices: (voices) => Array.from({ length: Math.min(32, voices.length) }, (_, k) => {
const x = voices[k]; return x ? FM6.pack(x.v || x) : null;
}),
/* the bank's name from a file name: its base, capitals, printable ASCII, 10 at most */
nameOf: (file) => String(file ?? "").replace(/\.[^.]*$/, "").toUpperCase().replace(/[^\x20-\x7E]/g, " ").trim().slice(0, 10).trim(),
async list(rq) { return parse[CMD.FM6B_LIST](await rq(req.fm6bList())); },
/* packed: up to 32 records (null: not written, empty in the new bank) -> END's rc (0: the new bank is on the device) */
async send(rq, packed, name) {
let rc = parse[CMD.FM6B_BEGIN](await rq(req.fm6bBegin(), { timeout: 3000, retries: 0 })).rc; /* (no retries: a WRITE twice is rc 1) */
if (rc) return rc;
const done = [];
for (let k = 0; k < Math.min(32, packed.length); k++) {
if (!packed[k]) continue;
rc = parse[CMD.FM6B_WRITE](await rq(req.fm6bWrite(k, packed[k]), { timeout: 2000, retries: 0 })).rc;
if (rc) return rc;
done.push(...packed[k].map((x) => x & 0x7F));
}
return parse[CMD.FM6B_END](await rq(req.fm6bEnd(name, crc32(done)), { timeout: 5000, retries: 0 })).rc;
},
};
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 = info.engines[dump.engine] === "DRUM"; /* (a DRUM 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 SHIFT offsets OFS PIT (81, 82,
once the chord keys CHRD VOIC; 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_SHIFT = [81, 82]; /* core.h P_SOFS, P_POFS (since P_COUNT 91, P_E0 83; the chord keys before JIANT) */
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 trackOwn = (i, pe0) => TRACK_OWN.has(i) || (pe0 >= 83 && P_SHIFT.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)} */
async function auditionPatch(rq, info, pt, opt = {}) {
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 all four) 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) {
const tr = parse[CMD.TRACK](await rq(req.track()));
for (let i = 0; i < tr.ntrk; i++) {
const d = parse[CMD.TRACK_DUMP](await rq(req.trackDump(i)), info);
tr.tracks[i].pan = ids.pan == null ? null : d.p[ids.pan];
}
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) {
if (v4) return parse[CMD.TRACK_PARAM](await rq(req.trackParam(track, panId, v), { key: "pan:" + track })).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;
p[ATK] = p[ATK + 1] = p[ATK + 3] = 0; p[ATK + 2] = 127; /* (0.6.81) the ADSR in the operators': FM6's neutral */
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 = [64, 64, 70, 64, 64, 0, 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 === "SAMPLE" || (pt.engine === 4 && (!name || name === "-"))) || !Array.isArray(p) || drum < 0) return null; /* (4: "-" once retired) */
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 NDTIME = ["1/4", "1/8", "1/16", "1/32", "8T", "16T", "1/2", "1/1", "2BAR", "4BAR", "5ms", "6ms", "7ms", "8ms", "9ms", "10ms", "11ms", "12ms", "13ms", "15ms", "17ms", "19ms", "21ms", "24ms", "27ms", "31ms", "35ms", "39ms", "44ms", "50ms", "56ms", "64ms", "72ms", "81ms", "91ms", "103ms", "116ms", "131ms", "148ms", "167ms", "189ms", "213ms", "241ms", "272ms", "307ms", "346ms", "391ms", "441ms", "498ms", "562ms", "634ms", "716ms", "808ms", "912ms", "1.03s", "1.16s", "1.31s", "1.48s", "1.67s", "1.89s", "2.13s", "2.40s", "2.71s", "2.95s"]; /* (JIANT 0.4) the delay's TIME: the divisions, then free times (0.8.4: to 2.95 s) */
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", "M1", "M2", "M3", "M4", "STEP", "NOISE", "PROX", "ENV2"]; /* (V10.14 PROX, V10.22 ENV2) */
const MDST = ["OFF", "PITCH", "CUT", "SHP", "AMP", "PAN", "DIST", "CHO", "DLY", "REV", "RATE", "VIB", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "CLIP", "PNCH", "D.TIM", "D.FB", "D.TON", "D.MIX", "R.SIZ", "R.DMP", "C.RAT", "C.DEP"];
const TP = [
D("LEVEL", F.DB, 0, 127, 104),
D("ATK", F.TIME, 0, 127, 10), D("DEC", F.TIME, 0, 127, 70), D("SUS", F.PCT, 0, 127, 90), D("REL", F.TIME, 0, 127, 60),
D("FILTER", F.BIPCT, -64, 63, 0), D("PITCH", F.BIPCT, -64, 63, 0), D("SHAPE", F.BIPCT, -64, 63, 0), E("LOOP", ["OFF", "ON"], 0), /* (JIANT 0.4: P_ED_FX is the ENV LOOP) */
D("RATE", F.LFOHZ, -14, 127, 60), E("WAVE", ["SIN", "TRI", "SAW", "SQR", "S&H", "DRIFT"], 0), D("PHASE", F.INT, -1, 127, 0), D("FADE", F.TIME, 0, 127, 0), /* (0.6.51) RATE < 0 in time, PHASE -1 FREE (0.9.18: shown as MODE TRIG / FREE, lfoModeRows) */
D("PITCH", F.BIPCT, -64, 63, 0), D("FILTER", 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", "TRNS"], 0), E("RATE", NDIV, 2), D("OCT", F.INT, 1, 4, 1), D("GATE", F.PCT, 1, 127, 64),
D("SWING", F.PCT, 0, 100, 0), D("PROB", F.PCT, 0, 127, 127), E("HOLD", NONOFF, 0), E("ORDER", ["NOTE", "PLAY"], 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("QUANT", ["OFF", "SNAP", "WHITE", "SEQ"], 0), D("TRANS", F.SEMI, -24, 24, 0),
D("LEN", 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("DLY", F.PCT, 0, 127, 0), D("REV", 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("MODE", ["RATE", "TIME"], 0), E("PRIO", ["LAST", "LOW", "HIGH"], 0), E("ALLOC", ["ROT", "REUSE"], 0), D("DETUNE", F.INT, 0, 127, 40),
D("DEPTH", F.PCT, 0, 127, 0), D("RATE", F.LFOHZ, 0, 127, 2), E("WAVE", ["SIN", "TRI", "SAW", "SQR", "S&H"], 1), E("SYNC", ["FREE", "BEAT"], 1), /* (JIANT 0.6.9) AUTO PAN, in the old per-track SLICER's slots (BEAT: RATE 0..7, 4BAR .. 1/32) */
...[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+BT", "TRS"], 0), D("TUNE", F.INT, -50, 50, 0),
E("TIME", NDTIME, 1), D("FEEDBK", F.PCT, 0, 120, 60), D("TONE", F.PCT, 0, 127, 64), D("MIX", F.PCT, 0, 127, 90), /* (JIANT 0.4: free
times past the divisions; TONE: COLR + HPF in one) */
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), D("REL", F.PCT, 0, 100, 30), /* G_DREL (was SYNC): DUCK's release */ E("ROUTE", ["CH1-6", "SEL"], 0), D("CPU", F.INT, 0, 0, 0),
D("SLOT", F.INT, 1, 4, 1), D("DJ FILT", F.BIPCT, -64, 63, 0), E("LOAD", NGO, 0), E("SAVE", NGO, 0), /* (0.9.1) G_DJF 17 (was NAME, "--"): the master DJ FILTER */
E("ENG", ["ANALOG", "-", "PHASE", "LOFI", "-", "VOICE", "-", "WHEEL",
"STRING", "-", "DRUM", "NOISE", "FM6", "ADD", "ANIMAL"], 0), D("CLIP", F.PCT, 0, 100, 0), /* G_CLIP (was SET); 0.8.3 ANIMAL; snd5 STRING 8 ADD 13 */
E("CLRSQ", NGO, 0), E("INIT", NGO, 0),
E("TYPE", ["ROOM", "SPRING", "SHIMR", "RESO", "CLOUD"], 0), /* G_RTYPE (id 24, was G_DRCH): the reverb's model */
D("PUNCH", F.PCT, 0, 100, 0), D("DUCK", F.PCT, 0, 100, 0), /* G_PUNCH, G_DUCK (JIANT; were G_DRLVL, G_DRREV) */
D("STEREO", F.BIPCT, -64, 63, 0), D("WIDE", F.PCT, 0, 127, 0), /* (JIANT, FUNB) G_DHPF (0.6.9: G_CSTER, the CHORUS's stereo), G_WIDTH: width */
D("MOD", F.PCT, 0, 127, 0), D("RATE", F.LFOHZ, 0, 127, 30), D("PRE", F.INT, -24, 100, 0), /* the reverb's modulation, pre-delay (0.6.12: SHIMMER / CLOUD AIR below 0) */
D("FILT", F.BIPCT, -64, 63, 0), D("WIDE", F.PCT, 0, 127, 0), /* (JIANT 0.3) G_RFILT, G_RWIDE: the reverb's tone, width */
D("PITCH", F.SEMI, -12, 12, 0), D("SPRAY", F.PCT, 0, 127, 0), /* .. G_DPIT, G_DSPRY: the GRAIN delay */
D("ALL TR", F.INT, -14, 14, 0), /* (JIANT 0.4) G_STRN: every sequence this many steps along the scale */
/* (JIANT 0.6.3) G_SLMODE 37 ..: the SLICER, one on a bus: mode, pattern, rate, depth; T1..T6 and FX in; the repeats'
pitch sequence: LEN, QNT, 16 steps */
E("MODE", ["OFF", "GATE", "STUT"], 0), D("PAT", F.INT, 1, 16, 1), E("RATE", ["1/8", "1/16", "1/32", "8T", "16T", "32T"], 1), D("DEPTH", F.PCT, 0, 127, 127),
...["T1", "T2", "T3", "T4", "T5", "T6", "FX"].map((l) => E(l, ["OFF", "ON"], 1)),
D("LEN", F.INT, 1, 16, 16), E("QUANT", ["CHR", "SCL"], 1),
...Array.from({ length: 16 }, () => D("PITCH", F.SEMI, -24, 24, 0)),
D("MOD", F.PCT, 0, 127, 0), /* (0.6.86) G_DMOD 66: the delay's tape drift (WOW, FLUTTER) */
E("TYPE", ["ANALOG", "DIGITAL"], 0), E("PING", ["OFF", "ON"], 0), /* (0.6.90) G_DTYPE 67, G_DPING 68 */
D("LEN", F.INT, 1, 64, 64), E("RES", ["1/8", "1/16", "1/32"], 1), /* (0.6.99) G_PFXLEN 69, G_PFXRES 70: the punch-in lane */
D("DRIVE", F.PCT, 0, 100, 0), /* (0.9.9-snd2) G_DDRV 71: the delay's loop driven */
];
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, xp = 0) => ({ name, e, env, mono, pat, xp }); /* xp (0.8.5):
VOICE's LANG | LYRIC << 2 */
const ENG = [
{ name: "ANALOG", titles: ["OSC", "FLT"], edit: [E("WAVE", ["SAW", "SQR", "TRI", "SIN", "PWM", "SYNC", "RING", "SAW3", "PLS3"], 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("CUT", F.CUTOFF, 0, 127, 90), D("RES", F.PCT, 0, 127, 30), D("DRIVE", F.PCT, 0, 127, 0), D("INT", F.SEMI, -24, 24, 0)], /* (JIANT 0.4: INT, osc 2's interval, was KTR) */
presets: [P("SAW LEAD", [0, 12, 64, 0, 90, 30, 10, 12], [4, 70, 100, 50], 1, 4), P("SOFT PAD", [0, 20, 64, 4, 60, 10, 0, 0], [80, 90, 110, 95], 0, 5),
P("SQR BASS", [1, 0, 0, 0, 50, 70, 40, 0], [0, 60, 40, 30], 1, 2), P("PWM STR", [4, 8, 40, 0, 75, 20, 0, 0], [60, 80, 110, 85], 0, 5),
P("ACID", [0, 0, 0, 0, 50, 100, 25, 0], [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, 7], [20, 80, 110, 60], 1, 13), P("SUB BASS", [3, 0, 0, 0, 40, 0, 20, 0], [0, 60, 100, 20], 1, 8),
P("PLUCK", [0, 8, 50, 0, 30, 40, 0, 0], [0, 88, 0, 60], 0, 3), P("BRASS", [0, 10, 64, 0, 45, 20, 10, 0], [35, 70, 90, 45], 0, 6),
P("WIND", [0, 0, 0, 90, 30, 90, 0, 0], [60, 90, 60, 80], 0, 5), P("STRINGS", [0, 25, 64, 0, 70, 10, 0, 0], [70, 90, 115, 90], 0, 5),
P("SYNC LEAD", [5, 11, 90, 0, 82, 30, 10, 0], [2, 70, 100, 40], 1, 4), P("RING BELL", [6, 18, 100, 0, 110, 20, 0, 0], [0, 92, 0, 80], 0, 7),
P("FAT BASS", [7, 9, 64, 0, 62, 45, 20, -12], [0, 62, 60, 25], 1, 2), P("JUNO PAD", [4, 14, 64, 2, 58, 12, 0, 0], [45, 90, 115, 90], 0, 5),
P("REESE", [7, 22, 64, 0, 44, 20, 25, 0], [2, 80, 110, 40], 1, 2), P("HOOVER", [7, 40, 64, 0, 92, 15, 35, 12], [10, 80, 110, 55], 1, 13),
P("DUB STAB", [1, 6, 64, 0, 52, 55, 10, 7], [0, 50, 20, 45], 0, 6), P("CELLO", [0, 4, 40, 2, 48, 18, 15, -12], [30, 85, 110, 70], 0, 5),
P("ARP PLUCK", [1, 10, 50, 0, 44, 50, 0, 12], [0, 62, 0, 40], 0, 3), P("MOOG LEAD", [2, 6, 40, 0, 72, 40, 40, -12], [6, 75, 100, 45], 1, 4),
P("DARK PAD", [0, 18, 64, 6, 38, 30, 10, -12], [70, 95, 120, 100], 0, 5), P("GLASS KEYS", [3, 8, 60, 0, 120, 0, 0, 19], [0, 82, 20, 65], 0, 6),
P("ORGAN SQR", [1, 4, 64, 0, 100, 0, 5, 12], [0, 64, 127, 30], 0, 6)] },
/* 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: ["PHS", "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("FB", F.PCT, 0, 127, 0)],
presets: [P("BRASS", [0, 0, 30, 90, 0, 0, 0, 0], [8, 70, 90, 40], 0, 6), P("ORGAN", [3, 0, 40, 0, 0, 0, 0, 0], [0, 127, 127, 30], 0, 6),
P("STRING", [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("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),
P("GROWL", [0, 0, 70, 80, 0, 0, 40, 55], [2, 70, 90, 40], 1, 4), P("FB BASS", [1, 0, 45, 60, 0, 0, 70, 35], [0, 60, 60, 25], 1, 2),
P("CZ PIANO", [3, 0, 55, 85, 0, 0, 15, 0], [0, 78, 30, 55], 0, 6), P("GLASS PAD", [6, 5, 45, 35, 14, 0, 0, 0], [60, 90, 115, 95], 0, 5),
P("DIGI STAB", [4, 2, 75, 70, 0, 1, 0, 0], [0, 55, 20, 40], 0, 6), P("SYN BASS", [1, 0, 50, 70, 0, 0, 60, 0], [0, 58, 50, 25], 1, 2),
P("VOX PAD", [5, 4, 35, 30, 10, 0, 0, 0], [70, 95, 115, 100], 0, 5), P("HARP", [3, 0, 70, 90, 0, 0, 0, 0], [0, 85, 0, 70], 0, 3),
P("PD LEAD", [0, 2, 65, 55, 9, 0, 20, 10], [4, 70, 95, 45], 1, 4), P("RING KEYS", [2, 4, 60, 60, 0, 1, 0, 0], [0, 75, 25, 60], 0, 6)] },
{ name: "LOFI", titles: ["CHIP", "TONE"], edit: [E("CHIP", ["4BIT", "4B/2", "8BIT", "1BIT", "STEP"], 0), E("WAVE", ["PLS", "TRI", "SAW", "NOIS", "WRAM", "BYTE", "FLOAT"], 0), D("DUTY", F.INT, 0, 127, 64),
D("CRUSH", F.PCT, 0, 127, 0), D("CUT", F.CUTOFF, 0, 127, 110), D("VIB", F.PCT, 0, 127, 0), D("BEND", F.PCT, 0, 127, 0), D("MASK", F.PCT, 0, 127, 0)], /* (JIANT 0.4: CUT BEND MASK) */
presets: [P("BYTEBEAT", [2, 5, 4, 0, 64, 0, 0, 0], [0, 80, 110, 40], 1, 4), P("BYTE VAR", [2, 5, 64, 40, 64, 0, 0, 0], [0, 80, 110, 50], 1, 3),
P("BYTE BENT", [2, 5, 16, 0, 64, 24, 70, 0], [0, 80, 110, 45], 1, 4), P("PULSE LD", [0, 0, 32, 0, 127, 20, 0, 0], [0, 60, 90, 30], 1, 4),
P("WAVE BASS", [1, 1, 0, 0, 90, 0, 0, 0], [0, 50, 70, 20], 1, 2), P("8BIT KEYS", [2, 0, 96, 0, 110, 0, 30, 0], [0, 60, 80, 40], 0, 13),
P("WAVE LEAD", [0, 4, 92, 0, 110, 18, 0, 0], [0, 70, 90, 30], 1, 3), P("STEP LEAD", [4, 0, 40, 34, 127, 16, 0, 0], [0, 64, 127, 55], 1, 4),
P("BYTE TONE", [2, 5, 40, 0, 64, 0, 0, 80], [0, 70, 100, 40], 1, 4), P("FLOAT FM", [2, 6, 4, 0, 64, 0, 0, 0], [0, 60, 90, 40], 1, 4),
P("FLOAT ARP", [2, 6, 8, 0, 64, 0, 0, 0], [0, 50, 80, 50], 1, 3), P("FLOAT PAD", [2, 6, 112, 0, 40, 0, 0, 0], [60, 90, 110, 90], 1, 3),
P("CHIP PAD", [0, 1, 64, 0, 90, 12, 0, 0], [40, 90, 115, 80], 0, 5), P("GB ARP", [2, 0, 16, 0, 120, 0, 0, 0], [0, 55, 0, 35], 0, 3),
P("TRI BASS", [0, 1, 64, 0, 80, 0, 0, 0], [0, 60, 90, 20], 1, 2), P("SOFT CHIP", [1, 0, 64, 0, 85, 8, 0, 0], [5, 70, 80, 50], 0, 6),
P("SAW CHIP", [2, 2, 64, 0, 100, 10, 0, 0], [0, 65, 90, 35], 1, 4), P("PULSE BASS", [0, 0, 40, 0, 70, 0, 0, 0], [0, 55, 80, 15], 1, 2)] },
/* 4: reserved (SAMPLE, retired in JIANT; its sounds load as ANALOG, its PERC set as DRUM) */
{ name: "-", titles: ["-", "-"], edit: [D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0),
D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0)],
presets: [] },
{ name: "VOICE", titles: ["VOWL", "TONE"], edit: [D("VOWEL", F.INT, 0, 127, 0), D("VOWEL2", F.INT, 0, 127, 64), D("TALK", F.TIME, 0, 127, 0),
D("SHIFT", 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("RAND", 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),
P("OOH PAD", [80, 100, 50, 0, 55, 25, 55, 0], [70, 90, 115, 95], 0, 5), P("CHANT", [20, 60, 100, -12, 70, 15, 65, 10], [30, 90, 110, 80], 0, 5),
P("TALK BOX", [10, 110, 40, 0, 110, 4, 85, 0], [2, 65, 95, 40], 1, 4),
/* (0.8.5) WORDS (src/sing.c): LANG 1 ES 2 EN 3 JA, LYRIC 0 TEXT 1..16 W1..W16 17..24 S1..S8 (xp = LANG | LYRIC << 2) */
P("CANTOR ES", [0, 64, 0, 0, 80, 6, 72, 0], [24, 70, 112, 72], 1, 4, 1 | 1 << 2),
P("CANTORA ES", [0, 0, 0, 4, 70, 10, 74, 0], [26, 70, 112, 72], 1, 4, 1 | 2 << 2),
P("SINGER EN", [0, 64, 0, 0, 84, 6, 72, 0], [24, 70, 112, 72], 1, 4, 2 | 3 << 2),
P("UTA JA", [0, 48, 0, 5, 76, 8, 74, 0], [24, 70, 112, 70], 1, 4, 3 | 4 << 2),
P("WORD CHOIR", [0, 64, 16, 0, 45, 20, 62, 0], [60, 90, 115, 85], 0, 5, 1 | 5 << 2),
P("SCAT EN", [0, 64, 0, 0, 96, 4, 76, 0], [16, 60, 100, 60], 1, 4, 2 | 17 << 2),
P("ROBOT EN", [0, 64, 0, -3, 127, 0, 90, 0], [2, 65, 120, 56], 1, 4, 2 | 6 << 2),
P("WHISPER JA", [0, 64, 0, 3, 50, 120, 52, 0], [40, 90, 110, 80], 0, 5, 3 | 7 << 2)] },
/* 6: reserved (TRIO, folded into ANALOG in JIANT 0.4: its sounds load as ANALOG's SYNC / RING / SAW3, core.h analog_from_trio) */
{ name: "-", titles: ["-", "-"], edit: [D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0),
D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0)],
presets: [] },
{ name: "WHEEL", titles: ["BARS", "TONE"], edit: [E("REG", ["FLUTE", "MELLO", "HOLLW", "SMOOT", "3BAR", "BLUES", "GOSPL", "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), P("PEDAL BASS", [0, 6, 0, -8, 0, 30, 15, 0], [0, 64, 127, 25], 1, 2),
P("DRIVE LEAD", [13, 0, 0, 3, 2, 60, 80, 1], [0, 64, 127, 35], 1, 4), P("CHURCH", [12, 0, 0, 0, 0, 0, 0, 0], [15, 64, 127, 70], 0, 5),
P("WAVE ORGAN", [8, 0, 0, 2, 3, 35, 15, 2], [0, 64, 127, 35], 0, 3), P("REED BASS", [14, 2, 0, -4, 0, 20, 10, 0], [0, 64, 127, 30], 1, 2)] },
/* 8: STRING (JIANT 0.9.9-snd5, src/eng_string.c; generated from it): Karplus-Strong in the COMB's lines (GRAIN's number, retired in JIANT) */
{ name: "STRING", titles: ["STRING", "BODY"], edit: [E("EXCITE", ["NOISE", "PLUCK", "PICK", "HAMMR", "STICK", "FDBK"], 1),
D("DECAY", F.PCT, 0, 127, 72), D("BRIGHT", F.PCT, 0, 127, 60), D("POS", F.PCT, 0, 127, 28), D("STRETCH", F.PCT, 0, 127, 0),
D("BODY", F.PCT, 0, 127, 40), D("SIZE", F.PCT, 0, 127, 40), D("BOW", F.PCT, 0, 127, 0)],
presets: [P("NYLON", [1, 72, 52, 28, 0, 60, 40, 0], [0, 64, 127, 104], 0, 3), P("STEEL GTR", [2, 86, 88, 24, 6, 40, 52, 0], [0, 64, 127, 104], 0, 3),
P("HARP", [1, 96, 62, 64, 0, 30, 30, 0], [0, 64, 127, 112], 0, 6), P("KOTO", [2, 78, 98, 14, 16, 30, 62, 0], [0, 64, 127, 104], 0, 5),
P("BANJO", [2, 52, 112, 10, 4, 90, 92, 0], [0, 64, 127, 96], 0, 4), P("PIANO", [3, 104, 76, 18, 42, 20, 22, 0], [0, 64, 127, 100], 0, 6),
P("DULCIMER", [3, 92, 100, 20, 26, 36, 60, 0], [0, 64, 127, 108], 0, 5), P("MARIMBA", [4, 56, 40, 64, 72, 80, 70, 0], [0, 64, 127, 96], 0, 5),
P("PLUCK BASS", [1, 62, 36, 20, 0, 50, 10, 0], [0, 64, 127, 80], 1, 2), P("BOWED", [0, 118, 46, 30, 0, 50, 40, 70], [30, 64, 127, 96], 0, 5),
P("KS NOISE", [0, 80, 127, 0, 0, 0, 0, 0], [0, 64, 127, 90], 0, 4), P("METAL STR", [0, 100, 120, 10, 112, 0, 0, 0], [0, 64, 127, 104], 0, 3),
P("FEEDBACK", [5, 90, 70, 24, 60, 70, 40, 60], [0, 64, 127, 90], 0, 5), P("SHOEGAZE", [5, 110, 50, 30, 55, 100, 90, 70], [0, 64, 127, 112], 0, 5),
P("SQUEAL", [5, 80, 96, 16, 70, 110, 12, 30], [0, 64, 127, 80], 0, 4), P("EBOW", [5, 127, 44, 40, 50, 20, 64, 90], [20, 64, 127, 100], 0, 5)] },
/* 9: reserved (PHYS, retired in TONIC: src/engines.c ENG_PHYS_GONE; its sounds load as ANALOG) */
{ name: "-", titles: ["-", "-"], edit: [D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0),
D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0)],
presets: [] },
{ name: "DRUM", titles: ["KIT", "KIT 2"], edit: [D("MORPH", F.PCT, 0, 127, 64), D("TUNE", F.PCT, 0, 127, 64),
D("TONE", F.PCT, 0, 127, 64), D("DECAY", F.PCT, 0, 127, 64), D("NOISE", F.PCT, 0, 127, 64), D("FM ENV", F.PCT, 0, 127, 0),
D("FOLD", F.PCT, 0, 127, 0), D("DRIVE", F.PCT, 0, 127, 0)],
presets: [P("DRUM-X", [64, 64, 70, 64, 64, 0, 0, 0], [0, 100, 127, 100], 0, 12), P("909 CLUB", [60, 64, 76, 64, 64, 0, 0, 10], [0, 100, 127, 100], 0, 12),
P("808 BOOM", [58, 60, 56, 76, 60, 0, 0, 0], [0, 100, 127, 100], 0, 12), P("LOFI DUST", [70, 64, 50, 54, 76, 0, 0, 20], [0, 100, 127, 100], 0, 12),
P("INDUSTRIAL", [72, 66, 88, 70, 74, 20, 0, 40], [0, 100, 127, 100], 0, 12), P("ACOUSTIC", [56, 64, 58, 62, 64, 0, 0, 0], [0, 100, 127, 100], 0, 12),
P("DUB ROOTS", [60, 60, 52, 70, 60, 0, 0, 0], [0, 100, 127, 100], 0, 12), P("TECHNO RAW", [66, 64, 80, 62, 66, 10, 0, 30], [0, 100, 127, 100], 0, 12),
P("BREAKS", [62, 66, 72, 62, 70, 0, 0, 10], [0, 100, 127, 100], 0, 12),
P("HIP HOP", [58, 62, 56, 64, 66, 0, 0, 18], [0, 100, 127, 100], 0, 14)] },
{ name: "NOISE", titles: ["SRC", "MOVE"], edit: [E("MODE", ["ANLG", "DUST", "LFSR", "META"], 0), D("COLOR", F.PCT, 0, 127, 64),
D("FREQ", F.CUTOFF, 0, 127, 80), D("PEAK", F.PCT, 0, 127, 30), D("TRK", F.PCT, 0, 127, 64), D("DENSE", 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], [10, 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),
P("SEA", [0, 40, 50, 60, 40, 0, 90, 0], [100, 90, 120, 110], 0, 5), P("HISS PAD", [0, 90, 95, 110, 127, 0, 20, 0], [80, 90, 115, 100], 0, 5),
P("CRACKLE", [1, 60, 100, 40, 64, 60, 20, 0], [5, 90, 127, 60], 0, 5), P("TAPE AIR", [0, 75, 60, 20, 64, 0, 50, 10], [90, 90, 120, 110], 0, 5)] },
{ name: "FM6", titles: ["OPS", "PATCH"], edit: [D("ALG", F.INT, 0, 32, 0), D("FB", F.INT, -7, 7, 0), D("MOD", F.BIPCT, -64, 63, 0),
D("RATIO", F.INT, -16, 16, 0), D("MEG", F.BIPCT, -64, 63, 0), D("VMOD", F.INT, -7, 7, 0), D("DETUNE", F.PCT, 0, 127, 0),
D("SLOT", F.INT, 0, FM6.FACTORY_PK.length + 32, 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("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("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("MARIMBA", [0, 0, 0, 0, 0, 0, 0, 5], [0, 0, 127, 0], 0, 3),
P("ORGAN", [0, 0, 0, 0, 0, 0, 0, 6], [0, 0, 127, 0], 0, 6), P("PLUCK", [0, 0, 0, 0, 0, 0, 0, 7], [0, 0, 127, 0], 0, 13),
P("FM LEAD", [16, 2, -30, 0, 0, 0, 8, 3], [0, 0, 127, 20], 1, 4), P("SQR LEAD", [0, 0, 10, 1, 20, 0, 6, 7], [0, 30, 110, 25], 1, 4),
P("SLAP BASS", [0, 1, 25, 0, -30, 3, 0, 2], [0, 0, 127, 0], 1, 2), P("SUB BASS", [0, 0, -64, 0, 0, 0, 0, 2], [0, 0, 127, 10], 1, 2),
P("BELL PAD", [0, 0, -10, 0, 0, 0, 40, 1], [55, 0, 105, 75], 0, 5), P("HARD BASS", [0, 2, 25, 0, 0, 0, 0, 2], [0, 0, 127, 0], 1, 2),
P("SAW LEAD", [1, 3, -20, 0, 10, 0, 12, 3], [0, 0, 127, 20], 1, 4)] },
/* 13: ADD (JIANT 0.9.9-snd5, src/eng_add.c; generated from it): additive, nine partials (SLICE's number, retired in JIANT) */
{ name: "ADD", titles: ["SPECTRUM", "MOTION"], edit: [E("MODE", ["HARM", "ODD", "WIDE", "BELL", "BAR", "DRUM", "PRIME", "FIFTH", "SUB", "PLATE"], 0),
D("MORPH", F.PCT, 0, 127, 0), D("BRIGHT", F.PCT, 0, 127, 70), D("PARTIAL", F.PCT, 0, 127, 127), D("SHIFT", F.INT, -64, 63, 0),
D("COMB", F.PCT, 0, 127, 0), D("DECAY", F.PCT, 0, 127, 127), D("MOTION", F.INT, -64, 63, 0)],
presets: [P("ADD ORGAN", [0, 0, 70, 127, 0, 0, 127, 0], [0, 64, 127, 40], 0, 5), P("ADD SAW", [0, 0, 92, 127, 0, 0, 127, 0], [0, 64, 127, 35], 0, 4),
P("HOLLOW", [1, 0, 84, 127, 0, 0, 127, 0], [4, 64, 127, 40], 0, 5), P("PHASER", [0, 0, 96, 127, 0, 40, 127, 0], [10, 64, 127, 45], 0, 5),
P("BELL", [3, 0, 100, 127, 0, 0, 74, 0], [0, 64, 127, 70], 0, 6), P("RADIO", [0, 0, 96, 127, 40, 0, 127, 20], [0, 64, 127, 80], 0, 6),
P("VIBES", [4, 0, 72, 127, 0, 0, 76, 0], [0, 64, 127, 55], 0, 6), P("GLASS", [2, 0, 118, 127, -20, 0, 80, 30], [0, 64, 127, 70], 0, 5),
P("SKIN TOM", [5, 0, 92, 127, 0, 0, 46, 0], [0, 64, 127, 30], 0, 4), P("AIR PAD", [2, 64, 100, 127, -10, 20, 127, 50], [64, 64, 127, 80], 0, 5),
P("SWELL", [0, 40, 104, 127, 0, 0, 127, -50], [20, 64, 127, 60], 0, 5), P("SUB ADD", [1, 0, 20, 40, 0, 0, 127, 0], [0, 64, 127, 25], 1, 2),
P("PRIME ORG", [6, 0, 84, 127, 0, 0, 127, 0], [2, 64, 127, 45], 0, 5), P("QUINT", [7, 0, 80, 127, 0, 24, 127, 20], [6, 64, 127, 50], 0, 5),
P("DRONE", [8, 50, 70, 127, 0, 30, 127, 40], [40, 64, 127, 90], 0, 5), P("GONG", [9, 30, 104, 127, -12, 0, 88, 30], [0, 64, 127, 90], 0, 6)] },
/* 14: ANIMAL (JIANT 0.8.3, src/eng_animal.c; generated from it): animal calls, five sources (MODE); the labels as the
device shows them per MODE (animal_desc) are the device's; here the engine's own */
{ name: "ANIMAL", titles: ["SRC", "CALL"], edit: [E("MODE", ["CMOS", "PULSE", "WHSTL", "WING", "GLOTT"], 0),
D("PRESS", F.PCT, 0, 127, 100), D("CHAOS", F.PCT, 0, 127, 0), D("SIZE", F.INT, 0, 127, 64), D("SWEEP", F.BIPCT, -64, 63, 0),
D("RATE", F.LFOHZ, 0, 127, 80), E("GROUP", ["HOLD", "TRILL", "1+1", "1+3", "2+2", "2+6", "3+3", "3+9", "4+4", "4+12", "6+6", "8+8", "8+24", "12+12", "16+16", "32+32"], 0),
D("TEMP", F.INT, 0, 40, 22, null, "C")],
presets: [P("CMOS BIRD", [0, 90, 0, 37, 16, 74, 0, 20], [0, 64, 127, 40], 0, 7), P("CMOS TRILL", [0, 70, 0, 50, 6, 94, 0, 6], [0, 64, 127, 40], 0, 7),
P("CMOS MONKEY", [0, 110, 20, 80, -40, 70, 5, 28], [0, 64, 127, 50], 0, 3), P("CMOS BUG", [0, 60, 90, 20, 12, 104, 0, 16], [0, 64, 127, 30], 0, 7),
P("CRICKET", [1, 127, 100, 26, 0, 119, 7, 22], [0, 64, 127, 30], 0, 5), P("TREE CRICKT", [1, 127, 110, 32, 4, 102, 1, 22], [0, 64, 127, 40], 0, 5),
P("KATYDID", [1, 10, 20, 24, 50, 80, 7, 22], [0, 64, 127, 30], 0, 5), P("CICADA", [1, 38, 85, 28, 14, 60, 0, 24], [20, 64, 127, 60], 0, 5),
P("TREEFROG", [1, 106, 49, 41, 6, 127, 15, 26], [0, 64, 127, 40], 0, 5), P("TOAD", [1, 127, 80, 44, 8, 116, 1, 22], [4, 64, 127, 50], 0, 5),
P("BULLFROG", [1, 70, 30, 53, 10, 52, 7, 22], [2, 64, 127, 50], 0, 8), P("CANARY", [2, 100, 20, 38, -30, 112, 14, 22], [0, 64, 127, 30], 0, 3),
P("CARDINAL", [2, 110, 6, 46, -40, 77, 10, 22], [0, 64, 127, 30], 0, 3), P("DOVE", [2, 70, 10, 66, 15, 60, 9, 22], [6, 64, 127, 50], 0, 5),
P("OWL", [2, 80, 8, 68, -8, 68, 9, 22], [4, 64, 127, 50], 0, 8), P("PEEPER", [2, 100, 4, 34, 30, 80, 3, 22], [0, 64, 127, 30], 0, 5),
P("BAT", [2, 120, 0, 40, -64, 127, 3, 22], [0, 64, 127, 20], 0, 7), P("MOSQUITO", [3, 30, 50, 64, 20, 40, 2, 22], [10, 64, 127, 40], 0, 5),
P("BEE", [3, 90, 30, 75, 10, 40, 2, 22], [10, 64, 127, 40], 0, 5), P("FLY", [3, 70, 90, 78, 25, 50, 1, 22], [10, 64, 127, 40], 0, 5),
P("WOLF", [4, 0, 8, 64, 40, 50, 0, 5], [20, 64, 127, 60], 1, 5), P("DOG BARK", [4, 100, 70, 64, -15, 85, 5, 6], [0, 64, 127, 30], 0, 3),
P("ROAR", [4, 110, 100, 100, -20, 50, 3, 9], [6, 64, 127, 50], 1, 8), P("PURR", [4, 10, 60, 50, 0, 60, 1, 19], [10, 64, 127, 40], 1, 8)] },
];
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 */
[[36, 0, 42, 0, 38, 0, 42, 36, 0, 36, 42, 0, 38, 0, 42, 46], [1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0]], /* 14 BOOM BAP (V10.34) */
];
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("LEVEL", F.PCT, 0, 127, 127));
TP.push(D("ROTATE", F.INT, -32, 32, 0), D("PITCH", F.SEMI, -24, 24, 0)); /* 81, 82: STRETCH's ROTATE, TRACK's PITCH (JIANT; SHIFT until 0.6.91; the chord keys before) */
for (const l of ["KICK", "SNARE", "CLAP", "HATCL", "HATOP", "TOM", "RIM", "BELL"]) TP.push(D(l, F.PCT, 0, 127, 127)); /* 83..90: DRUM lane levels */
TP.push(E("TYPE", ["SOFT", "HARD", "FOLD", "CRUSH", "RECT", "AMP"], 0), D("TONE", F.BIPCT, -64, 63, 0), /* 91, 92: DIST (JIANT, FUNB) */
D("LEN", F.STEPS, 1, 16, 16), E("DIV", NDIV, 2), D("SLEW", F.PCT, 0, 127, 0)); /* 93..95: the modulation sequence */
for (let k = 0; k < 16; k++) TP.push(D("LEVEL", F.PCT, 0, 127, 0)); /* 96..111: its levels */
TP.push(E("TYPE", ["LP", "HP", "BP", "COMB", "COMB-", "MS20", "LP24"], 0), /* 112: the FILTER's type (JIANT 0.5) */
D("CUT", F.CUTOFF, 0, 127, 127), D("RES", F.PCT, 0, 127, 0)); /* 113, 114: the other engines' */
const P_COUNT = 123, G_COUNT = 72, NSTEP = 64, P_E0 = 115, 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 */
/* tracks (firmware v3): four synth parts (1.0), six (JIANT 0.6); 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,
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,
vbank: { valid: false, name: "", voices: new Array(32).fill(null) }, vtx: null, /* (0.6.11) FM6's voice bank */
palettes: ["GREY", "GREEN", "AMBER", "ICE", "VIOLET", "ROSE", "PAPER", "HI-CON", "NIGHT", "MONO"],
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 = () => ENG[st.engine].name === "DRUM";
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];
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 < 8; i++) st.p[P_E0 + i] = pr.e[i];
[1, 2, 3, 4].forEach((id, k) => { st.p[id] = pr.env[k]; });
if (e.name === "VOICE") { st.p[61] = (pr.xp || 0) & 3; st.p[74] = (pr.xp || 0) >> 2; } /* (0.8.5) LANG, LYRIC (P_VLANG
= P_FM1_ATK 61, P_VLYR = P_FM3_REL 74; ui.c apply_preset_to) */
st.p[37] = pr.mono ? 2 : 0;
st.p[33] = 0; st.p[34] = 24; st.p[35] = 28; st.p[36] = 36;
for (let i = P_SLCR + 4; i < P_E0; i++) if (!trackOwn(i, P_E0)) st.p[i] = TP[i].def; /* a factory preset turns the
matrix off; the SLICER, the chord keys, the steps and the other track
settings stay (ui.c apply_preset_to) */
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;
const bk = s > FM6_OWN && s <= FM6_OWN + 32 ? s - FM6_OWN - 1 : -1; /* (0.6.11) B1..B32: the voice bank's */
if (bk >= 0 && !st.vbank.voices[bk]) { t.p[P_E0 + 7] = t.slot ?? FM6_OWN; return; } /* (none there: refused) */
if (s >= FM6_OWN && bk < 0) { 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 = (bk >= 0 ? st.vbank.voices[bk] : 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) */
if ([4, 9].includes(ei % ENG.length)) ei = 0; /* PHYS SAMPLE (retired, core.h eng_gone): ANALOG; (snd5) 8 STRING 13 ADD */
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 lanesOn = () => ratchetOn() && !opt.noLanes; /* (0.8.5, INFO 4F 01 07, after the voice bank) */
const stepOut = (x, b, lanes) => { 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 (lanes && lanesOn()) for (let l = 0; l < 8; l++) b(x.lanes ? x.lanes[l] : 0); }; /* (0.8.5: asked for, editor.c) */
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()) x.ratchet = Math.max(1, Math.min(4, a[12]));
if (a.length >= 21 && lanesOn()) x.lanes = a.slice(13, 21).map((m) => (m > 6 ? 0 : m));
}
/* 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, 0.9.9): DRUM-X, SINGER EN, CMOS BIRD, BYTEBEAT, FAT BASS, TINE EP */
[[1, 5, 9], [2, 14, 0], [3, 3, 0], [4, 0, 14], [5, FM6_E, 0], [0, 10, 0]].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 (DRUM-X)
with BEAT, track 5 (the bass) with OFFBEAT (as SEQ > PATTERNS would load them), the voice left, the bird right */
st.sel = 4; loadPattern(1);
st.sel = 0; loadPattern(11);
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();
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));
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.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] === 3 || a[1] === 4) {
const at = m.events.findIndex(e => e.step === a[2] && e.param === a[3]);
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:a[2],param:a[3],value:v14dec(a[4],a[5])}; if (at >= 0) m.events[at] = e; else m.events.push(e); }
}
[a[0],rc,+m.on,m.events.length,64].forEach(b);
m.events.forEach(e => {b(e.step);b(e.param);v(e.value);});
break;
}
case CMD.INFO:
s(opt.legacy ? "FELUCCA 0.4 BETA (MOCK)" : "FELUCCA v1.0 (MOCK)"); b(ENG.length); b(P_COUNT); b(G_COUNT); b(NSTEP); b(P_E0);
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 (ratchetOn()) { b(0x52); b(1); b(4); }
if (!opt.noFm6 && !opt.noVbank && ratchetOn()) { b(0x56); b(1); b(32); }
if (lanesOn()) { b(0x4F); b(1); b(7); } } } /* (FM6 v2: no bank, preset patches; 0.6.11: the voice bank; 0.8.5: the lanes' modes) */
if (st.uiCaps && !opt.noLyric) { b(0x59); b(1); b(63); } /* (0.8.5) LYRIC, the last tag */
}
break;
case CMD.LYRIC: { /* (0.8.5) editor.c ED_LYRIC */
if (opt.noLyric || !a.length || a[0] >= NTRK) return null;
const tr = st.tracks[a[0]];
let rc = 0;
if (a.length > 1) {
let txt = "";
for (let i = 1; i < a.length && a[i]; i++) txt += String.fromCharCode(a[i] >= 32 && a[i] <= 126 ? a[i] : 32);
if (txt.length > 63) { txt = txt.slice(0, 63); rc = 1; }
tr.lyric = txt;
}
b(a[0]); b(rc); s(tr.lyric || "");
break;
}
case CMD.GET: case CMD.SET: {
if (a.length < 2) return null;
const d = desc(a[0], a[1]);
if (!d) return null;
const arr = a[0] ? st.g : st.p;
if (cmd === CMD.SET && a.length >= 4) {
if (a[0] === 1 && a[1] === G_ENGSEL) setEngine(clamp(v14dec(a[2], a[3]), 0, ENG.length - 1));
else if (d.max > d.min) arr[a[1]] = enumOrig(d, clamp(v14dec(a[2], a[3]), d.min, d.max));
if (!a[0] && a[1] === P_E0 + 7 && st.engine === FM6_E) fm6Slot(st.tracks[st.sel], arr[a[1]]); /* PTCH (fm6_poll) */
}
b(a[0]); b(a[1]); v(arr[a[1]]);
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: {
if (a.length < 2 || a[0] >= NTRK || a[1] >= P_COUNT) return null;
const t = st.tracks[a[0]], d = a[1] >= P_E0 ? ENG[t.engine].edit[a[1] - P_E0] : TP[a[1]];
if (a.length >= 4 && d.max > d.min) t.p[a[1]] = enumOrig(d, clamp(v14dec(a[2], a[3]), d.min, d.max));
b(a[0]); b(a[1]); v(t.p[a[1]]);
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, a.length === 23 || (a.length === 3 && a[2] === 1));
break;
}
case CMD.DESC: {
if (a.length < 2) return null;
const d = desc(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 < 32; 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, a.length === 22 || (cmd === CMD.STEP_GET && a.length === 2 && a[1] === 1));
break;
}
case CMD.FM6B_BEGIN: case CMD.FM6B_WRITE: case CMD.FM6B_END: case CMD.FM6B_LIST: { /* (0.6.11) fm6_vbank.c */
if (opt.noFm6 || !st.uiCaps) return null;
const vb = st.vbank;
if (cmd === CMD.FM6B_BEGIN) {
if (a.length) { b(1); break; }
st.vtx = { voices: new Array(32).fill(null) }; b(0);
} else if (cmd === CMD.FM6B_WRITE) {
b(a.length ? a[0] : 127);
if (!st.vtx) b(5);
else if (a.length !== 1 + 128 || a[0] > 31 || st.vtx.voices[a[0]]) b(1);
else { st.vtx.voices[a[0]] = Array.from(a.slice(1)); b(0); }
} else if (cmd === CMD.FM6B_END) {
let rc = a.length !== 15 || a[14] > 15 ? 1 : !st.vtx ? 5 : 0;
if (!rc) {
const crc = (a[10] | a[11] << 7 | a[12] << 14 | a[13] << 21 | a[14] << 28) >>> 0;
const tx = st.vtx; st.vtx = null;
if (crc32(tx.voices.filter(Boolean).flat()) !== crc) rc = 2;
else {
st.vbank = { valid: true, name: String.fromCharCode(...a.slice(0, 10)).replace(/[\s\0]+$/, ""), voices: tx.voices };
for (const t of st.tracks) /* a track on a bank slot keeps its voice, as its own */
if (t.slot > FM6_OWN) { t.own = null; t.p[P_E0 + 7] = t.slot = FM6_OWN; }
}
}
b(rc); b(st.vbank.voices.filter(Boolean).length);
} else {
if (a.length) return null;
b(32); b(vb.valid ? 1 : 0); s(vb.name);
vb.voices.forEach((pk) => { b(pk ? 1 : 0); s(pk ? FM6.name(FM6.unpack(pk)) : ""); });
}
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] === 4 && a[1] === PERC_SET) setEngine(DRUM_E); /* SAMPLE preset 4, once PERC: DRUM's kit */
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 > 64)) 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;
});
}
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;
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: "JIANT", type: "input", state: "connected", onmidimessage: null };
let busy = false;
const output = {
id: "mock-out", name: "JIANT", 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();
}, flash ? 150 : 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, [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, [0, id, ...v14enc(t.p[id])]);
else if (st.v4) push(CMD.TRACK_CHANGED, [i, id, ...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 (EDITOR_PROTOCOL.md). "-" (a reserved engine number: DIGITAL 1, PHYS 9) is no alias. -> the original's index */
function aliasOf(names, i) {
if (!names || names[i] == null || names[i] === "-") 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 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];
if (d.names && d.names[5] === "BYTE" && d.names[0] === "PLS") return [vals[5], ...(vals.length > 6 ? [vals[6]] : []), ...vals.slice(0, 5)]; /* (JIANT 0.4: LOFI's WAVE, BYTE first; 0.5.1: FLOAT next) */
if (len.includes(null) && d.names && len.some((x) => x !== null) && d.names.every((n, i) => len[i] !== null || /^[\d.]+m?s$/.test(n)))
return [...vals.filter((v) => len[v - d.min] !== null).sort((a, b) => len[b - d.min] - len[a - d.min] || a - b),
...vals.filter((v) => len[v - d.min] === null)]; /* (JIANT 0.4, the delay's TIME: the divisions, then free times) */
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 = ["DRUM", "VOICE", "ANIMAL", "LOFI", "ANALOG", "FM6", "PHASE", "WHEEL", "NOISE", "STRING", "SAMPLE", "DIGITAL"]; /* (0.9.9: DRUM-X, VOICE,
ANIMAL first, as the parts at power-on; DIGITAL, FELUCCA_FM4 builds only, last; was ANALOG FM6 DIGITAL PHASE LOFI VOICE WHEEL NOISE
DRUM ANIMAL, the order PROGRAM CHANGE still numbers the sounds in: engines.c ENGINE_PC_ORDER) */
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_lpf_peak: 0xEAA0, ui_slider_vertical: 0xEA73, symbol_books: 0xEADC, control_rec_f: 0xEA09, control_stop_f: 0xEA0F,
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", SCL: "symbol_tuning", ARP: "control_arrow_up_down", "SEQ PATTERN": "symbol_grid",
GLOBAL: "symbol_cog", INSTRUMENT: "symbol_keyboard" };
const PAGE_IC = { FLT: "function_filter_lpf_peak", FILT: "function_filter_lpf_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 が中央)。● はキャリア。",
midiPorts: "MIDI ポート(自動接続できない場合)", midiPortHelp: "ブラウザが認識したポートです。入力と出力が両方必要です。空の場合は MIDI ポートが認識されていません。", midiInput: "入力", midiOutput: "出力",
fm6BankSend: "本体のボイスバンクへ送る (B1–B32)", fm6BankSent: "ボイスバンクを送りました:", fm6BankFail: "ボイスバンクを送れませんでした (rc ", fm6BankNow: "本体のボイスバンク:", fm6BankNone: "なし",
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)がありません。Felucca 1.0 以降に更新すると使えます。",
motion: "オートメーション", motionOn: "再生", motionClear: "オートメーションを消去", motionConfirm: "選択トラックのオートメーションを消しますか?", chance: "確率 %", ratchet: "ラチェット", motionStep: "ステップ", motionParam: "パラメーター", motionValue: "値",
backupTitle: "全体バックアップ", backupExport: "バックアップ保存", backupImport: "バックアップ復元", backupHelp: "現在の曲・A〜D・音色バンク・設定を、このパソコンへ保存。", backupOld: "全体バックアップには対応版への更新が必要です。", backupConfirm: "全体バックアップを復元しますか? 現在の曲と保存データを置き換えます。USBを抜かないでください。", backupWorking: "バックアップ処理中 ", backupDone: "バックアップを保存しました", backupRestored: "全体バックアップを復元しました",
deviceDisplay: "本体の画面",
deviceDisplayHelp: "FM-1 の画面に反映し、保存します。再生中の変更は停止後に保存されます。",
devicePresets: "本体のプリセット",
deviceFavHelp: "お気に入りと表示フィルターは FM-1 と同期します。パソコンのライブラリの音色は、本体のユーザースロットに保存してから登録してください。",
deviceList: "表示",
deviceAll: "すべてのプリセット",
deviceFavorites: "お気に入りのみ",
deviceEmpty: "お気に入りはまだありません。「すべてのプリセット」から追加してください。",
deviceTheme: "テーマ",
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: "JIANT が見つかりません。USB で接続して、もう一度押してください。", portsSeen: "見えている MIDI ポート:", portsNone: "MIDI ポートがありません。データ用ケーブルか、MENU > USB が CONSOLE か確認してください",
connecting: "接続中", reading: "読み込み中 ", steploading: "ステップを読み込み中 ",
ready: "接続しました", disconnected: "切断されました", lost: "JIANT が外されました", instbusy: "別のタブでインストーラーが書き込み中です。終わってから接続してください。",
noreply: "応答がありません", error: "エラー: ", busy: "処理中",
applying: "書き込み中 ", applied: "読み込みました", badfile: "ファイルを読み込めません: ",
savedSlot: "保存しました: スロット ", loadedSlot: "読み込みました: スロット ", emptySlot: "空のスロットです: ",
confirmSave: "スロット {n} に上書き保存しますか?", confirmLoad: "スロット {n} を読み込みますか? すべてのトラックの音色とシーケンスが置き換わります(元に戻せません)。",
confirmClear: "シーケンスを全部消しますか?", confirmInit: "音色を初期化しますか? シーケンスはそのままです(本体の SAVE 長押しで元に戻せます)。",
erase: "消去", remove: "外す",
layout: "(ファームウェアのパラメーター数が想定と違うため、簡易表示にしています)",
ctlHelp: "スライダーはクリックしてからホイールか矢印キーで微調整(Shift で 10 ずつ)、ダブルクリックで初期値。",
lyricT: "歌詞(VOICE WORDS)",
lyricHelp: "VOICE トラックの歌詞(63 文字まで)。EDIT > WORDS の LANG で言語(ES / EN / JA、日本語はローマ字)、LYRIC を TEXT に。音符ごとに次の音節を歌い、「-」は母音をもう一音のばす。",
lyricSend: "送信",
lyricLang: "LANG",
lyricSrc: "LYRIC",
lyricSent: "歌詞を送りました",
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: "音色を読み込みました(シーケンスはそのまま。パターンは本体の SEQ > PHRASES から。SAVE 長押しで元に戻せます): ", reloaded: "本体で音色が変わったので読み直しました", readingBank: "スロットを読み込み中",
badEngine: "このファームウェアにないエンジンです: ", flashFail: "書き込みに失敗しました(rc {rc})",
installer: "JIANT インストーラー",
tabSeq: "シーケンサー", tabTracks: "トラック", tabSettings: "設定",
needDevice: "FM-1 を接続すると編集できます。",
bankConnect: "FM-1 を接続すると本体のユーザープリセットも扱えます。", bankNone: "このファームウェアにはユーザープリセットがありません。",
mixer: "ミキサー", mixHelp: "本体の MIXER ページと同じトラック。フェーダーはレベル。パンはどのトラックも選択を変えずに書き込みます(0.8 のファームウェアでは一瞬そのトラックを選びます)。REC は本体での録音待機の表示です。",
level: "レベル", pan: "パン", mute: "ミュート", rec: "REC", selectTrack: "選択", selectedTrack: "選択中",
projHelp: "プロジェクトは本体の状態をまとめて保存します: 全トラックの音色とパターン、曲の並び順、選択中のトラック、グローバル設定。",
slot: "スロット", songTitle: "ソング", songHelp: "保存スロットのパターンと繰り返す回数を順に並べます。音色は現在のまま。並び順を残すには、上のプロジェクトを保存してください。切替はトラック1のパターン終端、曲末で停止します。", songAdd: "行を追加", songRemove: "最後の行を削除", songPlay: "先頭から再生", songStop: "停止", songReps: "回", songEmpty: "行を追加してください", songBusy: "停止してから編集してください", songInvalid: "スロットと回数を確認してください", songPlaying: "再生中の行", songSaved: "並び順を変更しました。プロジェクトを保存すると残せます。",
system: "システム", firmware: "ファームウェア", sync: "同期", tracksN: "トラック", stepsN: "ステップ数", enginesL: "エンジン",
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.",
midiPorts: "MIDI ports (choose manually if Auto fails)", midiPortHelp: "These are the ports reported by the browser. Both an input and an output are required; empty lists mean the browser is not seeing a MIDI port.", midiInput: "Input", midiOutput: "Output",
fm6BankSend: "Send to the device's voice bank (B1–B32)", fm6BankSent: "Voice bank sent:", fm6BankFail: "The voice bank was not sent (rc ", fm6BankNow: "The device's voice bank:", fm6BankNone: "none",
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 to Felucca 1.0 or later to use it.",
motion: "Automation", motionOn: "Play automation", motionClear: "Clear automation", motionConfirm: "Clear this track's automation?", chance: "Chance %", ratchet: "Ratchet", motionStep: "Step", motionParam: "Parameter", motionValue: "Value",
backupTitle: "Complete backup", backupExport: "Save backup", backupImport: "Restore backup", backupHelp: "Save the current music, A–D, sound banks and settings to this computer.", backupOld: "Complete backups need firmware with archive support.", backupConfirm: "Restore this complete backup? Current music and saved data 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.",
deviceTheme: "Theme",
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: "JIANT not found. Connect it by USB and press Connect again.", portsSeen: "MIDI ports seen:", portsNone: "no MIDI port at all: check the cable carries data and MENU > USB is CONSOLE",
connecting: "Connecting", reading: "Reading ", steploading: "Reading steps ",
ready: "Connected", disconnected: "Disconnected", lost: "JIANT was unplugged", instbusy: "The installer is writing in another tab: connect when it has finished.",
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: ",
confirmSave: "Overwrite slot {n}?", confirmLoad: "Load slot {n}? The sounds and sequences of all tracks are replaced (no undo).",
confirmClear: "Clear the whole sequence?", confirmInit: "Reset the sound to the engine defaults? The sequence stays (hold SAVE on the device to undo).",
erase: "Erase", remove: "Remove",
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.",
lyricT: "Lyric (VOICE WORDS)",
lyricHelp: "VOICE lyrics: up to 63 characters after transliteration. ES, EN, JA (romaji), RU, DE, FR, ZH (pinyin), PT, GN. New languages use approximate phonetic singing rules; Mandarin notes follow your melody. TEXT advances each note; TEXT FIXED repeats POS. A \"-\" holds the vowel one more note.",
lyricSend: "Send",
lyricLang: "LANG",
lyricSrc: "LYRIC",
lyricSent: "Lyric sent",
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; its pattern is on the device under SEQ > PHRASES; 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: "JIANT installer",
tabSeq: "Sequencer", tabTracks: "Tracks", tabSettings: "Settings",
needDevice: "Connect the FM-1 to edit.",
bankConnect: "Connect the FM-1 to see its user presets too.", bankNone: "This firmware has no user presets.",
mixer: "Mixer", mixHelp: "The tracks 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", mute: "Mute", rec: "REC", selectTrack: "Select", selectedTrack: "Selected",
projHelp: "A project keeps the sounds and patterns of all tracks, the song chain, the selected track and the global settings.",
slot: "Slot", songTitle: "Song", songHelp: "Arrange sections (the saved projects A–D, with their sounds) and choose how many bars each plays (1–64). Save a project above to keep the chain. Rows change on the bar; the song stops at the end and the music before it comes back.", songAdd: "Add row", songRemove: "Remove last row", songPlay: "Play from start", songStop: "Stop", songReps: "bars", songEmpty: "Add a row first", songBusy: "Stop before editing", songInvalid: "Check sections and bars", songPlaying: "Playing row", songSaved: "Chain changed. Save a project to keep it.",
system: "System", firmware: "Firmware", sync: "Sync", tracksN: "Tracks", stepsN: "Steps", enginesL: "Engines",
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(); renderTrackbar(); renderMixer(); renderSysinfo(); renderFm6(); }
}
$("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", "tracks", "library", "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);
renderPanels();
if (name === "tracks" && prev !== "tracks" && hasTracks() && dev.dump) op(readMixer);
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"; }
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); }
}
$("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) => [EXPECT.gcount, 32, 36, 37, 66, 67, 69, 71].includes(info.gcount) && /* (JIANT FUNB: 5, 9, then 10 more globals; 0.6.3: the SLICER's 29) */
[[120, 112], [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, [5, 6, 7, 8]]] },
{ t: "LFO", pages: [["LFO", 0, [9, 10, 11, 12]], ["LFO DEST", 0, [13, 14, 15, 16]],
...(pe0 >= 112 ? [["MSEQ", 0, [93, 95, 94]], ...[0, 1, 2, 3].map((k) => [`STEPS ${4 * k + 1}-${4 * k + 4}`, 0,
[96 + 4 * k, 97 + 4 * k, 98 + 4 * k, 99 + 4 * k]])] : [])] }, /* (JIANT) the modulation sequence: LEN DIV SLEW, its 16 levels */
...(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 && engName() === "DRUM" ? [["LANES", 0, P_LANES.slice(0, 4)], ["LANES 2", 0, P_LANES.slice(4)]] : [])] }, /* lane levels 83..90 */
...(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]]] }, /* (JIANT 0.4: no VOICE 2: PAN on MIXER, MUTE there and GLO) */
{ t: "FX", pages: [["FX", 0, [33, 34, 35, 36]], ["MASTER", 1, [21, 25, 26, 13]], ...(dev && dev.gdesc && dev.gdesc[17] && dev.gdesc[17].label === "DJ FILT" ? [["DJ FILTER", 1, [17]]] : []), /* (0.9.1, as the device names it) */ ...(pe0 >= 112 ? [["DIST", 0, [33, 91, 92]]] : []), ...(dev && dev.info && dev.info.gcount >= 66 ? [["AUTO PAN", 0, [45, 46, 48, 47]], ["SLICER", 1, [37, 38, 39, 40]], ["SL BUS", 1, [41, 42, 43, 44]],
["SL BUS 2", 1, [45, 46, 47]], ["SL PITCH", 1, [48, 49]], ...[0, 1, 2, 3].map((k) => [`PITCH ${4 * k + 1}-${4 * k + 4}`, 1,
[50 + 4 * k, 51 + 4 * k, 52 + 4 * k, 53 + 4 * k]])] : [["SLICER", 0, [45, 46, 47, 48]]]), /* (0.6.3: one, on a bus) */
["DLY", 1, [4, 5, 6, 7]], ...(pe0 >= 112 ? [["DLY 2", 1, [28, 34, 35, ...(dev && dev.info && dev.info.gcount >= 67 ? [66] : [])]],
...(dev && dev.info && dev.info.gcount >= 69 ? [["DLY 3", 1, [67, 68]]] : [])] : []), ["REVERB", 1, pe0 >= 112 ? [24, 8, 9, 31] : [24, 8, 9]],
...(pe0 >= 112 ? [["REVERB 2", 1, [29, 30, 32, 33]]] : []), ["CHORUS", 1, pe0 >= 112 ? [10, 11, 27] : [10, 11]]] }, /* G_RTYPE 24: ROOM SPRING SHIMR RESO CLOUD; MASTER: CLIP PNCH DUCK REL; (0.6.9) AUTOPAN: DPTH RATE SYNC WAVE, CHORUS: STER (27) */
{ t: "SCL", pages: [["SCL", 0, [25, 26, 27, 28]], ["SCL 2", 1, [36]]] }, /* (JIANT 0.4) G_STRN 36: every sequence along the scale */
{ 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 >= 83 ? [["STRETCH · TRACK", 0, P_SHIFT]] : [])] }, /* ROTATE PITCH 81, 82 (SHIFT until 0.6.91) */
{ 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 === "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);
/* -------------------------------------------------------------- MIDI --- */
let connecting = false, portsClosing = Promise.resolve();
const portStates = new Map();
function renderMidiPorts() {
if (!access) return;
$("midiportcounts").textContent = `${t("midiInput")}: ${[...access.inputs.values()].filter(p=>p.state!=="disconnected").length} · ${t("midiOutput")}: ${[...access.outputs.values()].filter(p=>p.state!=="disconnected").length}`;
for (const [id, ports] of [["midiinput",access.inputs],["midioutput",access.outputs]]) {
const box=$(id), value=box.value;
box.replaceChildren(el("option",{value:"",text:"Auto (JIANT / FM1)"}), ...[...ports.values()].filter(p=>p.state!=="disconnected").map(p=>el("option",{value:p.id,text:p.name || p.id})));
if ([...box.options].some(o=>o.value===value)) box.value=value;
}
}
/* (0.9.11) the web installer in another tab of this browser (web/index_pkg.html): while it writes, the editor lets the
* FM-1 go and does not reconnect by itself (the update loader's port is a "JIANT" one too); it says it is here */
let installerUntil = 0;
try {
const bc = new BroadcastChannel("jiant-midi");
bc.onmessage = (e) => {
const m = e.data || {};
if (m.type === "who") bc.postMessage({ type: "editor", connected: !!dev });
if (m.type === "installer") {
installerUntil = m.busy ? Date.now() + 60000 : 0;
if (m.busy) { wantConnected = false; if (dev) disconnect("instbusy"); }
}
};
} catch (_) {}
async function connect() {
if (connecting || dev) return;
if (Date.now() < installerUntil) { sayK("instbusy"); 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;
}
await portsClosing;
renderMidiPorts();
for (const p of [...access.inputs.values(), ...access.outputs.values()]) portStates.set(p.id, p.state);
const opened = await openEditorMidi(access, {
onUnknown: f => console.debug("ignored reply", f), onTimeout: () => sayK("noreply"),
onPush: f => onPush(f), onGap: () => { rewatch = true; },
}, {input: $("midiinput").value, output: $("midioutput").value});
dev = { ...opened, 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) {
const timeout = /^timeout/.test(e.message);
if (connectedDevice) disconnect();
if (e.message === "no MIDI ports") $("midiports").open = true;
const notFound = e.message === "no MIDI ports" || /^Not a JIANT/.test(e.message) || timeout;
sayK(notFound ? "nodevice" : "error", notFound ? (seenPorts ? ` (${t("portsSeen")} ${seenPorts})` : ` (${t("portsNone")})`) : e.message);
}
} finally {
connecting = false;
$("connect").disabled = false;
}
}
function disconnect(reasonKey = "disconnected") {
if (dev) {
dev.link.close();
dev.input.onmidimessage = null;
portsClosing = Promise.allSettled([dev.input.close?.(), dev.output.close?.()]);
}
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) return;
const chosen = p.id === $("midiinput").value || p.id === $("midioutput").value || dev && (p.id===dev.input.id || p.id===dev.output.id);
if (!chosen && !editorPort({name:p.name,state:"connected"})) return;
if (portStates.get(p.id) === p.state) return; /* open/close is not a physical reconnect */
portStates.set(p.id, p.state);
renderMidiPorts();
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, !!(d && d.info && d.info.laneModes)))); }
/* 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 = d.info || parse[CMD.INFO](await sessionRequest(d, req.info(), { timeout: 800, 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; }
}
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);
if (d.info.chainRows) d.song = parse[CMD.SONG](await sessionRequest(d, req.song()));
buildUI();
renderPanels();
await loadSteps(d);
if (d.info.ntrk) await readMixer(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) */
function matrixContextId(d, id) {
const e = d.info.engines[d.dump.engine], off = id - d.info.pe0;
return off === 0 || (e === "LOFI" && off === 1) || (e === "INPUT" && off === 3) || /^(?:DEST|DST)\d$/.test(d.pdesc[id]?.label || "") || d.pdesc[id]?.label === "LANG";
}
async function rereadEngineDesc(d = dev) {
assertSession(d);
const pe0 = d.info.pe0;
const before = JSON.stringify(d.pdesc);
for (let i = 0; i < 8 && pe0 + i < d.info.pcount; i++) d.pdesc[pe0 + i] = await getDescOrNull(0, pe0 + i, d);
for (let i = 0; i < pe0; i++) if (/^(?:DEST|DST)\d$/.test(d.pdesc[i]?.label || "")) d.pdesc[i] = await getDescOrNull(0, i, d);
if (d.built !== d.dump.engine || JSON.stringify(d.pdesc) !== before) buildGroups();
}
async function loadSteps(d = dev) {
assertSession(d);
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();
renderSysinfo();
fm6List = null;
fm6Asked = false;
fm6Picked = -1;
renderFm6();
}
/* the track selector (v3): the four parts; 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");
}
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)],
["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 }))));
}
/* (0.8.5) the VOICE track's lyric (LYRIC, cmd 39): shown for a VOICE track on a firmware that has it */
function lyricShown() { return !!dev && !!dev.info && !!dev.info.lyric && !!dev.dump && dev.info.engines[dev.dump.engine] === "VOICE"; }
async function lyricRead(d = dev) {
if (!lyricShown()) return;
const r = parse[CMD.LYRIC](await rq(req.lyric(d.sel || 0)));
if (document.activeElement !== $("lyric")) $("lyric").value = r.text;
lyricPreview();
}
$("lyricsend").addEventListener("click", () => {
if (!lyricShown()) return;
op(async () => {
const text = lyricText($("lyric").value, LYR_LANG[+$("lyrlang").value]);
const r = parse[CMD.LYRIC](await rq(req.lyric(dev.sel || 0, text)));
$("lyric").value = r.text;
sayK("lyricSent");
});
});
/* LANG (P_VLANG, id 61) and LYRIC (P_VLYR, id 74): VOICE's words, in other engines' slots (sing.c) */
const LYR_LANG = ["OFF", "ES", "EN", "JA", "RU", "DE", "FR", "ZH", "PT", "GN"];
const LYR_SRC = ["TEXT", ...Array.from({ length: 16 }, (_, i) => `W${i + 1}`), ...Array.from({ length: 8 }, (_, i) => `S${i + 1}`), "TEXT FIXED"];
function lyricPreview() {
try { const text=lyricText($("lyric").value,LYR_LANG[+$("lyrlang").value]); $("lyric-preview").textContent=`${text.length}/63 · ${text}`; }
catch(e) { $("lyric-preview").textContent=e.message; }
}
$("lyric").addEventListener("input",lyricPreview);
const LYR_ID = { lang: 61, src: 74 };
for (const [id, names, key] of [["lyrlang", LYR_LANG, "lang"], ["lyrsrc", LYR_SRC, "src"]]) {
$(id).replaceChildren(...names.map((n, i) => el("option", { value: i, text: n })));
$(id).addEventListener("change", () => {
lyricPreview();
if (!lyricShown()) return;
op(async () => { parse[CMD.SET](await rq(req.set(0, LYR_ID[key], +$(id).value))); dev.dump = await getDump(); refreshAll(); });
});
}
function updateBrowser() {
const e = dev.dump.engine;
const sel = $("engine");
$("lyricbox").hidden = !lyricShown();
if (lyricShown()) {
for (const [id,param] of [["lyrlang",LYR_ID.lang],["lyrsrc",LYR_ID.src]]) {
const max=dev.pdesc[param]?.max;
if (Number.isInteger(max)) for (const option of $(id).options) option.disabled=+option.value>max;
}
if (document.activeElement !== $("lyrlang")) $("lyrlang").value = String(Math.max(0, Math.min(9, dev.dump.p[LYR_ID.lang] | 0)));
if (document.activeElement !== $("lyrsrc")) $("lyrsrc").value = String(Math.max(0, Math.min(25, dev.dump.p[LYR_ID.src] | 0)));
}
renderTrackbar();
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 && /^(?:DEST|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);
}
for (const [id, divs] of Object.entries(groups)) $(id).replaceChildren(...divs);
}
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;
if (!s && d.label === "PHASE" && d.min === -1 && d.fmt === F.INT) return lfoModeRows(id, d);
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, disabled: /(?:^|:)N\/A$/.test(name) }, 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;
}
/* (0.9.18) the LFO's PHASE as the device's pages show it: MODE TRIG / FREE (FREE is PHASE -1, as stored since 0.6.51) and
PHASE 0..127, TRIG's start (dimmed in FREE: the phase TRIG had is kept here for TRIG again) */
function lfoModeRows(id, d) {
const k = key(0, id);
const mode = el("select", {}, el("option", { value: 0 }, "TRIG"), el("option", { value: 1 }, "FREE"));
const ph = el("input", { type: "range", min: 0, max: d.max, step: 1 });
const mout = el("span", { class: "v" }), out = el("span", { class: "v" });
const c = { input: ph, out, desc: d, scope: 0, id, mem: 0 };
c.show = (v, force) => {
if (v >= 0) c.mem = v;
mode.value = v < 0 ? "1" : "0";
mout.textContent = v < 0 ? "FREE" : "TRIG";
ph.disabled = v < 0;
out.textContent = String(c.mem);
if (force || !touched(k)) ph.value = String(c.mem);
};
mode.addEventListener("change", () => userSet(0, id, +mode.value ? -1 : c.mem, true));
ph.addEventListener("pointerdown", () => { dragging = k; });
ph.addEventListener("input", () => userSet(0, id, +ph.value, false));
ph.addEventListener("change", () => userSet(0, id, +ph.value, true));
mode.title = "MODE";
ph.title = "PHASE";
const rows = [el("div", { class: "row" }, el("span", { text: "MODE" }), mode, mout),
el("div", { class: "row" }, el("span", { text: "PHASE" }), ph, out)];
c.row = rows[1];
ctl.set(k, c);
c.show(dev.dump.p[id], true);
const f = document.createDocumentFragment();
f.append(...rows);
return f;
}
function showValue(k, v, force) {
const c = ctl.get(k);
if (!c || v == null) return;
if (c.show) return c.show(v, force);
const [txt0, unit] = fmtValue(c.desc, v), txt = modDst(c.desc, txt0);
c.out.textContent = unit ? `${txt} ${unit}` : txt;
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();
}
if (!s && dev && matrixContextId(dev, id)) { dev.dump = await getDump(); await rereadEngineDesc(); refreshAll(); } /* (V10.40) WAVE / EXCITE / MODE:
* some knobs change name and range (ANALOG SAW3's INT 3, STRING FDBK) */
} 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);
updateBrowser();
refreshAll();
await loadSteps(d); /* (a sound load keeps them; read anyway after a RELOAD) */
if (hasTracks()) await readMixer(d); /* the sound names and the selected strip */
await lyricRead(d); /* (0.8.5) a VOICE track's lyric */
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 */
function renderSlots() {
renderSong();
renderBackup();
const box = $("slots");
box.replaceChildren();
for (let i = 0; i < 4; i++) {
const u = dev.slotUsed[i];
box.append(el("span", { text: String.fromCharCode(65 + i) }),
el("span", { class: "dim", text: 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")));
}
}
async function project(op, slot) {
if (!dev) return;
if (!confirm(t(op ? "confirmSave" : "confirmLoad").replace("{n}", slot + 1))) return;
const releaseBusy = beginBusy();
try {
/* 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();
if (dev.info.chainRows) { dev.song = parse[CMD.SONG](await rq(req.song())); renderSong(); }
sayK(op ? "savedSlot" : r.used ? "loadedSlot" : "emptySlot", String(slot + 1));
} catch (err) { report(err); } finally { releaseBusy(); }
}
function renderSong() {
const box = $("songchain");
box.hidden = !dev || !dev.info?.chainRows || !dev.song;
if (box.hidden) return;
const s = dev.song;
$("songplay").textContent = t(s.playing ? "songStop" : "songPlay");
$("songadd").disabled = !!s.playing || s.rows.length >= 16;
$("songremove").disabled = !!s.playing || !s.rows.length;
$("songstatus").textContent = s.playing ? `${t("songPlaying")} ${s.row + 1}/${s.count} · ${s.remaining} ${t("songReps")}` : s.count ? "" : t("songEmpty");
const rows = $("songrows");
if (rows.contains(document.activeElement)) return;
rows.replaceChildren();
s.rows.forEach((r, i) => {
const line = el("div", { class: "bar", style: "margin:8px 0" });
line.append(el("span", { text: String(i + 1) }));
const sel = el("select", { disabled: !!s.playing, "aria-label": `${t("slot")} ${i + 1}` });
for (let k = 0; k < 4; k++) sel.append(el("option", { value: k, text: `${t("slot")} ${k + 1}${dev.slotUsed[k] ? "" : ` (${t("empty")})`}` }));
sel.value = String(r.slot);
sel.addEventListener("change", () => { const next = s.rows.map((x) => ({ ...x })); next[i].slot = +sel.value; op(() => changeSong(1, next)); });
const reps = el("input", { type: "number", min: 1, max: 64, value: r.repeat, disabled: !!s.playing, style: "width:64px", "aria-label": `${t("songReps")} ${i + 1}` });
reps.addEventListener("change", () => { const v = +reps.value; if (!Number.isInteger(v) || v < 1 || v > 64) { reps.value = r.repeat; return; } const next = s.rows.map((x) => ({ ...x })); next[i].repeat = v; op(() => changeSong(1, next)); });
line.append(sel, reps, el("span", { text: t("songReps") }));
rows.append(line);
});
}
async function changeSong(action, rows = []) {
const r = parse[CMD.SONG](await rq(req.song(action, rows)));
if (r.rc) throw new Error(r.rc >= 3 ? `${t("slot")} ${r.rc - 2}: ${t("empty")}` : t(r.rc === 2 ? "songBusy" : "songInvalid"));
dev.song = r;
renderSong();
if (action === 1) sayK("songSaved");
}
$("songplay").addEventListener("click", () => op(() => changeSong(dev.song?.playing ? 3 : 2)));
$("songadd").addEventListener("click", () => op(() => changeSong(1, [...dev.song.rows, { slot: dev.song.rows.at(-1)?.slot || 0, repeat: 1 }])));
$("songremove").addEventListener("click", () => op(() => changeSong(1, dev.song.rows.slice(0, -1))));
setInterval(async () => {
if (!dev?.info?.chainRows || busy || document.hidden || !dev.link.idle || tab !== "projects") return;
const releaseBusy = beginBusy();
const d = dev;
try { const r = parse[CMD.SONG](await rq(req.song())); if (d === dev) { d.song = r; renderSong(); } }
catch (err) { report(err); } finally { releaseBusy(); }
}, 1000);
/* Complete archives remain on this computer; no project 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(`JIANT-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)));
if (m.rc || m.track !== selected) throw new Error("Invalid motion state");
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", {}, ...["motionStep", "motionParam", "motionValue"].map(k => el("th", {text:t(k)})), el("th")),
...m.events.map(e => {
const desc = e.param === 127 ? d.gdesc[17] : d.pdesc[e.param], label = desc?.label || `P${e.param}`; /* (0.9.1: 127 the DJ FILTER's) */
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, 3, {...e,value:+value.value})));
if (r.rc) throw new Error("Automation edit refused"); d.motion = r; renderMotion();
}));
return el("tr", {}, el("td", {text:e.step + 1}), el("td", {text:label}), el("td", {}, value),
el("td", {}, el("button", {text:t("remove"),onclick:() => op(async () => {
const r = parse[CMD.MOTION](await sessionRequest(d, req.motion(m.track, 4, e)));
if (r.rc) throw new Error("Automation edit refused"); d.motion = r; renderMotion();
})})));
}));
}
$("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})));
if (r.rc) throw new Error("Automation edit refused"); d.motion = r; renderMotion();
}));
$("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)));
if (r.rc) throw new Error("Automation edit refused"); d.motion = r; renderMotion();
}));
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") })] : [])));
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 notes = el("input", { type: "text", placeholder: "—", spellcheck: "false" });
const hits = el("input", { type: "text", placeholder: "—", spellcheck: "false", class: "hits" });
const time = el("select", {}, ...TIMES.map((n, k) => el("option", { value: k, text: n })));
const acc = el("input", { type: "checkbox" });
const sl = el("input", { type: "checkbox" });
const vel = el("input", { type: "number", min: 0, max: 127 });
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 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)] : []));
tr._c = { notes, hits, time, acc, sl, vel, chance, ratchet };
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);
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);
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 : "") : "";
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 ((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} : {}) })));
}
if (dev.info.motionMax) { dev.motion = parse[CMD.MOTION](await rq(req.motion(dev.sel ?? 0, 2))); renderMotion(); }
$("steptables").dataset.len = "";
renderSteps();
sayK("ready");
} catch (err) { report(err); } finally { releaseBusy(); }
});
/* ---------------------------------------------------------- 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) {
assertSession(d);
if (!d || !hasTracks()) return;
const m = await mixer.read((r, o) => sessionRequest(d, r, o), d.info, { pan: pPan() });
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;
});
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 c = {
lvDesc, pDesc, fader, pan,
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, 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.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);
}
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 && old !== c.value && matrixContextId(d, c.id)) needReload = true;
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;
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) {
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 || dump.p.some((v, i) => v !== d.dump.p[i] && matrixContextId(d, i)); /* (V10.40: or its
* WAVE / MODE, whose knobs can change: rereadEngineDesc rebuilds only if they did) */
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 loadSteps(); sayK("ready"); return; }
if (dump.p[pSlen()] !== oldLen) { $("steptables").dataset.len = ""; renderSteps(); }
if (d.watch) return; /* steps come as STEP_CHANGED */
/* 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);
});
}
function renderPreferences(force = false) {
const d = dev, p = d && d.preferences;
$("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]);
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 });
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", () => {
if (!dev) return;
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 })) };
download(`felucca-${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; }
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, {
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.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.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") })]));
}
$("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"].join(" ").trim() || 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.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);
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";
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 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")));
});
/* device bank */
function bankLoad(slot) {
if (!dev || !dev.bank || slot == null || libBusy) return;
const s = dev.bank.slots[slot];
libOp(async (d, rqf) => {
selfLoad();
const rc = await bank.load(rqf, slot);
if (rc) { sayK("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 (!fm6Ok()) { box.replaceChildren(); return; }
/* (JIANT 0.6.11) the device's voice bank (SLOT B1..B32): its name, and the imported file sent to it whole */
const bankRow = dev.info.fm6Bank ? [el("p", { class: "dim",
text: `${t("fm6BankNow")} ${fm6BankList ? (fm6BankList.valid ? `${fm6BankList.name || "-"} (${fm6BankList.voices.filter((v) => v.used).length})` : t("fm6BankNone")) : "…"}` })] : [];
if (dev.info.fm6Bank && fm6Imported.length > 1)
bankRow.push(el("p", { class: "bar" }, el("button", { text: t("fm6BankSend"), onclick: () => op(fm6BankSend) })));
if (!fm6Imported.length) { box.replaceChildren(...bankRow); 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}`); } }))), ...bankRow);
}
let fm6BankList = null, fm6ImportName = ""; /* (0.6.11) the device's voice bank (FM6B_LIST), the file imported last */
async function fm6BankRefresh(d = dev) {
if (!d || !d.info.fm6Bank) return;
fm6BankList = await fm6Bank.list((r, o) => sessionRequest(d, r, o));
renderFm6Imported();
}
async function fm6BankSend() {
const name = fm6Bank.nameOf(fm6ImportName) || "BANK";
const rc = await fm6Bank.send((r, o) => sessionRequest(dev, r, o), fm6Bank.fromVoices(fm6Imported), name);
if (rc) { sayK("fm6BankFail", `${rc})`); return; }
await fm6BankRefresh();
sayK("fm6BankSent", ` ${name} (${Math.min(32, fm6Imported.length)})`);
}
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();
await fm6BankRefresh(d);
}
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;
fm6ImportName = f.name;
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>