mirror of
https://github.com/isod89/sloop-fm1.git
synced 2026-12-05 12:24:33 +01:00
4045 lines
215 KiB
HTML
4045 lines
215 KiB
HTML
<!doctype html>
|
||
<!-- SPDX-License-Identifier: GPL-3.0-only
|
||
Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments -->
|
||
<!-- 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>SLOOP 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; }
|
||
#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; }
|
||
}
|
||
.smp { margin: 0 0 14px; padding: 6px 0 0; border-top: 1px solid var(--line); }
|
||
.smp.over { outline: 1px solid var(--fg); outline-offset: 2px; }
|
||
.smp .head { display: flex; flex-wrap: wrap; gap: 4px 12px; align-items: center; }
|
||
.smp .head b { font-weight: 600; min-width: 40px; }
|
||
.smp progress { width: 160px; height: 6px; accent-color: var(--fg); }
|
||
.smp table { margin: 4px 0; }
|
||
.smp input.name { width: 80px; text-transform: uppercase; }
|
||
.smp input.root { width: 48px; }
|
||
.smp .bad { text-decoration: underline wavy; }
|
||
.chop canvas.wave { display: block; width: 100%; height: 150px; margin: 6px 0; border: 1px solid var(--line); cursor: default; touch-action: none; }
|
||
.chop canvas.wave:focus { outline: 1px solid var(--fg); }
|
||
.chop .head { margin: 3px 0; }
|
||
.chop .sep { width: 8px; }
|
||
.chop input.num { width: 56px; }
|
||
.chop input[type=range] { width: 90px; accent-color: var(--fg); }
|
||
.chop button.tap { min-width: 72px; }
|
||
.chop .chops { display: flex; flex-wrap: wrap; gap: 3px; margin: 4px 0; }
|
||
.chop .chip { background: none; color: var(--fg); border: 1px solid var(--line); padding: 1px 6px; }
|
||
.chop .chip.on { background: var(--fg); color: var(--bg); }
|
||
.chop .chip.off { color: var(--dim); text-decoration: line-through; }
|
||
footer { margin-top: 24px; font-size: 11px; color: var(--dim); }
|
||
.row.pushed .v { font-weight: 600; }
|
||
/* 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); }
|
||
/* v5: the drum track as 16 lanes x LEN steps; a hit's level by its shade, its ratchet as a number */
|
||
.dgrid { display: grid; gap: 1px; margin: 6px 0 12px; overflow-x: auto; }
|
||
.dgrid .ln { font-size: 10px; color: var(--dim); white-space: nowrap; padding-right: 6px; align-self: center; }
|
||
.dgrid .hd { font-size: 9px; color: var(--dim); }
|
||
.dgrid .gap { grid-column: 1 / -1; height: 8px; }
|
||
.dgrid button { background: var(--bg); color: var(--bg); border: 1px solid var(--line); padding: 0; min-width: 16px; height: 18px;
|
||
font-size: 9px; line-height: 1; font-weight: 700; }
|
||
.dgrid button.beat { border-left-color: var(--fg); }
|
||
.dgrid button.on { background: var(--fg); border-color: var(--fg); opacity: .85; }
|
||
.dgrid button.on.l1 { opacity: .3; }
|
||
.dgrid button.on.l2 { opacity: .6; }
|
||
.dgrid button.on.l3 { opacity: 1; box-shadow: 0 0 0 1px var(--fg); }
|
||
.strip .solo { font-size: 11px; font-weight: 600; visibility: hidden; }
|
||
.strip .solo.on { visibility: visible; }
|
||
/* 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>
|
||
</head>
|
||
<body>
|
||
<main>
|
||
<button class="lang" id="lang"></button>
|
||
<h1>SLOOP Editor</h1>
|
||
<p class="dim"><a href="../installer/" style="color:inherit" data-t="installer"></a></p>
|
||
<!-- always visible: connection, version, sync mode, the tabs and (Sound / Sequencer / Tracks) the track selector -->
|
||
<header class="top">
|
||
<div class="bar">
|
||
<button id="connect" data-t="connect" data-ic="port_usb_c"></button>
|
||
<span id="version" class="dim"></span>
|
||
<span id="live" class="dim"></span>
|
||
<span id="mock" class="dim" hidden data-t="mock"></span>
|
||
</div>
|
||
<div id="status"></div>
|
||
<nav class="tabs" id="tabs" role="tablist">
|
||
<button role="tab" data-tab="sound" data-t="sound" data-ic="symbol_audio"></button>
|
||
<button role="tab" data-tab="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="samples" data-t="samples" data-ic="symbol_waves"></button>
|
||
<button role="tab" data-tab="projects" data-t="projects" data-ic="symbol_folder"></button>
|
||
<button role="tab" data-tab="settings" data-t="tabSettings" data-ic="symbol_cog"></button>
|
||
</nav>
|
||
<div class="trackbar" id="trackbar" hidden><span class="dim" data-t="track"></span><span class="seg" id="trackbtns" role="group"></span></div>
|
||
</header>
|
||
<p class="hint" id="hint" hidden></p>
|
||
|
||
<section class="panel" id="p-sound" data-tab="sound" data-dev hidden>
|
||
<div class="browser" id="browser">
|
||
<label><span data-t="engine"></span><br><select id="engine"></select></label>
|
||
<label><span data-t="presets"></span><br><select id="preset" size="8"></select></label>
|
||
<div>
|
||
<p class="bar"><button id="init" data-t="initSound"></button>
|
||
<button id="factlib" data-t="factoryToLib" data-ic="symbol_folder"></button></p>
|
||
<p class="bar"><button id="savefile" data-t="saveFile" data-ic="symbol_download"></button>
|
||
<button id="loadfile" data-t="loadFile" data-ic="symbol_upload"></button>
|
||
<input type="file" id="file" accept=".json,application/json" hidden></p>
|
||
</div>
|
||
</div>
|
||
<p class="dim" id="drumnote" data-t="drumNote" hidden></p>
|
||
<p class="dim" id="ctlhelp" data-t="ctlHelp"></p>
|
||
<div class="groups" id="groups"></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="bar" id="drumbar" hidden></div>
|
||
<div class="dgrid" id="drumgrid" hidden></div>
|
||
<div class="grid" id="stepgrid"></div>
|
||
<div class="stepcols" id="steptables"></div>
|
||
</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="libcols" id="libsec">
|
||
<div id="libpane">
|
||
<h2 data-t="library" data-ic="symbol_books"></h2>
|
||
<div class="bar">
|
||
<input type="search" id="libq" spellcheck="false">
|
||
<select id="libeng"></select>
|
||
<select id="libtag"></select>
|
||
<select id="libsort"></select>
|
||
</div>
|
||
<div class="list" id="liblist"></div>
|
||
<p class="bar" style="margin-top:6px">
|
||
<button id="libaud" data-t="audition" data-ic="symbol_audio"></button>
|
||
<button id="libput" data-t="toSlot" data-ic="symbol_upload"></button>
|
||
<button id="libren" data-t="rename"></button>
|
||
<button id="libtags" data-t="tags"></button>
|
||
<button id="libdup" data-t="duplicate"></button>
|
||
<button id="libdel" data-t="delete" data-ic="symbol_trash"></button>
|
||
<button id="libexp1" data-t="exportPatch" data-ic="symbol_download"></button>
|
||
</p>
|
||
<p class="bar">
|
||
<button id="libsave" data-t="saveToLib" data-ic="port_disk"></button>
|
||
<button id="libimport" data-t="import" data-ic="symbol_upload"></button>
|
||
<button id="libexport" data-t="exportLib" data-ic="symbol_download"></button>
|
||
<input type="file" id="libfile" accept=".json,application/json" multiple hidden>
|
||
<span class="dim" id="libcount"></span>
|
||
</p>
|
||
</div>
|
||
<div>
|
||
<h2 data-t="bank" data-ic="port_disk"></h2>
|
||
<p class="dim" id="bankhint"></p>
|
||
<div id="bankpane" hidden>
|
||
<div class="bar"><b id="bankhead"></b></div>
|
||
<div class="list" id="banklist"></div>
|
||
<p class="bar" style="margin-top:6px">
|
||
<button id="bkload" data-t="bankLoad" data-ic="symbol_folder_open"></button>
|
||
<button id="bkstore" data-t="bankStore" data-ic="port_disk"></button>
|
||
<button id="bkget" data-t="bankGet" data-ic="symbol_download"></button>
|
||
<button id="bkerase" data-t="erase" data-ic="symbol_trash"></button>
|
||
</p>
|
||
<p class="bar">
|
||
<button id="bkrefresh" data-t="reload" data-ic="control_arrow_loop"></button>
|
||
<button id="bkexport" data-t="exportBank" data-ic="symbol_download"></button>
|
||
<span class="dim" data-t="dndHelp"></span>
|
||
</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
|
||
<section class="panel" id="p-samples" data-tab="samples" data-dev hidden>
|
||
<h2 data-t="samples" data-ic="symbol_waves"></h2>
|
||
<p class="dim" data-t="smpHelp"></p>
|
||
<div class="smp chop" id="chop"></div>
|
||
<div id="smpslots"></div>
|
||
</section>
|
||
|
||
<section class="panel" id="p-projects" data-tab="projects" data-dev hidden>
|
||
<h2 data-t="projects" data-ic="symbol_folder"></h2>
|
||
<p class="dim" data-t="projHelp"></p>
|
||
<div class="slots" id="slots"></div>
|
||
</section>
|
||
|
||
<section class="panel" id="p-settings" data-tab="settings" data-dev hidden>
|
||
<div class="groups" id="setgroups"></div>
|
||
<div class="group" style="margin-top:12px">
|
||
<h2 data-t="system" data-ic="symbol_cog"></h2>
|
||
<table id="sysinfo"></table>
|
||
</div>
|
||
</section>
|
||
|
||
<footer>SLOOP, based on Felucca by Leo Kuroshita (@kurogedelic), <a href="https://hugelton.com" target="_blank" rel="noopener">Hügelton Instruments</a>. GPL-3.0.<br>
|
||
<span data-t="foot"></span> M-VAVE and FM-1 are trademarks of their respective owners.<br>
|
||
<a href="FUKIAI-LICENSE.txt" data-t="iconsCredit"></a></footer>
|
||
</main>
|
||
<script>
|
||
"use strict";
|
||
/*PROTO-BEGIN*/
|
||
/* ---------------------------------------------------------------- protocol --- */
|
||
const HDR = [0x7D, 0x46, 0x4C];
|
||
const CMD = { INFO: 1, GET: 2, SET: 3, DUMP: 4, DESC: 5, STEP_GET: 6, STEP_SET: 7, PRESET: 8, PROJECT: 9, NAMES: 10,
|
||
SMP_BEGIN: 11, SMP_WRITE: 12, SMP_END: 13, SMP_ERASE: 14, SMP_INFO: 15,
|
||
UP_LIST: 16, UP_GET: 17, UP_PUT: 18, UP_STORE: 19, UP_LOAD: 20, UP_ERASE: 21,
|
||
WATCH: 22, CHANGED: 23, RELOAD: 24, PING: 25, STEP_CHANGED: 26,
|
||
TRACK: 27, TRACK_MIX: 28, TRACK_DUMP: 29, TRACK_STEP: 30,
|
||
TRACK_PARAM: 31, TRACK_CHANGED: 32,
|
||
DRUM_STEP: 33 };
|
||
/* 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,
|
||
SWING: 14, FILT: 15 };
|
||
/* v5 (SLOOP 2.0): the drum track's 16 sounds (firmware drums.c LANE_NOTE / LANE_NAME), one per white key
|
||
F3..G5; a hit has a level (NORM, GHOST, SOFT, HARD: OCT- / OCT+ held on the device) and a ratchet x1..x4 */
|
||
const DRUM_LANES = [[36, "KICK"], [35, "KICK 2"], [38, "SNARE"], [39, "CLAP"], [42, "HAT"], [46, "OPEN HAT"], [44, "PEDAL"], [37, "RIM"],
|
||
[40, "SNARE 2"], [43, "LOW TOM"], [48, "HI TOM"], [49, "CRASH"], [51, "RIDE"], [70, "SHAKER"], [63, "CONGA"], [56, "COWBELL"]];
|
||
const LV_NAMES = ["NORM", "GHOST", "SOFT", "HARD"];
|
||
const LV_ORDER = [1, 2, 0, 3]; /* by loudness: GHOST SOFT NORM HARD (as the device's LEVEL knob) */
|
||
/* an empty drum step: no lane on */
|
||
const emptyDrum = () => ({ on: 0, lvl: new Array(16).fill(0), rat: new Array(16).fill(0) });
|
||
|
||
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)) };
|
||
}
|
||
|
||
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); } }
|
||
}
|
||
|
||
/* v5 steps end with level / ratchet (2 bits per note, 7-bit bytes: lvl, hi (bit 0 lvl, bit 1 rat), rat) */
|
||
function stepExt(r, a, o) {
|
||
if (r.i + 3 <= a.length) {
|
||
const lo = r.b(), hi = r.b(), rt = r.b();
|
||
o.lvl = lo | ((hi & 1) << 7);
|
||
o.rat = rt | (((hi >> 1) & 1) << 7);
|
||
}
|
||
return o;
|
||
}
|
||
|
||
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.ntrk = r.i < a.length ? r.b() : 0; /* v3: tracks (0 = older firmware, one instrument) */
|
||
o.proto = r.i < a.length ? r.b() : 0; /* v5: the protocol version (0 = older firmware) */
|
||
return o;
|
||
},
|
||
[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 < 64 && r.i < a.length; i++) o.names.push(r.s());
|
||
return o;
|
||
},
|
||
[CMD.STEP_GET](a) {
|
||
const r = new Reader(a);
|
||
const o = { index: r.b(), n: r.b(), notes: [r.b(), r.b(), r.b(), r.b()], time: r.b(), flags: r.b(), vel: r.b() };
|
||
return stepExt(r, a, 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(), busy: a.length > 3 && a[3] === 1 }; },
|
||
[CMD.NAMES](a) {
|
||
const r = new Reader(a);
|
||
const o = { engine: r.b(), names: [] };
|
||
const n = r.b();
|
||
for (let i = 0; i < n; i++) o.names.push(r.s());
|
||
o.titles = [];
|
||
try { o.titles.push(r.s(), r.s()); } catch (e) { o.titles = []; } /* older firmware: no page titles */
|
||
return o;
|
||
},
|
||
[CMD.SMP_BEGIN](a) { const r = new Reader(a); return { slot: r.b(), rc: r.b() }; },
|
||
[CMD.SMP_WRITE](a) { const r = new Reader(a); return { slot: r.b(), offset: r.b() | (r.b() << 7) | (r.b() << 14), rc: r.b() }; },
|
||
[CMD.SMP_END](a) { return parse[CMD.SMP_BEGIN](a); },
|
||
[CMD.SMP_ERASE](a) { return parse[CMD.SMP_BEGIN](a); },
|
||
[CMD.SMP_INFO](a) {
|
||
const r = new Reader(a);
|
||
const o = { nslots: r.b(), slotKiB: r.b(), slots: [] };
|
||
for (let i = 0; i < o.nslots; i++) o.slots.push({ zones: r.b(), name: r.s(), kib: r.b() });
|
||
return o;
|
||
},
|
||
[CMD.UP_LIST](a) {
|
||
const r = new Reader(a);
|
||
const o = { start: r.b(), count: r.b(), total: r.b(), slots: [] };
|
||
for (let i = 0; i < o.count; i++) o.slots.push({ slot: o.start + i, used: r.b(), engine: r.b(), name: r.s() });
|
||
return o;
|
||
},
|
||
/* needs P_COUNT from INFO */
|
||
[CMD.UP_GET](a, info) {
|
||
const r = new Reader(a);
|
||
const o = { slot: r.b(), used: r.b(), engine: r.b(), name: r.s(), p: [], pattern: [] };
|
||
for (let i = 0; i < info.pcount; i++) o.p.push(r.v());
|
||
for (let i = 0; i < UP.PAT; i++) o.pattern.push([r.b(), r.b()]);
|
||
return o;
|
||
},
|
||
[CMD.UP_PUT](a) { return parse[CMD.SMP_BEGIN](a); },
|
||
[CMD.UP_STORE](a) { return parse[CMD.SMP_BEGIN](a); },
|
||
[CMD.UP_LOAD](a) { return parse[CMD.SMP_BEGIN](a); },
|
||
[CMD.UP_ERASE](a) { return parse[CMD.SMP_BEGIN](a); },
|
||
[CMD.WATCH](a) { return { on: new Reader(a).b() }; },
|
||
[CMD.CHANGED](a) { return parse[CMD.GET](a); },
|
||
[CMD.RELOAD](a) { const r = new Reader(a); return { engine: r.b(), preset: r.b(), track: r.i < a.length ? r.b() : 0 }; },
|
||
[CMD.PING](a) { return {}; },
|
||
[CMD.STEP_CHANGED](a) { const r = new Reader(a); return { index: r.b(), track: r.i < a.length ? r.b() : 0 }; },
|
||
/* v3: tracks. engine === NENGINES: the drum track */
|
||
[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() });
|
||
o.solo = r.i < a.length ? r.b() : 0; /* v5: the tracks soloed (bit per track) */
|
||
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 stepExt(r, a, { 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() });
|
||
},
|
||
/* v5: the drum track's step: the lanes on (16 bits), their levels and ratchets (2 bits each) */
|
||
[CMD.DRUM_STEP](a) {
|
||
const r = new Reader(a);
|
||
const o = { index: r.b(), on: r.b() | (r.b() << 7) | ((r.b() & 3) << 14), lvl: [], rat: [] };
|
||
let lv = 0, rt = 0;
|
||
for (let k = 0; k < 5; k++) lv += r.b() * 2 ** (7 * k);
|
||
for (let k = 0; k < 5; k++) rt += r.b() * 2 ** (7 * k);
|
||
for (let l = 0; l < 16; l++) {
|
||
const on = (o.on >> l) & 1;
|
||
o.lvl.push(on ? Math.floor(lv / 4 ** l) % 4 : 0);
|
||
o.rat.push(on ? Math.floor(rt / 4 ** l) % 4 : 0);
|
||
}
|
||
return o;
|
||
},
|
||
/* 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); },
|
||
};
|
||
|
||
/* 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 = {
|
||
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) => [CMD.STEP_GET, [i]],
|
||
stepSet: (i, st) => {
|
||
const n = Math.max(0, Math.min(4, st.n | 0));
|
||
const notes = [0, 1, 2, 3].map((k) => (st.notes[k] | 0) & 0x7F);
|
||
const ext = st.lvl == null && st.rat == null ? [] /* v5: level / ratchet kept (older firmware ignores them) */
|
||
: [(st.lvl | 0) & 0x7F, (((st.lvl | 0) >> 7) & 1) | ((((st.rat | 0) >> 7) & 1) << 1), (st.rat | 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, ...ext]];
|
||
},
|
||
/* v5: get (d == null) or set the drum track's step i: {on: 16 bits, lvl[16], rat[16]} */
|
||
drumStep: (i, d) => {
|
||
if (!d) return [CMD.DRUM_STEP, [i & 0x7F]];
|
||
let lv = 0, rt = 0;
|
||
for (let l = 0; l < 16; l++) if ((d.on >> l) & 1) { lv += ((d.lvl[l] | 0) & 3) * 4 ** l; rt += ((d.rat[l] | 0) & 3) * 4 ** l; }
|
||
const g7 = (x, n) => Array.from({ length: n }, (_, k) => Math.floor(x / 2 ** (7 * k)) & 0x7F);
|
||
return [CMD.DRUM_STEP, [i & 0x7F, ...g7(d.on & 0xFFFF, 3), ...g7(lv, 5), ...g7(rt, 5)]];
|
||
},
|
||
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 */
|
||
names: (e) => [CMD.NAMES, [e & 0x7F]],
|
||
smpBegin: (s) => [CMD.SMP_BEGIN, [s & 0x7F]],
|
||
smpWrite: (s, off, bytes) => [CMD.SMP_WRITE, [s & 0x7F, off & 0x7F, (off >> 7) & 0x7F, (off >> 14) & 0x7F, ...pack7(bytes)]],
|
||
smpEnd: (s, hdr) => [CMD.SMP_END, [s & 0x7F, ...pack7(hdr)]],
|
||
smpErase: (s) => [CMD.SMP_ERASE, [s & 0x7F]],
|
||
smpInfo: () => [CMD.SMP_INFO, []],
|
||
upList: (start, count) => [CMD.UP_LIST, [start & 0x7F, Math.max(1, Math.min(UP.LIST_MAX, count | 0))]],
|
||
upGet: (s) => [CMD.UP_GET, [s & 0x7F]],
|
||
/* patch: {engine, name, p: P_COUNT values, pattern: 16 x [note, flags]} */
|
||
upPut: (s, pt) => [CMD.UP_PUT, [s & 0x7F, pt.engine & 0x7F, ...strEnc(upName(pt.name)), ...pt.p.flatMap((v) => v14enc(v ?? 0)),
|
||
...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 (3 = drums) */
|
||
track: (sel) => [CMD.TRACK, sel == null ? [] : [sel & 0x7F]],
|
||
trackMix: (tr, level, mute) => [CMD.TRACK_MIX, level == null ? [tr & 0x7F] : [tr & 0x7F, ...v14enc(level), mute ? 1 : 0]],
|
||
trackDump: (tr) => [CMD.TRACK_DUMP, [tr & 0x7F]],
|
||
trackStep: (tr, i, st) => [CMD.TRACK_STEP, st ? [tr & 0x7F, ...req.stepSet(i, st)[1]] : [tr & 0x7F, i & 0x7F]],
|
||
/* v4: get (v == null) or set parameter id (P_*) of track tr, clamped as SET */
|
||
trackParam: (tr, id, v) => [CMD.TRACK_PARAM, v == null ? [tr & 0x7F, id & 0x7F] : [tr & 0x7F, id & 0x7F, ...v14enc(v)]],
|
||
};
|
||
|
||
/* which reply belongs to which request (the device echoes these) */
|
||
function replyMatches(cmd, args, a) {
|
||
switch (cmd) {
|
||
case CMD.GET: case CMD.SET: case CMD.DESC: return a[0] === args[0] && a[1] === args[1];
|
||
case CMD.STEP_GET: case CMD.STEP_SET: case CMD.NAMES:
|
||
case CMD.SMP_BEGIN: case CMD.SMP_END: case CMD.SMP_ERASE: return a[0] === args[0];
|
||
case CMD.SMP_WRITE: return a[0] === args[0] && a[1] === args[1] && a[2] === args[2] && a[3] === args[3];
|
||
case CMD.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: case CMD.DRUM_STEP: return a[0] === args[0];
|
||
case CMD.WATCH: return (a[0] & 1) === (args[0] & 1); /* bit 1: v4 firmware only */
|
||
case CMD.TRACK_STEP: case CMD.TRACK_PARAM: return a[0] === args[0] && a[1] === args[1];
|
||
default: return true;
|
||
}
|
||
}
|
||
|
||
/* strict request/response: one frame in flight, the rest queued. Push frames (CHANGED, RELOAD,
|
||
STEP_CHANGED) can come at any time, also between a request and its reply: they go to onPush. */
|
||
class Link {
|
||
constructor(send, opts = {}) {
|
||
this.sendRaw = send;
|
||
this.q = [];
|
||
this.cur = null;
|
||
this.closed = false;
|
||
this.lastSent = 0; /* Date.now() of the last frame sent (WATCH keep-alive) */
|
||
this.timeout = opts.timeout || 300;
|
||
this.onUnknown = opts.onUnknown || (() => {});
|
||
this.onTimeout = opts.onTimeout || (() => {});
|
||
this.onPush = opts.onPush || (() => {});
|
||
this.onGap = opts.onGap || (() => {}); /* (ms) nothing was sent for that long (WATCH may have ended) */
|
||
}
|
||
get idle() { return !this.cur && !this.q.length; }
|
||
hasQueued(key) { return this.q.some((r) => r.key === key); }
|
||
/* r = [cmd, args]; opt: {timeout, retries, key (coalesce queued requests: the latest args win), front,
|
||
quiet (a timeout is expected: no onTimeout)} */
|
||
request(r, opt = {}) {
|
||
if (this.closed) return Promise.reject(new Error("closed"));
|
||
const [cmd, args] = r;
|
||
if (opt.key) {
|
||
const old = this.q.find((x) => x.key === opt.key);
|
||
if (old) { old.cmd = cmd; old.args = args; return old.promise; }
|
||
}
|
||
let res, rej;
|
||
const promise = new Promise((a, b) => { res = a; rej = b; });
|
||
const item = { cmd, args, key: opt.key, res, rej, promise, quiet: !!opt.quiet,
|
||
timeout: opt.timeout || this.timeout, retries: opt.retries ?? 1 };
|
||
if (opt.front) this.q.unshift(item); else this.q.push(item);
|
||
this.pump();
|
||
return promise;
|
||
}
|
||
pump() {
|
||
if (this.cur || this.closed || !this.q.length) return;
|
||
this.cur = this.q.shift();
|
||
this.fire();
|
||
}
|
||
fire() {
|
||
const c = this.cur;
|
||
const now = Date.now();
|
||
if (this.lastSent && now - this.lastSent > 2500) this.onGap(now - this.lastSent);
|
||
this.lastSent = now;
|
||
try { this.sendRaw(frame(c.cmd, c.args)); } catch (e) { this.finish(null, e); return; }
|
||
c.timer = setTimeout(() => {
|
||
if (this.cur !== c) return;
|
||
if (c.retries-- > 0) { this.fire(); return; }
|
||
if (!c.quiet) this.onTimeout(c.cmd);
|
||
this.finish(null, new Error("timeout (cmd " + c.cmd + ")"));
|
||
}, c.timeout);
|
||
}
|
||
finish(val, err) {
|
||
const c = this.cur;
|
||
if (!c) return;
|
||
clearTimeout(c.timer);
|
||
this.cur = null;
|
||
if (err) c.rej(err); else c.res(val);
|
||
this.pump();
|
||
}
|
||
/* raw incoming MIDI bytes */
|
||
receive(data) {
|
||
const f = unframe(data);
|
||
if (!f) return; /* not ours (notes, clock, other SysEx) */
|
||
if (PUSH.has(f.cmd)) { this.onPush(f); return; }
|
||
const c = this.cur;
|
||
if (!c || f.cmd !== c.cmd || !replyMatches(c.cmd, c.args, f.a)) { this.onUnknown(f); return; }
|
||
this.finish(f.a);
|
||
}
|
||
close() {
|
||
this.closed = true;
|
||
const all = (this.cur ? [this.cur] : []).concat(this.q);
|
||
if (this.cur) clearTimeout(this.cur.timer);
|
||
this.cur = null;
|
||
this.q = [];
|
||
for (const r of all) r.rej(new Error("closed"));
|
||
}
|
||
}
|
||
|
||
/* ------------------------------------------------------------- formatting --- */
|
||
const NOTE_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
|
||
const noteName = (n) => NOTE_NAMES[n % 12] + (Math.floor(n / 12) - 1); /* 60 = C4 */
|
||
/* GM drum notes (35..81) by short names, for the drum track's steps */
|
||
const GM_DRUM = { 35: "KICK2", 36: "KICK", 37: "RIM", 38: "SNARE", 39: "CLAP", 40: "SNARE2", 41: "LTOM2", 42: "CHH", 43: "LTOM",
|
||
44: "PHH", 45: "MTOM2", 46: "OHH", 47: "MTOM", 48: "HTOM2", 49: "CRASH", 50: "HTOM", 51: "RIDE", 52: "CHINA", 53: "BELL",
|
||
54: "TAMB", 55: "SPLASH", 56: "COWBELL", 57: "CRASH2", 58: "VIBRA", 59: "RIDE2", 60: "HBONGO", 61: "LBONGO", 62: "MCONGA",
|
||
63: "HCONGA", 64: "LCONGA", 65: "HTIMB", 66: "LTIMB", 67: "HAGOGO", 68: "LAGOGO", 69: "CABASA", 70: "MARACA", 71: "SWHIS",
|
||
72: "LWHIS", 73: "SGUIRO", 74: "LGUIRO", 75: "CLAVES", 76: "HWOOD", 77: "LWOOD", 78: "MCUICA", 79: "OCUICA", 80: "MTRI", 81: "OTRI" };
|
||
const GM_DRUM_BY_NAME = Object.fromEntries(Object.entries(GM_DRUM).map(([n, s]) => [s, +n]));
|
||
const drumName = (n) => GM_DRUM[n] || String(n);
|
||
/* a note token: a number, a note name (C4, F#3, Bb2) or a GM drum name (KICK, CHH) */
|
||
function parseNote(tok) {
|
||
const dn = GM_DRUM_BY_NAME[tok.toUpperCase()];
|
||
if (dn != null) return dn;
|
||
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 > 0 ? Math.trunc((v * 100 + Math.trunc(d.max / 2)) / d.max) : v), "%"];
|
||
case F.SWING: return [String(50 + Math.trunc((Math.max(0, Math.min(100, v)) + 2) / 4)), "%"]; /* MPC: 50 % straight .. 75 % */
|
||
case F.FILT: return !v ? ["OFF", ""] : v < 0 ? ["LP" + Math.trunc((-v * 100 + 32) / 64), "%"] : ["HP" + Math.trunc((v * 100 + 31) / 63), "%"];
|
||
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: { 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 [String(v), d.unit || ""];
|
||
}
|
||
}
|
||
|
||
/* ---------------------------------------------------------- user samples --- */
|
||
/* A port of tools/sampleio.py (read_any_wav, resample, to_int16, ima_encode, user_slot),
|
||
byte for byte: web/test_web.mjs compares them. */
|
||
const SMP = { SLOT_SIZE: 0x14000, DATA_OFF: 512, RATE: 22050, HDR_LEN: 32 + 16 * 28, MAX_ZONES: 16 };
|
||
SMP.MAX_DATA = SMP.SLOT_SIZE - SMP.DATA_OFF;
|
||
|
||
/* groups of up to 7 bytes, each preceded by their top bits */
|
||
function pack7(b) {
|
||
const out = [];
|
||
for (let i = 0; i < b.length; i += 7) {
|
||
const g = Array.from(b.slice(i, i + 7));
|
||
out.push(g.reduce((m, x, j) => m | (((x >> 7) & 1) << j), 0));
|
||
for (const x of g) out.push(x & 0x7F);
|
||
}
|
||
return out;
|
||
}
|
||
function unpack7(a) {
|
||
const out = [];
|
||
for (let i = 0; i < a.length; i += 8) {
|
||
const top = a[i];
|
||
for (let j = 0; j < 7 && i + 1 + j < a.length; j++) out.push(a[i + 1 + j] | (((top >> j) & 1) << 7));
|
||
}
|
||
return Uint8Array.from(out);
|
||
}
|
||
|
||
const CRC_TABLE = (() => {
|
||
const t = new Uint32Array(256);
|
||
for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; }
|
||
return t;
|
||
})();
|
||
function crc32(b) { let c = 0xFFFFFFFF; for (let i = 0; i < b.length; i++) c = CRC_TABLE[(c ^ b[i]) & 0xFF] ^ (c >>> 8); return (c ^ 0xFFFFFFFF) >>> 0; }
|
||
|
||
const IMA_STEP = [7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88,
|
||
97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658,
|
||
724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660,
|
||
4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818,
|
||
18500, 20350, 22385, 24623, 27086, 29794, 32767];
|
||
const IMA_IDX = [-1, -1, -1, -1, 2, 4, 6, 8];
|
||
/* IMA ADPCM, 4 bit, low nibble first, from predictor 0 / index 0 -> {data, pred, idx} (state at loopStart) */
|
||
function imaEncode(s, loopStart = 0) {
|
||
let pred = 0, idx = 0, atLoop = [0, 0];
|
||
const nib = new Uint8Array(s.length + (s.length & 1));
|
||
for (let n = 0; n < s.length; n++) {
|
||
if (n === loopStart) atLoop = [pred, idx];
|
||
const step = IMA_STEP[idx];
|
||
let diff = s[n] - pred, code = 0;
|
||
if (diff < 0) { code = 8; diff = -diff; }
|
||
let vd = step >> 3;
|
||
if (diff >= step) { code |= 4; diff -= step; vd += step; }
|
||
if (diff >= step >> 1) { code |= 2; diff -= step >> 1; vd += step >> 1; }
|
||
if (diff >= step >> 2) { code |= 1; vd += step >> 2; }
|
||
pred = Math.max(-32768, Math.min(32767, code & 8 ? pred - vd : pred + vd));
|
||
idx = Math.max(0, Math.min(88, idx + IMA_IDX[code & 7]));
|
||
nib[n] = code;
|
||
}
|
||
const out = new Uint8Array(nib.length >> 1);
|
||
for (let k = 0; k < nib.length; k += 2) out[k >> 1] = nib[k] | (nib[k + 1] << 4);
|
||
return { data: out, pred: atLoop[0], idx: atLoop[1] };
|
||
}
|
||
|
||
/* WAV: PCM 8/16/24/32 or float, any channel count, mixed to mono -> {sr, x} (gen_samples.read_any_wav) */
|
||
function parseWav(buf) {
|
||
const d = new Uint8Array(buf), v = new DataView(d.buffer, d.byteOffset, d.byteLength);
|
||
const id = (i) => String.fromCharCode(d[i], d[i + 1], d[i + 2], d[i + 3]);
|
||
if (d.length < 12 || id(0) !== "RIFF" || id(8) !== "WAVE") throw new Error("not a WAV file");
|
||
let i = 12, fmt = null, data = null;
|
||
while (i + 8 <= d.length) {
|
||
const cid = id(i), n = v.getUint32(i + 4, true);
|
||
if (cid === "fmt ") {
|
||
let tag = v.getUint16(i + 8, true);
|
||
const ch = v.getUint16(i + 10, true), sr = v.getUint32(i + 12, true), bits = v.getUint16(i + 22, true);
|
||
if (tag === 0xFFFE) tag = v.getUint16(i + 32, true);
|
||
fmt = { tag, ch, sr, bits };
|
||
} else if (cid === "data") {
|
||
data = [i + 8, Math.min(d.length, i + 8 + n)];
|
||
break;
|
||
}
|
||
i += 8 + n + (n & 1);
|
||
}
|
||
if (!fmt || !data) throw new Error("WAV without fmt/data");
|
||
const { tag, ch, sr, bits } = fmt, bps = bits >> 3, frame = bps * ch;
|
||
if (!(tag === 1 || tag === 3) || !bps || !ch) throw new Error("unsupported WAV format");
|
||
const nfr = Math.floor((data[1] - data[0]) / frame), x = new Float64Array(nfr);
|
||
for (let f = 0; f < nfr; f++) {
|
||
let acc = 0;
|
||
for (let c = 0; c < ch; c++) {
|
||
const o = data[0] + f * frame + c * bps;
|
||
let s;
|
||
if (tag === 3) s = bps === 4 ? v.getFloat32(o, true) : v.getFloat64(o, true);
|
||
else if (bps === 2) s = v.getInt16(o, true) / 32768;
|
||
else if (bps === 3) s = (((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) << 8) >> 8) / 8388608;
|
||
else if (bps === 4) s = v.getInt32(o, true) / 2147483648;
|
||
else s = (d[o] - 128) / 128;
|
||
acc += s;
|
||
}
|
||
x[f] = acc / ch;
|
||
}
|
||
return { sr, x };
|
||
}
|
||
|
||
/* gen_samples.resample: moving average over the ratio, then linear interpolation */
|
||
function resample(x, sr, to) {
|
||
if (sr === to) return Array.from(x);
|
||
if (sr > to) {
|
||
const k = Math.max(1, pyRound(sr / to));
|
||
if (k > 1) {
|
||
const y = new Array(x.length);
|
||
for (let i = 0; i < x.length; i++) { let s = 0; for (let j = i; j < Math.min(x.length, i + k); j++) s += x[j]; y[i] = s / k; }
|
||
x = y;
|
||
}
|
||
}
|
||
const step = sr / to, out = [];
|
||
let p = 0;
|
||
while (p < x.length - 1) { const i = Math.floor(p), f = p - i; out.push(x[i] * (1 - f) + x[i + 1] * f); p += step; }
|
||
return out;
|
||
}
|
||
function pyRound(v) { const f = Math.floor(v), r = v - f; return r > 0.5 ? f + 1 : r < 0.5 ? f : (f % 2 ? f + 1 : f); }
|
||
|
||
/* mono float -> int16, peak normalised to 30000 */
|
||
function normalize(x) {
|
||
let pk = 1e-9;
|
||
for (const v of x) pk = Math.max(pk, Math.abs(v));
|
||
return Int16Array.from(x, (v) => Math.max(-32768, Math.min(32767, Math.trunc(v / pk * 30000))));
|
||
}
|
||
|
||
/* root from a file name like "piano_C4" or "F#3" (C4 = 60), else 60 (sampleio.note_from_name) */
|
||
function rootFromName(name) {
|
||
const m = /(?<![A-Za-z])([A-G])([#b]?)(-?\d)(?!\d)/.exec(name);
|
||
if (!m) return 60;
|
||
const n = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 }[m[1]] + (m[2] === "#" ? 1 : m[2] === "b" ? -1 : 0) + (parseInt(m[3], 10) + 1) * 12;
|
||
return Math.max(0, Math.min(127, n));
|
||
}
|
||
|
||
/* zones: [{s: Int16Array (22050 Hz), root, lo?, hi?}] -> {hdr (480 B), data, zones} (sampleio.user_slot) */
|
||
function buildSlot(name, zonesIn) {
|
||
const zones = [], parts = [];
|
||
let len = 0;
|
||
for (const z of zonesIn) {
|
||
const e = imaEncode(z.s, 0);
|
||
zones.push({ off: len, n: z.s.length, ls: 0, le: z.s.length - 1, root: z.root, lo: z.lo ?? null, hi: z.hi ?? null, pred: e.pred, idx: e.idx });
|
||
parts.push(e.data);
|
||
len += e.data.length;
|
||
}
|
||
const data = new Uint8Array(len);
|
||
let o = 0;
|
||
for (const p of parts) { data.set(p, o); o += p.length; }
|
||
if (len > SMP.MAX_DATA) throw new Error(`too long: ${len} B (max ${SMP.MAX_DATA} B)`);
|
||
if (!zones.length || zones.length > SMP.MAX_ZONES) throw new Error("1..16 files per slot");
|
||
zones.sort((a, b) => a.root - b.root);
|
||
zones.forEach((z, j) => {
|
||
if (z.lo == null) {
|
||
z.lo = j === 0 ? 0 : Math.floor((zones[j - 1].root + z.root) / 2) + 1;
|
||
z.hi = j === zones.length - 1 ? 127 : Math.floor((z.root + zones[j + 1].root) / 2);
|
||
}
|
||
});
|
||
const hdr = new Uint8Array(SMP.HDR_LEN), v = new DataView(hdr.buffer);
|
||
v.setUint32(0, 0x504D5346, true);
|
||
v.setUint16(4, 1, true);
|
||
hdr[6] = zones.length;
|
||
const nm = String(name).toUpperCase().replace(/[^\x20-\x7E]/g, "").slice(0, 8);
|
||
for (let i = 0; i < nm.length; i++) hdr[8 + i] = nm.charCodeAt(i);
|
||
v.setUint32(16, len, true);
|
||
v.setUint32(20, crc32(data), true);
|
||
const rate = pyRound(SMP.RATE / 44100 * 65536);
|
||
zones.forEach((z, j) => {
|
||
const b = 32 + j * 28;
|
||
[z.off, z.n, z.ls, z.le, rate].forEach((x, k) => v.setUint32(b + k * 4, x >>> 0, true));
|
||
v.setInt16(b + 20, z.root * 16, true);
|
||
v.setInt16(b + 22, z.pred, true);
|
||
hdr[b + 24] = z.idx; hdr[b + 25] = z.lo; hdr[b + 26] = z.hi; hdr[b + 27] = 0;
|
||
});
|
||
return { hdr, data, zones };
|
||
}
|
||
|
||
/* ------------------------------------------------------------------- chop --- */
|
||
/* Chopping a recording into a slot (the CHOP block of the samples tab). All at SMP.RATE, positions
|
||
in samples. These are pure: test_web.mjs runs them. */
|
||
const CHOP = { HOP: 128, MAX: 16, FADE_IN: 22, FADE_OUT: 132, PRE: 32 }; /* 5.8 ms frames; fades 1 / 6 ms; start 1.5 ms early */
|
||
|
||
/* onset novelty per frame: the rise of the log energy of the signal's first difference (the attack
|
||
of a hit, not its body), over the louder of the two frames before */
|
||
function chopNovelty(x) {
|
||
const H = CHOP.HOP, F = Math.ceil(x.length / H), L = new Float64Array(F), P = new Float64Array(F), nov = new Float64Array(F);
|
||
let top = 1e-12, ptop = 1e-12;
|
||
for (let f = 0; f < F; f++) {
|
||
let e = 0, p = 0;
|
||
for (let i = f * H, n = Math.min(x.length, i + H); i < n; i++) { const d = x[i] - (i ? x[i - 1] : 0); e += d * d; p += x[i] * x[i]; }
|
||
L[f] = e;
|
||
P[f] = p;
|
||
if (e > top) top = e;
|
||
if (p > ptop) ptop = p;
|
||
}
|
||
for (let f = 0; f < F; f++) { L[f] = Math.log10(L[f] / top + 1e-9); P[f] = Math.log10(P[f] / ptop + 1e-9); } /* 0 = the loudest */
|
||
for (let f = 0; f < F; f++) {
|
||
const before = Math.max(f ? L[f - 1] : -9, f > 1 ? L[f - 2] : -9);
|
||
nov[f] = L[f] > -3.5 ? Math.max(0, L[f] - before) : 0; /* (under -35 dB: no hit) */
|
||
}
|
||
nov.level = P; /* (log10 power, 0 = the loudest frame) */
|
||
return nov;
|
||
}
|
||
|
||
/* the first sample of the hit in frame f: where the signal first reaches 30 % of its peak over the
|
||
frames f-1..f+2, then PRE samples earlier (the attack is kept whole) */
|
||
function chopAttack(x, f) {
|
||
const H = CHOP.HOP, a = Math.max(0, (f - 1) * H), b = Math.min(x.length, (f + 3) * H);
|
||
let pk = 0;
|
||
for (let i = a; i < b; i++) pk = Math.max(pk, Math.abs(x[i]));
|
||
for (let i = a; i < b; i++) if (Math.abs(x[i]) >= 0.3 * pk) return Math.max(0, i - CHOP.PRE);
|
||
return a;
|
||
}
|
||
|
||
/* hits: sens 1 (only the hardest and loudest) .. 10 (every small one); at least 60 ms apart. A hit is a
|
||
sharp rise (nov over thr) to a level (its loudest frame within 3) over the gate */
|
||
function chopHits(x, nov, sens) {
|
||
const k = Math.max(1, Math.min(10, sens)), thr = 0.15 + (10 - k) * 0.08, gate = -(0.5 + k * 0.35);
|
||
const gap = Math.round(0.06 * SMP.RATE / CHOP.HOP), L = nov.level;
|
||
const out = [];
|
||
let last = -1e9;
|
||
for (let f = 0; f < nov.length - 1; f++) { /* (a hit on the very first frame counts too) */
|
||
if (nov[f] < thr || (f && nov[f] < nov[f - 1]) || nov[f] < nov[f + 1]) continue;
|
||
if (L && Math.max(L[f], L[Math.min(L.length - 1, f + 1)], L[Math.min(L.length - 1, f + 2)]) < gate) continue;
|
||
if (f - last < gap) {
|
||
if (out.length && nov[f] > nov[last]) { out[out.length - 1] = chopAttack(x, f); last = f; }
|
||
continue;
|
||
}
|
||
out.push(chopAttack(x, f));
|
||
last = f;
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/* a tap at pos (as heard) moved to the hit it meant: the strongest attack within +-win s, if any */
|
||
function chopSnap(x, nov, pos, win = 0.05) {
|
||
const H = CHOP.HOP, w = Math.round(win * SMP.RATE / H), c = Math.round(pos / H);
|
||
let best = -1, bv = 0.12;
|
||
for (let f = Math.max(1, c - w); f <= Math.min(nov.length - 1, c + w); f++) if (nov[f] > bv) { bv = nov[f]; best = f; }
|
||
return best < 0 ? Math.max(0, Math.min(x.length - 1, Math.round(pos))) : chopAttack(x, best);
|
||
}
|
||
|
||
/* markers every `beats` beats at bpm from start to end */
|
||
function chopGrid(start, end, bpm, beats) {
|
||
const step = SMP.RATE * 60 / bpm * beats, out = [];
|
||
for (let p = start; p < end - step * 0.25 && out.length < 64; p += step) out.push(Math.round(p));
|
||
return out;
|
||
}
|
||
|
||
/* n equal parts of start..end */
|
||
function chopEqual(start, end, n) {
|
||
return Array.from({ length: n }, (_, i) => Math.round(start + (end - start) * i / n));
|
||
}
|
||
|
||
/* the chops of sorted markers: each to the next marker (the last to the end), cut at maxLen samples
|
||
when maxLen > 0 -> [{start, end}] (all of them; the slot takes CHOP.MAX) */
|
||
function chopList(marks, total, maxLen = 0) {
|
||
return marks.map((m, i) => {
|
||
let e = i + 1 < marks.length ? marks[i + 1] : total;
|
||
if (maxLen > 0) e = Math.min(e, m + maxLen);
|
||
return { start: m, end: Math.max(m + 1, e) };
|
||
});
|
||
}
|
||
|
||
/* chops -> slot zones {s (Int16Array, one gain for all: their levels are kept), root, lo, hi, fname}.
|
||
mode 0: one key each from key0 (each key plays its chop at its own speed, the keys between are silent)
|
||
mode 1: the chop `sel` alone over the whole keyboard, at its own speed on key0 */
|
||
function chopZones(x, chops, key0, mode = 0, sel = 0) {
|
||
const use = mode === 1 ? [chops[Math.max(0, Math.min(chops.length - 1, sel))]] : chops.slice(0, CHOP.MAX);
|
||
let pk = 1e-9;
|
||
for (const c of use) for (let i = c.start; i < c.end; i++) pk = Math.max(pk, Math.abs(x[i]));
|
||
return use.map((c, j) => {
|
||
const n = c.end - c.start, s = new Int16Array(n), fi = Math.min(CHOP.FADE_IN, n >> 2), fo = Math.min(CHOP.FADE_OUT, n >> 2);
|
||
for (let i = 0; i < n; i++) {
|
||
let g = 1;
|
||
if (i < fi) g = i / fi;
|
||
if (i >= n - fo) g = Math.min(g, (n - i) / fo);
|
||
s[i] = Math.max(-32768, Math.min(32767, Math.trunc(x[c.start + i] / pk * 30000 * g)));
|
||
}
|
||
const key = Math.min(127, key0 + (mode === 1 ? 0 : j));
|
||
return { s, root: key, lo: mode === 1 ? 0 : key, hi: mode === 1 ? 127 : key,
|
||
fname: `CHOP${String((mode === 1 ? sel : j) + 1).padStart(2, "0")}_${NOTE_NAMES[key % 12]}${Math.floor(key / 12) - 1}.wav` };
|
||
});
|
||
}
|
||
|
||
/* a mono 16-bit WAV at SMP.RATE */
|
||
function wavFile(s) {
|
||
const b = new Uint8Array(44 + s.length * 2), v = new DataView(b.buffer);
|
||
const str = (o, t) => { for (let i = 0; i < t.length; i++) b[o + i] = t.charCodeAt(i); };
|
||
str(0, "RIFF"); v.setUint32(4, 36 + s.length * 2, true); str(8, "WAVEfmt "); v.setUint32(16, 16, true);
|
||
v.setUint16(20, 1, true); v.setUint16(22, 1, true); v.setUint32(24, SMP.RATE, true); v.setUint32(28, SMP.RATE * 2, true);
|
||
v.setUint16(32, 2, true); v.setUint16(34, 16, true); str(36, "data"); v.setUint32(40, s.length * 2, true);
|
||
for (let i = 0; i < s.length; i++) v.setInt16(44 + i * 2, s[i], true);
|
||
return b;
|
||
}
|
||
|
||
/* files [{name, data: Uint8Array}] -> a ZIP (stored, no compression) */
|
||
function zipStore(files) {
|
||
const parts = [], dir = [];
|
||
let off = 0;
|
||
for (const f of files) {
|
||
const nm = new TextEncoder().encode(f.name), crc = crc32(f.data), h = new Uint8Array(30 + nm.length), v = new DataView(h.buffer);
|
||
v.setUint32(0, 0x04034B50, true); v.setUint16(4, 20, true); v.setUint32(14, crc, true);
|
||
v.setUint32(18, f.data.length, true); v.setUint32(22, f.data.length, true); v.setUint16(26, nm.length, true); h.set(nm, 30);
|
||
const c = new Uint8Array(46 + nm.length), w = new DataView(c.buffer);
|
||
w.setUint32(0, 0x02014B50, true); w.setUint16(4, 20, true); w.setUint16(6, 20, true); w.setUint32(16, crc, true);
|
||
w.setUint32(20, f.data.length, true); w.setUint32(24, f.data.length, true); w.setUint16(28, nm.length, true);
|
||
w.setUint32(42, off, true); c.set(nm, 46);
|
||
parts.push(h, f.data);
|
||
dir.push(c);
|
||
off += h.length + f.data.length;
|
||
}
|
||
const size = dir.reduce((a, c) => a + c.length, 0), end = new Uint8Array(22), e = new DataView(end.buffer);
|
||
e.setUint32(0, 0x06054B50, true); e.setUint16(8, files.length, true); e.setUint16(10, files.length, true);
|
||
e.setUint32(12, size, true); e.setUint32(16, off, true);
|
||
const out = new Uint8Array(off + size + 22);
|
||
let o = 0;
|
||
for (const p of [...parts, ...dir, end]) { out.set(p, o); o += p.length; }
|
||
return out;
|
||
}
|
||
|
||
/* -------------------------------------------------------------- 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, 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, "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) */
|
||
function remapParams(p, fromKeys, toKeys) {
|
||
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));
|
||
}
|
||
|
||
/* one pattern step as the firmware keeps it (up_pat_norm): a tie has no note, a rest no flags */
|
||
const patNorm = (n, f) => (f & 4 ? [0, 4] : [n & 0x7F, n ? f & 3 : 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);
|
||
});
|
||
}
|
||
/* pattern -> 16 STEP_SET objects, as the firmware loads one (load_pat16; velocity 96) */
|
||
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 };
|
||
});
|
||
}
|
||
const patternUsed = (pat) => !!pat && pat.some((x) => x && x[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 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(pat) ? pat : 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;
|
||
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 (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 */
|
||
function readLibraryFile(obj, ctx) {
|
||
if (!obj || typeof obj !== "object") throw new Error("not JSON");
|
||
const engIndex = (name, idx, fileEngines) => {
|
||
const nm = name || (fileEngines || [])[idx];
|
||
if (ctx.engines && ctx.engines.length) {
|
||
if (nm) return ctx.engines.indexOf(nm);
|
||
return idx < ctx.engines.length ? idx : -1;
|
||
}
|
||
return idx;
|
||
};
|
||
if (obj.format === "felucca-patch") { /* "Save to file": the whole current sound */
|
||
if (!Array.isArray(obj.p) || !Number.isInteger(obj.engine)) throw new Error("felucca-patch without engine / p");
|
||
const e = engIndex(obj.engineName, obj.engine);
|
||
if (e < 0) return { patches: [], skipped: 1, keys: null };
|
||
return { patches: [cleanPatch({ name: obj.presetName || obj.engineName || "PATCH", engine: e, engineName: obj.engineName,
|
||
p: obj.p.slice(0, ctx.keys ? ctx.keys.length : obj.p.length), pattern: Array.isArray(obj.steps) ? patternFromSteps(obj.steps) : null, tags: ["file"] })],
|
||
skipped: 0, 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 e = engIndex(x.engineName, x.engine | 0, obj.engines);
|
||
if (e < 0) { skipped++; continue; }
|
||
const p = remapParams(x.params, fileKeys, ctx.keys);
|
||
out.push(cleanPatch({ ...x, engine: e, engineName: (ctx.engines || [])[e] || x.engineName || (obj.engines || [])[x.engine], p }));
|
||
}
|
||
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 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 };
|
||
},
|
||
async get(rq, info, slot) { return parse[CMD.UP_GET](await rq(req.upGet(slot)), info); },
|
||
/* -> rc (0 ok) */
|
||
async put(rq, slot, pt) { return parse[CMD.UP_PUT](await rq(req.upPut(slot, pt), 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))));
|
||
return { patch: cleanPatch({ name, engine: dump.engine, engineName: info.engines[dump.engine], p: dump.p, pattern: patternFromSteps(steps) }), dump, steps };
|
||
}
|
||
|
||
/* what loading a sound leaves alone (firmware ui.c param_kept): the mix (LEVEL, PAN, MUTE), the pattern
|
||
parameters (LEN, DIV, SWG, GATE) and the key the part plays in (ROOT, SCL, QNT; CHORD from SLOOP 2.0) */
|
||
const keptIds = (info) => new Set([0, 25, 26, 27, 29, 30, 31, 32, 39, 40, ...(info.pe0 > 49 ? [49] : [])]);
|
||
/* play a patch without writing flash, as UP_LOAD would load it: SET the engine (G_ENGSEL, engine defaults),
|
||
then every parameter of the sound that differs. Never the pattern (LIVE: a sound never changes the
|
||
sequence), the mix or the key. opt: {gEng: G_ENGSEL id, progress(i, n)} -> {wrote: false} */
|
||
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), kept = keptIds(info);
|
||
for (let i = 0; i < n; i++) {
|
||
const v = pt.p[i];
|
||
if (opt.progress) opt.progress(i, n);
|
||
if (v == null || kept.has(i) || v === dump.p[i]) continue;
|
||
await rq(req.set(0, i, v));
|
||
}
|
||
return { wrote: false };
|
||
}
|
||
|
||
/* 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; the drum level is
|
||
G_DRLVL). 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];
|
||
tr.tracks[i].e0 = d.p[info.pe0]; /* the drum track: its kit */
|
||
}
|
||
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. 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)} */
|
||
function makeMockDevice(opt = {}) {
|
||
const NONOFF = ["OFF", "ON"], NDIV = ["1/4", "1/8", "1/16", "1/32", "8T", "16T"], 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 TP = [
|
||
D("LVL", 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("FLT", F.BIPCT, -64, 63, 0), D("PIT", F.BIPCT, -64, 63, 0), D("SHP", F.BIPCT, -64, 63, 0), D("FX", F.BIPCT, -64, 63, 0),
|
||
D("RATE", F.LFOHZ, 0, 127, 60), E("WAVE", ["SIN", "TRI", "SAW", "SQR", "S&H"], 0), D("PHS", F.INT, 0, 127, 0), D("FADE", F.TIME, 0, 127, 0),
|
||
D("PIT", F.BIPCT, -64, 63, 0), D("FLT", F.BIPCT, -64, 63, 0), D("SHP", F.BIPCT, -64, 63, 0), D("AMP", F.PCT, 0, 127, 0),
|
||
E("MODE", ["OFF", "UP", "DN", "UPDN", "RND", "ORD"], 0), E("RATE", NDIV, 2), D("OCT", F.INT, 1, 4, 1), D("GATE", F.PCT, 1, 127, 64),
|
||
D("SWG", F.SWING, 0, 100, 0), D("PROB", F.PCT, 0, 127, 127), E("HOLD", NONOFF, 0), E("ORD", ["NOTE", "PLAY"], 0),
|
||
D("ROOT", F.NOTE, 0, 11, 0), E("SCL", ["CHR", "MAJ", "MIN", "DOR", "MIX", "PEN", "MPEN", "HARM", "PHRY", "LYD", "LOC", "MEL", "BLUES", "WHOLE", "DIMHW", "DIMWH"], 0), E("QNT", ["OFF", "SNAP", "WHITE"], 0), D("TRN", F.SEMI, -24, 24, 0),
|
||
D("LEN", F.STEPS, 1, 64, 16), E("DIV", NDIV, 2), D("SWG", F.SWING, 0, 100, 0), D("GATE", F.PCT, 1, 127, 64),
|
||
D("DST", F.PCT, 0, 127, 0), D("CHO", F.PCT, 0, 127, 0), D("DLY", F.PCT, 0, 127, 0), D("REV", F.PCT, 0, 127, 0),
|
||
E("VCE", ["POLY", "MONO", "LEG", "UNI"], 0), D("GLD", F.TIME, 0, 127, 0), D("PAN", F.BIPCT, -64, 63, 0), E("MUTE", NONOFF, 0),
|
||
E("GLMOD", ["RATE", "TIME"], 0), E("PRIO", ["LAST", "LOW", "HIGH"], 0), E("ALLOC", ["ROT", "REUSE"], 0), D("DTUNE", F.INT, 0, 127, 40),
|
||
E("SLCR", ["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),
|
||
E("CHORD", ["OFF", "TRIAD", "7TH", "9TH", "SUS4", "POWER"], 0),
|
||
];
|
||
const GP = [
|
||
D("BPM", F.BPM, 40, 240, 90), D("SWING", F.SWING, 0, 100, 0), E("CLICK", ["OFF", "REC", "ON"], 0), D("TUNE", F.INT, -50, 50, 0),
|
||
E("TIME", NDIV, 1), D("FDBK", F.PCT, 0, 120, 60), D("COLR", F.PCT, 0, 127, 70), D("MIX", F.PCT, 0, 127, 90),
|
||
D("SIZE", F.PCT, 0, 127, 90), D("DAMP", F.PCT, 0, 127, 60), D("CRT", F.LFOHZ, 0, 127, 40), D("CDP", F.PCT, 0, 127, 60),
|
||
E("MIDI", NDASH, 0), E("SYNC", NDASH, 0), E("ROUT", NDASH, 0), D("CPU", F.INT, 0, 0, 0),
|
||
D("SLOT", F.INT, 1, 4, 1), E("NAME", NDASH, 0), E("LOAD", NGO, 0), E("SAVE", NGO, 0),
|
||
E("ENG", ["ANALOG", "DIGITAL", "PHASE", "LOFI", "SAMPLE", "VOICE", "TRIO", "WHEEL",
|
||
"GRAIN"], 0), E("SET", NGO, 0),
|
||
E("CLRSQ", NGO, 0), E("INIT", NGO, 0),
|
||
D("CH", F.INT, 0, 16, 10), D("LVL", F.INT, 0, 127, 100), D("REV", F.INT, 0, 127, 16),
|
||
D("DUST", F.PCT, 0, 127, 0), D("DUCK", F.PCT, 0, 127, 0), D("FILT", F.FILT, -64, 63, 0),
|
||
E("ROLL", ["1/8", "1/16", "1/32", "32T", "1/64"], 1), E("NEW", NGO, 0),
|
||
];
|
||
/* the drum track's P_E0: its kit (drums.c DRUM_KIT_NAMES; 5 = 808, the power-on kit) */
|
||
const KIT = E("KIT", ["ORIGINAL", "DEEP", "TIGHT", "BRIGHT", "DUST", "808", "909", "606", "VINTAGE", "80S", "TRAP", "DRILL", "BOOMBAP",
|
||
"LO-FI", "HOUSE", "TECHNO", "MINIMAL", "ELECTRO", "JUNGLE", "DUBSTEP", "DEMBOW", "AFRO", "LATIN", "DISCO", "SYNTHWV", "CHIP", "8BIT",
|
||
"ARCADE", "GLITCH", "INDUSTR", "TRIBAL", "HYPER", "AMBIENT", "JAZZ"], 0);
|
||
/* a GM note -> its drum lane (drums.c LANE_OF_GM: 35..81) */
|
||
const LANE_OF_GM = [1, 0, 7, 2, 3, 8, 9, 4, 9, 6, 9, 5, 10, 10, 11, 10, 12, 11, 12, 13, 11, 15, 11, 13, 12, 14, 14, 14, 14, 14,
|
||
14, 14, 15, 15, 13, 13, 15, 15, 13, 13, 7, 7, 7, 14, 14, 15, 15];
|
||
const laneOf = (n) => (n < 35 ? 0 : n > 81 ? 13 : LANE_OF_GM[n - 35]);
|
||
const v5 = !opt.legacy && !opt.v3; /* SLOOP 2.0: steps with level / ratchet, DRUM_STEP, TRACK solo */
|
||
/* the drum step as an old (v1..v4) step: its first 4 lanes as GM notes, ACC when one is hard (editor.c ed_dstep_old) */
|
||
const dOld = (d) => {
|
||
const notes = [];
|
||
let hard = 0;
|
||
for (let l = 0; l < 16 && notes.length < 4; l++) if ((d.on >> l) & 1) { notes.push(DRUM_LANES[l][0]); hard |= d.lvl[l] === 3; }
|
||
const n = notes.length;
|
||
return { n, notes: [...notes, 0, 0, 0, 0].slice(0, 4), time: n ? 0 : 2, flags: hard ? 1 : 0, vel: n ? 100 : 0, lvl: 0, rat: 0 };
|
||
};
|
||
/* an old step written into the drum track: its notes onto their lanes (ed_dstep_from_old) */
|
||
const dFromOld = (d, n, notes, time, flags) => {
|
||
Object.assign(d, emptyDrum());
|
||
if (time !== 0) return;
|
||
for (let i = 0; i < Math.min(4, n); i++) { const l = laneOf(notes[i] & 0x7F); d.on |= 1 << l; d.lvl[l] = flags & 1 ? 3 : 0; }
|
||
};
|
||
/* a step's bytes as STEP_GET sends them (v5: + lvl, hi, rat) */
|
||
const stepOut = (b, x) => {
|
||
b(x.n); x.notes.forEach(b); b(x.time); b(x.flags); b(x.vel);
|
||
if (v5) { b(x.lvl | 0); b((((x.lvl | 0) >> 7) & 1) | ((((x.rat | 0) >> 7) & 1) << 1)); b(x.rat | 0); }
|
||
};
|
||
/* a step written (n, 4 notes, time, flags, vel [, lvl, hi, rat]) */
|
||
const stepIn = (x, a) => {
|
||
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];
|
||
x.lvl = a.length >= 11 ? (a[8] & 0x7F) | ((a[9] & 1) << 7) : 0;
|
||
x.rat = a.length >= 11 ? (a[10] & 0x7F) | (((a[9] >> 1) & 1) << 7) : 0;
|
||
};
|
||
const NONE = D("-", F.INT, 0, 0, 0);
|
||
const RATIO = [".5", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "14", "16"];
|
||
const P = (name, e, env = [10, 70, 90, 60], mono = 0, pat = 0) => ({ name, e, env, mono, pat });
|
||
const ENG = [
|
||
{ name: "ANALOG", titles: ["OSC", "FLT"], edit: [E("WAVE", ["SAW", "SQR", "TRI", "SIN", "PWM"], 0), D("DTN", F.INT, 0, 127, 10, null, "ct"), D("MIX", F.PCT, 0, 127, 64),
|
||
D("NOIS", F.PCT, 0, 127, 0), D("CUT", F.CUTOFF, 0, 127, 90), D("RES", F.PCT, 0, 127, 30), D("DRV", F.PCT, 0, 127, 0), D("KTR", F.PCT, 0, 127, 64)],
|
||
presets: [P("808 BOOM", [3, 0, 0, 0, 127, 0, 48, 0], [0, 112, 0, 52], 1), P("808 DIRTY", [3, 0, 0, 0, 96, 12, 118, 30], [0, 108, 0, 46], 1),
|
||
P("SUB BASS", [3, 0, 0, 0, 127, 0, 10, 0], [0, 60, 118, 24], 1), P("REESE", [0, 22, 64, 0, 56, 22, 36, 40], [0, 70, 118, 28], 1),
|
||
P("WOBBLE", [0, 9, 64, 0, 38, 72, 62, 30], [0, 64, 127, 22], 1, 1), P("FUNK BASS", [1, 6, 50, 0, 50, 30, 22, 64], [0, 55, 62, 20], 1),
|
||
P("G-FUNK LD", [2, 0, 0, 0, 92, 0, 10, 64], [6, 70, 112, 46], 1), P("TRAP PLUCK", [0, 8, 64, 0, 30, 35, 0, 64], [0, 58, 0, 45], 0),
|
||
P("SYN BRASS", [0, 10, 64, 0, 45, 20, 16, 64], [12, 70, 96, 35], 0), P("WARM PAD", [4, 12, 64, 6, 52, 8, 0, 32], [75, 90, 115, 90], 0),
|
||
P("DARK STR", [0, 18, 64, 0, 48, 6, 0, 32], [60, 90, 118, 85], 0), P("ATMOS PAD", [4, 25, 64, 20, 60, 15, 0, 32], [90, 100, 120, 100], 0)] },
|
||
{ name: "DIGITAL", titles: ["OPS", "MOD"], edit: [E("ALG", ["1", "2", "3", "4", "5", "6", "7", "8"], 0), E("R2", RATIO, 1), E("R3", RATIO, 1), E("R4", RATIO, 1),
|
||
D("IDX", F.PCT, 0, 127, 60), D("MDEC", F.TIME, 0, 127, 60), D("FB", F.PCT, 0, 127, 0), NONE],
|
||
presets: [P("RHODES", [4, 1, 1, 14, 26, 35, 0, 0], [0, 85, 35, 55], 0), P("DX RHODES", [4, 1, 1, 14, 85, 45, 0, 0], [0, 82, 40, 55], 0),
|
||
P("WURLI", [4, 1, 2, 3, 62, 35, 8, 0], [0, 75, 30, 45], 0), P("CLAV", [3, 1, 3, 5, 90, 25, 20, 0], [0, 50, 20, 18], 0),
|
||
P("TRAP BELL", [4, 8, 1, 4, 80, 70, 0, 0], [0, 92, 0, 70], 0), P("MUSIC BOX", [4, 4, 3, 9, 45, 75, 0, 0], [0, 90, 0, 75], 0),
|
||
P("MARIMBA", [4, 4, 1, 1, 60, 30, 0, 0], [0, 80, 0, 60], 0), P("FM BASS", [0, 1, 1, 1, 34, 40, 8, 0], [0, 60, 70, 25], 1)] },
|
||
{ 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("DTN", F.INT, 0, 127, 0, null, "ct"), E("LINE", ["MIX", "RING"], 0), D("SUB", F.PCT, 0, 127, 0), NONE],
|
||
presets: [P("CZ BASS", [5, 0, 28, 70, 0, 0, 40, 0], [0, 60, 50, 22], 1), P("SOFT KEYS", [3, 0, 40, 70, 0, 0, 0, 0], [0, 80, 20, 50], 0),
|
||
P("CZ STRING", [0, 4, 50, 40, 12, 0, 0, 0], [50, 90, 105, 75], 0), P("RESO PLUCK", [5, 0, 60, 60, 0, 0, 0, 0], [0, 70, 30, 60], 0, 1),
|
||
P("CZ BRASS", [0, 0, 30, 90, 0, 0, 0, 0], [8, 70, 90, 40], 0)] },
|
||
{ name: "LOFI", titles: ["CHIP", "MOTN"], edit: [E("CHIP", ["4BIT", "4B/2", "8BIT", "1BIT", "STEP"], 0), E("WAVE", ["PLS", "TRI", "SAW", "NOIS", "WRAM"], 0), D("DUTY", F.INT, 0, 127, 64),
|
||
D("CRSH", F.PCT, 0, 127, 0), D("SWP", F.PCT, 0, 127, 0), D("VIB", F.PCT, 0, 127, 0), E("ARP", ["OFF", "OCT", "MAJ", "MIN"], 0), D("TONE", F.PCT, 0, 127, 127)],
|
||
presets: [P("GAME LEAD", [0, 0, 32, 0, 0, 20, 0, 127], [0, 60, 90, 30], 1), P("GB BASS", [1, 1, 0, 0, 0, 0, 0, 90], [0, 50, 70, 20], 1),
|
||
P("8BIT ARP", [2, 0, 96, 0, 0, 0, 2, 110], [0, 60, 80, 40], 0)] },
|
||
{ name: "SAMPLE", titles: ["SET", "TONE"], edit: [E("SET", ["DUSTY", "BASS", "VIBES", "HORNS", "STRGS", "FLUTE", "SCRCH", "PERC", "USR1", "USR2", "USR3"], 0), D("TUNE", F.SEMI, -24, 24, 0), D("BITS", F.INT, 0, 127, 0),
|
||
E("LOOP", NONOFF, 1), D("CUT", F.INT, 0, 127, 127), NONE, D("DRV", F.PCT, 0, 127, 0), NONE],
|
||
presets: [P("DUSTY PNO", [0, 0, 20, 1, 104, 0, 14, 0], [0, 127, 127, 52], 0), P("UP BASS", [1, 0, 0, 1, 118, 0, 12, 0], [0, 127, 127, 26], 1),
|
||
P("VIBES", [2, 0, 0, 1, 127, 0, 0, 0], [0, 127, 127, 72], 0), P("HORN STAB", [3, 0, 0, 1, 120, 0, 20, 0], [0, 127, 127, 22], 0),
|
||
P("STRING STB", [4, 0, 0, 1, 122, 0, 10, 0], [0, 127, 127, 26], 0), P("LOFI FLUTE", [5, 0, 12, 1, 100, 0, 0, 0], [12, 80, 120, 60], 1),
|
||
P("SCRATCH", [6, 0, 0, 1, 127, 0, 8, 0], [0, 127, 127, 18], 0), P("GM KIT", [7, 0, 0, 0, 127, 0, 0, 0], [0, 127, 127, 60], 0),
|
||
P("LOFI KEYS", [0, 0, 45, 1, 78, 0, 30, 0], [0, 127, 110, 60], 0), P("DEEP BASS", [1, -12, 0, 1, 90, 0, 40, 0], [0, 127, 127, 30], 1)] },
|
||
{ name: "VOICE", titles: ["VOWL", "TONE"], edit: [D("VOWL", F.INT, 0, 127, 0), D("VOWL2", 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("BRTH", 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), P("SOUL OOH", [110, 0, 0, 0, 30, 30, 55, 0], [70, 90, 115, 90], 0),
|
||
P("TALKBOX", [32, 95, 60, 0, 100, 4, 75, 0], [4, 70, 110, 40], 1), P("WOW BASS", [95, 0, 68, 0, 100, 0, 80, 0], [0, 70, 70, 30], 1)] },
|
||
{ name: "TRIO", titles: ["OSC", "TONE"], edit: [E("WAVE", ["SAW3", "PLS3", "PPT", "SST", "TRI3", "S&T", "P&S", "P+N", "NOIS", "SYNC", "SYNCP", "SYNC3",
|
||
"RING", "RING3", "R+S", "R+SP"], 0), D("INT2", F.SEMI, -24, 24, 0), D("INT3", F.SEMI, -24, 24, -12), D("DTN", F.INT, 0, 50, 6, null, "ct"),
|
||
E("MODE", ["LP", "BP", "HP", "NOT"], 0), D("CUT", F.CUTOFF, 0, 127, 80), D("RES", F.PCT, 0, 127, 40), D("PW", F.PCT, 0, 127, 64)],
|
||
presets: [P("FAT BASS", [0, 0, -12, 9, 0, 62, 45, 64], [0, 62, 60, 25], 1), P("MIN STAB", [0, 3, 7, 6, 0, 80, 20, 64], [0, 50, 0, 30], 0),
|
||
P("MIN7 STAB", [3, 3, 10, 5, 0, 75, 15, 64], [0, 60, 20, 40], 0), P("SYNC LEAD", [9, 9, 0, 0, 0, 82, 30, 64], [2, 70, 100, 40], 1),
|
||
P("HOOVER", [0, 0, -12, 40, 0, 70, 20, 64], [10, 70, 110, 40], 1)] },
|
||
{ 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("DRV", F.PCT, 0, 127, 0), E("ROTR", ["OFF", "SLOW", "FAST"], 1)],
|
||
presets: [P("SOUL ORGAN", [3, 0, 0, 0, 0, 25, 10, 1], [0, 64, 127, 40], 0), P("GOSPEL", [6, 0, 0, 0, 1, 60, 40, 2], [0, 64, 127, 45], 0),
|
||
P("JAZZ ORGAN", [4, 0, 0, 0, 2, 50, 8, 1], [0, 64, 127, 40], 0), P("DIRTY B3", [5, 0, 0, 0, 0, 60, 90, 2], [0, 64, 127, 40], 0)] },
|
||
{ name: "GRAIN", titles: ["GRAN", "SPRY"], edit: [E("SRC", ["DUSTY", "BASS", "VIBES", "HORNS", "STRGS", "FLUTE", "SCRCH", "PERC", "USR1", "USR2", "USR3"], 0),
|
||
D("POS", F.PCT, 0, 127, 32), D("SIZE", F.PCT, 0, 127, 80), D("DENS", F.PCT, 0, 127, 80),
|
||
D("PTCH", F.SEMI, -24, 24, 0), D("SPRD", F.PCT, 0, 127, 30), D("RAND", F.PCT, 0, 127, 10), D("TONE", F.PCT, 0, 127, 127)],
|
||
presets: [P("LOFI CLOUD", [0, 45, 95, 85, 0, 35, 12, 80], [70, 90, 120, 90], 0), P("VIBE HAZE", [2, 30, 100, 90, 0, 25, 10, 90], [50, 100, 120, 95], 0),
|
||
P("FLUTE DUST", [5, 50, 108, 72, 0, 10, 10, 85], [50, 100, 127, 100], 0)] },
|
||
];
|
||
/* demo patterns of the mock only (the LIVE firmware has no factory patterns: a preset never writes the
|
||
sequencer); used to seed the mock's user presets and track 1 as if they had been recorded */
|
||
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]],
|
||
];
|
||
const P_COUNT = 58, G_COUNT = 32, NSTEP = 64, P_E0 = 50, G_ENGSEL = 20, P_SLCR = 45, P_CHORD = 49;
|
||
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
|
||
/* four tracks (firmware v3); engine / preset / p / step below are the selected track's */
|
||
const NTRK = 4, TRK_DRUM = 3;
|
||
const newTrack = (i) => ({ engine: 0, preset: 0, drum: i === TRK_DRUM,
|
||
p: TP.map((d) => d.def).concat(i === TRK_DRUM ? [5, 0, 0, 0, 0, 0, 0, 0] : new Array(8).fill(0)),
|
||
step: Array.from({ length: NSTEP }, () => ({ n: 0, notes: [0, 0, 0, 0], time: 2, flags: 0, vel: 0, lvl: 0, rat: 0 })),
|
||
dstep: i === TRK_DRUM ? Array.from({ length: NSTEP }, emptyDrum) : null });
|
||
const st = {
|
||
tracks: [0, 1, 2, 3].map(newTrack), sel: 0, rec: 0, solo: 0,
|
||
g: GP.map((d) => d.def),
|
||
slots: [null, null, null, null],
|
||
smp: [0, 1, 2].map(() => ({ flash: new Uint8Array(SMP.SLOT_SIZE).fill(0xFF), zones: 0, name: "", len: 0, next: SMP.DATA_OFF })),
|
||
bank: new Array(opt.slots || 32).fill(null), /* user presets: {engine, name, p, pattern} */
|
||
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 drumSel = () => st.tracks[st.sel].drum;
|
||
const engOf = (t) => (t.drum ? ENG.length : t.engine); /* the engine byte: NENGINES = drums */
|
||
const watchMs = opt.watchMs || 3000;
|
||
const tdesc = (t, id) => (t.drum && id === P_E0 ? KIT : id >= P_E0 ? ENG[t.engine].edit[id - P_E0] : TP[id]);
|
||
const desc = (scope, id) => (scope === 0 && id < P_COUNT ? tdesc(st.tracks[st.sel], id) : scope === 1 && id < G_COUNT ? GP[id] : null);
|
||
const seqEmpty = () => st.step.every((s) => !s.n);
|
||
function loadPat16(pat) { /* ui.c load_pat16 */
|
||
const ps = stepsFromPattern(pat);
|
||
st.step.forEach((s, i) => Object.assign(s, i < 16 ? ps[i] : { n: 0, notes: [0, 0, 0, 0], time: 2, flags: 0, vel: 0 }));
|
||
st.p[29] = 16;
|
||
}
|
||
const loadPattern = (k) => loadPat16(PATTERNS[k][0].map((n, i) => [n, PATTERNS[k][1][i]]));
|
||
function applyPreset(pi, demo) { /* demo: seed the mock (never from a command) */
|
||
if (drumSel()) return;
|
||
const e = ENG[st.engine];
|
||
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]; });
|
||
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; i < P_CHORD; i++) st.p[i] = TP[i].def; /* a factory preset turns the SLICER off (CHORD stays: the key) */
|
||
if (demo && pr.pat && seqEmpty()) loadPattern(pr.pat - 1);
|
||
}
|
||
function setEngine(ei) {
|
||
if (drumSel()) return;
|
||
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);
|
||
}
|
||
const clearSteps = () => st.step.forEach((s) => Object.assign(s, { n: 0, notes: [0, 0, 0, 0], time: 2, flags: 0, vel: 0, lvl: 0, rat: 0 }));
|
||
const snapshot = (name) => ({ engine: st.engine, name, p: st.p.slice(), pattern: patternFromSteps(st.step) });
|
||
/* a few user presets to start with */
|
||
[[0, 0, 0, "MY LEAD"], [1, 1, 1, "GLASS BELL"], [2, 2, 3, "PHASE RESO"], [5, 3, 2, "8BIT ARP"]].forEach(([slot, e, p, name]) => {
|
||
setEngine(e); clearSteps(); applyPreset(p, true);
|
||
st.bank[slot] = snapshot(name);
|
||
clearSteps();
|
||
});
|
||
[[1, 1, 5], [2, 3, 0]].forEach(([i, e, p]) => { st.sel = i; setEngine(e); applyPreset(p); clearSteps(); }); /* MUSIC BOX, GAME LEAD */
|
||
/* a mix to look at: pads left, lead right, and a GM drum pattern on track 4 */
|
||
st.tracks[1].p[39] = -24; st.tracks[2].p[39] = 20; st.tracks[2].p[0] = 92; st.tracks[TRK_DRUM].p[39] = 0;
|
||
/* a boom bap beat on the 16 lanes: kick 0, snare 2, clap 3, hat 4, open hat 5; a ghost snare, a hat roll (x2) */
|
||
const KICK = 0, SNARE = 2, CLAP = 3, HAT = 4, OHAT = 5;
|
||
[[KICK, HAT], [HAT], [HAT], [HAT], [SNARE, HAT], [HAT], [HAT], [KICK, OHAT], [KICK, HAT], [HAT], [KICK], [HAT, SNARE], [SNARE, CLAP], [HAT], [HAT], [OHAT]]
|
||
.forEach((ls, i) => {
|
||
const d = st.tracks[TRK_DRUM].dstep[i];
|
||
for (const l of ls) d.on |= 1 << l;
|
||
if (i === 11) d.lvl[SNARE] = 1; /* GHOST */
|
||
if (i === 14) d.rat[HAT] = 1; /* x2 */
|
||
});
|
||
st.sel = 0;
|
||
setEngine(0);
|
||
clearSteps();
|
||
applyPreset(4, true); /* WOBBLE, a recorded-looking pattern on track 1 (mock only) */
|
||
const project = () => JSON.parse(JSON.stringify({ tracks: st.tracks, sel: st.sel, g: st.g }));
|
||
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;
|
||
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);
|
||
for (let i = 0; i < UP.PAT; i++) { const x = u ? u.pattern[i] : [0, 0]; b(x[0]); b(x[1]); }
|
||
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 = [], pattern = [];
|
||
for (let i = 0; i < P_COUNT; i++) p.push(r.v());
|
||
for (let i = 0; i < UP.PAT; i++) pattern.push(patNorm(r.b(), r.b()));
|
||
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 */
|
||
st.engine = engine;
|
||
st.bank[slot] = { engine, name, p: p.map((x, i) => { const d = desc(0, i); return clamp(x, d.min, d.max); }), pattern };
|
||
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 || drumSel() ? 1 : 0;
|
||
if (!rc) st.bank[a[0]] = snapshot(name || `${ENG[st.engine].name} ${String(a[0] + 1).padStart(2, "0")}`);
|
||
b(a[0]); b(rc);
|
||
break;
|
||
}
|
||
case CMD.UP_LOAD: {
|
||
if (a.length < 1) return null;
|
||
const u = drumSel() ? null : st.bank[a[0]];
|
||
if (u) { /* the sound; the mix, pattern and key parameters stay (param_kept) */
|
||
const KEPT = [0, 25, 26, 27, 29, 30, 31, 32, 39, 40, P_CHORD], mix = KEPT.map((i) => st.p[i]);
|
||
st.engine = u.engine; st.preset = 0; st.p = u.p.slice();
|
||
KEPT.forEach((i, k) => { st.p[i] = mix[k]; });
|
||
/* LIVE firmware: a user preset brings its sound only, never its pattern */
|
||
}
|
||
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;
|
||
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.INFO:
|
||
s(opt.legacy ? "FELUCCA 0.4 BETA (MOCK)" : opt.v3 ? "FELUCCA 0.8 (MOCK)" : "FELUCCA SLOOP 2.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 (v5) b(5);
|
||
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]] = clamp(v14dec(a[2], a[3]), d.min, d.max);
|
||
}
|
||
b(a[0]); b(a[1]); v(arr[a[1]]);
|
||
break;
|
||
}
|
||
case CMD.DUMP:
|
||
b(engOf(st.tracks[st.sel])); 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(engOf(t)); b(t.preset); v(i === TRK_DRUM ? st.g[25] : t.p[0]); b(t.p[40] ? 1 : 0); b((st.rec >> i) & 1); });
|
||
if (v5) b(st.solo & 15);
|
||
break;
|
||
case CMD.TRACK_MIX: {
|
||
if (a.length < 1 || a[0] >= NTRK) return null;
|
||
const t = st.tracks[a[0]], drum = a[0] === TRK_DRUM;
|
||
if (a.length >= 4) {
|
||
const lv = clamp(v14dec(a[1], a[2]), 0, 127);
|
||
if (drum) st.g[25] = lv; else t.p[0] = lv;
|
||
t.p[40] = a[3] ? 1 : 0;
|
||
}
|
||
b(a[0]); v(drum ? st.g[25] : 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(engOf(t)); 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 = tdesc(t, a[1]);
|
||
if (a.length >= 4 && d.max > d.min) t.p[a[1]] = 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 t = st.tracks[a[0]];
|
||
if (t.drum) {
|
||
if (a.length >= 10) dFromOld(t.dstep[a[1]], a[2], a.slice(3, 7), a[7], a[8]);
|
||
b(a[0]); b(a[1]); stepOut(b, dOld(t.dstep[a[1]]));
|
||
break;
|
||
}
|
||
const x = t.step[a[1]];
|
||
if (a.length >= 10) stepIn(x, a.slice(2));
|
||
b(a[0]); b(a[1]); stepOut(b, x);
|
||
break;
|
||
}
|
||
case CMD.DRUM_STEP: { /* v5: index [, on 3 x 7 bits, lvl 5 x 7, rat 5 x 7] */
|
||
if (a.length < 1 || a[0] >= NSTEP) return null;
|
||
const d = st.tracks[TRK_DRUM].dstep[a[0]];
|
||
if (a.length >= 14) {
|
||
const g = (k, n) => a.slice(k, k + n).reduce((x, y, j) => x + y * 2 ** (7 * j), 0);
|
||
const on = g(1, 3) & 0xFFFF, lv = g(4, 5) % 2 ** 32, rt = g(9, 5) % 2 ** 32;
|
||
Object.assign(d, emptyDrum());
|
||
d.on = on;
|
||
for (let l = 0; l < 16; l++) if ((on >> l) & 1) { d.lvl[l] = Math.floor(lv / 4 ** l) % 4; d.rat[l] = Math.floor(rt / 4 ** l) % 4; }
|
||
}
|
||
out.push(...req.drumStep(a[0], d)[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 < 64; i++) s(d.names[i]);
|
||
break;
|
||
}
|
||
case CMD.STEP_GET: case CMD.STEP_SET: {
|
||
if (a.length < 1 || a[0] >= NSTEP) return null;
|
||
if (drumSel()) {
|
||
const d = st.tracks[st.sel].dstep[a[0]];
|
||
if (cmd === CMD.STEP_SET && a.length >= 9) dFromOld(d, a[1], a.slice(2, 6), a[6], a[7]);
|
||
b(a[0]); stepOut(b, dOld(d));
|
||
break;
|
||
}
|
||
const x = st.step[a[0]];
|
||
if (cmd === CMD.STEP_SET && a.length >= 9) stepIn(x, a.slice(1));
|
||
b(a[0]); stepOut(b, x);
|
||
break;
|
||
}
|
||
case CMD.PRESET:
|
||
if (a.length < 2 || a[0] >= ENG.length) return null;
|
||
if (a[0] !== st.engine) setEngine(a[0]);
|
||
applyPreset(a[1]);
|
||
b(engOf(st.tracks[st.sel])); b(st.preset);
|
||
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.slots[k] = project();
|
||
else if (a[0] === 0 && st.slots[k]) Object.assign(st, JSON.parse(JSON.stringify(st.slots[k])));
|
||
b(a[0]); b(k); b(st.slots[k] ? 1 : 0);
|
||
break;
|
||
}
|
||
case CMD.NAMES:
|
||
if (a.length < 1 || a[0] >= ENG.length) return null;
|
||
b(a[0]); b(ENG[a[0]].presets.length); ENG[a[0]].presets.forEach((p) => s(p.name));
|
||
ENG[a[0]].titles.forEach(s);
|
||
break;
|
||
/* user sample slots: the header is checked like the firmware's ed_smp_end() */
|
||
case CMD.SMP_BEGIN: case CMD.SMP_ERASE: {
|
||
if (a.length < 1 || a[0] >= 3) return null;
|
||
const u = st.smp[a[0]];
|
||
if (cmd === CMD.SMP_ERASE) u.flash.fill(0xFF); else u.flash.fill(0xFF, 0, 4096);
|
||
u.zones = 0; u.name = ""; u.len = 0; u.next = SMP.DATA_OFF;
|
||
b(a[0]); b(0);
|
||
break;
|
||
}
|
||
case CMD.SMP_WRITE: {
|
||
if (a.length < 5 || a[0] >= 3) return null;
|
||
const u = st.smp[a[0]], off = a[1] | (a[2] << 7) | (a[3] << 14), dat = unpack7(a.slice(4));
|
||
let rc = 0;
|
||
if (off < SMP.DATA_OFF || (off & 0xFF) || !dat.length || off + dat.length > SMP.SLOT_SIZE || dat.length > 256) rc = 1;
|
||
else {
|
||
if (!(off & 0xFFF)) u.flash.fill(0xFF, off, off + 4096);
|
||
u.flash.set(dat, off);
|
||
u.next = off + dat.length;
|
||
}
|
||
b(a[0]); b(off); b(off >> 7); b(off >> 14); b(rc);
|
||
break;
|
||
}
|
||
case CMD.SMP_END: {
|
||
if (a.length < 2 || a[0] >= 3) return null;
|
||
const u = st.smp[a[0]], hd = unpack7(a.slice(1)), dv = new DataView(hd.buffer);
|
||
let rc = 0;
|
||
if (hd.length < SMP.HDR_LEN || dv.getUint32(0, true) !== 0x504D5346 || dv.getUint16(4, true) !== 1) rc = 2;
|
||
else if (!hd[6] || hd[6] > 16) rc = 5;
|
||
else {
|
||
const len = dv.getUint32(16, true);
|
||
if (len > SMP.MAX_DATA) rc = 1;
|
||
else if (crc32(u.flash.subarray(SMP.DATA_OFF, SMP.DATA_OFF + len)) !== dv.getUint32(20, true)) rc = 3;
|
||
else {
|
||
u.flash.set(hd, 0);
|
||
u.zones = hd[6]; u.len = len;
|
||
u.name = String.fromCharCode(...hd.slice(8, 16)).replace(/\0.*$/, "");
|
||
}
|
||
}
|
||
b(a[0]); b(rc);
|
||
break;
|
||
}
|
||
case CMD.SMP_INFO:
|
||
b(3); b(SMP.SLOT_SIZE / 1024);
|
||
st.smp.forEach((u) => { b(u.zones); s(u.zones ? u.name : ""); b(u.zones ? Math.ceil(u.len / 1024) : 0); });
|
||
break;
|
||
default:
|
||
return null;
|
||
}
|
||
return frame(cmd, out);
|
||
}
|
||
|
||
/* a WebMIDI-like access object: one input and one output named "Felucca" */
|
||
const input = { id: "mock-in", name: "Felucca", type: "input", state: "connected", onmidimessage: null };
|
||
let busy = false;
|
||
const output = {
|
||
id: "mock-out", name: "Felucca", type: "output", state: "connected",
|
||
send(data) {
|
||
const f = unframe(data);
|
||
if (!f) { console.error("mock: refused a frame that is not F0 7D 46 4C ... F7", data); return; }
|
||
if (busy) { console.warn("mock: frame dropped (device holds only one frame)", data); return; }
|
||
busy = true;
|
||
watching(); /* a lapsed WATCH ends before this request counts */
|
||
st.lastReq = Date.now();
|
||
const flash = [CMD.UP_PUT, CMD.UP_STORE, CMD.UP_ERASE].includes(f.cmd) && !opt.legacy;
|
||
setTimeout(() => {
|
||
busy = false;
|
||
const r = handle(f.cmd, f.a);
|
||
if (r && input.onmidimessage) input.onmidimessage({ data: Uint8Array.from(r) });
|
||
const ra = r ? r.slice(5, -1) : [];
|
||
if (r && ((f.cmd === CMD.SET && f.a[0] === 1 && f.a[1] === G_ENGSEL) || f.cmd === CMD.PRESET
|
||
|| (f.cmd === CMD.PROJECT && f.a[0] === 0 && ra[2]) || (f.cmd === CMD.UP_LOAD && !ra[1]))) reloadPush();
|
||
}, f.cmd === CMD.SMP_ERASE ? 900 : f.cmd === CMD.SMP_BEGIN ? 120 : flash ? 150 : f.cmd === CMD.SMP_WRITE ? 25 + Math.random() * 10 : 4 + Math.random() * 12);
|
||
},
|
||
};
|
||
/* WATCH ends by itself watchMs after the last request */
|
||
function watching() {
|
||
if (st.watch && Date.now() - st.lastReq > watchMs) st.watch = false;
|
||
return st.watch;
|
||
}
|
||
function push(cmd, args) {
|
||
if (!watching()) return false;
|
||
const fr = Uint8Array.from(frame(cmd, args));
|
||
setTimeout(() => { if (input.onmidimessage) input.onmidimessage({ data: fr }); }, 0);
|
||
return true;
|
||
}
|
||
const reloadPush = () => push(CMD.RELOAD, opt.legacy ? [st.engine, st.preset] : [engOf(st.tracks[st.sel]), 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 (the drum track: G_DRLVL); pushes CHANGED */
|
||
level(v) {
|
||
const drum = st.sel === TRK_DRUM;
|
||
v = clamp(v, 0, 127);
|
||
if (drum) st.g[25] = v; else st.p[0] = v;
|
||
push(CMD.CHANGED, drum ? [1, 25, ...v14enc(v)] : [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 (drumSel()) { const d = st.tracks[st.sel].dstep[i]; d.on ^= 1 << 4; d.lvl[4] = d.rat[4] = 0; } /* the hat lane */
|
||
else 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,
|
||
stop: () => timers.forEach(clearInterval),
|
||
access: { sysexEnabled: true, inputs: new Map([[input.id, input]]), outputs: new Map([[output.id, output]]), onstatechange: null },
|
||
};
|
||
}
|
||
/*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, symbol_drum: 0xEA66,
|
||
function_filter_lpf_peak: 0xEAA0, ui_slider_vertical: 0xEA73, symbol_books: 0xEADC, control_rec_f: 0xEA09,
|
||
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", EDIT: "ui_knob", VOICE: "symbol_keyboard",
|
||
FX: "symbol_effector", SCL: "symbol_tuning", ARP: "control_arrow_up_down", "SEQ PATTERN": "symbol_grid",
|
||
GLOBAL: "symbol_cog", MASTER: "ui_slider_vertical", DRUMS: "symbol_drum", INSTRUMENT: "symbol_keyboard" };
|
||
const PAGE_IC = { FLT: "function_filter_lpf_peak", FILT: "function_filter_lpf_peak", DLY: "symbol_echo", "REV/CHO": "symbol_spring", SLICER: "symbol_grid" };
|
||
/* 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: {
|
||
other: "English", connect: "接続", disconnect: "切断", mock: "モック(実機なし)",
|
||
sound: "音色", engine: "エンジン", presets: "プリセット", initSound: "音色を初期化",
|
||
track: "トラック", drum: "ドラム",
|
||
saveFile: "ファイルに保存", loadFile: "ファイルを読み込む", projects: "プロジェクト",
|
||
load: "読込", save: "保存", used: "使用中", empty: "空", unknown: "—",
|
||
steps: "ステップ", reload: "再読み込み", clearSeq: "シーケンスを消去",
|
||
notesHelp: "ノートは C4 E4 G4 のように入力(最大 4 音、C4 = 60)。",
|
||
notes: "ノート", time: "タイム", acc: "アクセント", slide: "スライド", vel: "ベロシティ",
|
||
foot: "Chrome か Edge で使えます。", iconsCredit: "アイコン: Fukiai(MIT)Hügelton Instruments",
|
||
nomidi: "このブラウザでは使えません。Chrome か Edge で開いてください。",
|
||
denied: "MIDI(SysEx)の使用が許可されませんでした。",
|
||
nodevice: "SLOOP が見つかりません。USB で接続して、もう一度押してください。",
|
||
connecting: "接続中", reading: "読み込み中 ", steploading: "ステップを読み込み中 ",
|
||
ready: "接続しました", disconnected: "切断されました", lost: "FM-1 が外されました",
|
||
noreply: "応答がありません", error: "エラー: ", busy: "処理中",
|
||
applying: "書き込み中 ", applied: "読み込みました", badfile: "ファイルを読み込めません: ",
|
||
savedSlot: "保存しました: スロット ", loadedSlot: "読み込みました: スロット ", emptySlot: "空のスロットです: ",
|
||
confirmSave: "スロット {n} に上書き保存しますか?", confirmLoad: "スロット {n} を読み込みますか? 今の音色とパターンは置き換わります。",
|
||
confirmClear: "シーケンスを全部消しますか?", confirmInit: "音色を初期化しますか?",
|
||
samples: "サンプル", smpHelp: "WAV をドロップするか選んでください。1 スロットに 16 ファイルまで、モノ 22050 Hz の ADPCM で合計約 7 秒。SAMPLE エンジンの SET(または SLICE エンジンの SRC)で USR1〜USR3 を選ぶと鳴ります。",
|
||
zones: "ゾーン", smpName: "名前", chooseFiles: "ファイルを選ぶ", upload: "書き込む", erase: "消去", clearList: "リストを消す",
|
||
file: "ファイル", root: "ルート", keys: "鍵盤", length: "長さ", remove: "外す",
|
||
chopOpen: "音を開く", chopHelp: "録音(WAV、MP3、AIFF…)を開くかドロップし、チョップを決めてスロットへ。1 キーに 1 チョップ。",
|
||
chopDrop: "ここに録音をドロップ、またはクリック", chopPlay: "▶ 再生", chopStop: "■ 停止", chopTap: "TAP",
|
||
chopSnap: "アタックに吸着", chopClear: "マーカーを消去", chopHits: "アタック検出", chopSens: "感度",
|
||
chopGrid: "グリッド", chopEqual: "等分", chopKey: "最初のキー", chopModeKeys: "1 キーに 1 チョップ",
|
||
chopModeOne: "選択チョップを鍵盤全体に", chopMax: "最大長", chopTo: "送信先", chopZip: "WAV をダウンロード",
|
||
chopChops: "チョップ", chopTooLong: "スロットに入りません", chopTooMany: "(最大 16 チョップ。残りは使われません)",
|
||
chopLoaded: "読み込みました: ", chopSent: "チョップを書き込みました ",
|
||
chopHint: "スペース: 再生中に TAP(停止中は再生/停止)· 1–9 0: 試聴 · ダブルクリック: 追加 · ドラッグ: 移動 · ← →: 微調整 · Del: 削除 · ホイール: ズーム",
|
||
smpTooBig: "大きすぎます", smpDecodeFail: "読み込めません: ", smpUploading: "書き込み中 USR", smpDone: "書き込みました USR",
|
||
smpFail: "サンプルの書き込みに失敗しました: ", smpErased: "消去しました USR",
|
||
confirmErase: "USR{n} を消去しますか?", confirmUpload: "USR{n} に書き込みますか? 今の内容は消えます。",
|
||
layout: "(ファームウェアのパラメーター数が想定と違うため、簡易表示にしています)",
|
||
ctlHelp: "スライダーはクリックしてからホイールか矢印キーで微調整(Shift で 10 ずつ)、ダブルクリックで初期値。",
|
||
live: "● リアルタイム", polling: "○ ポーリング(古いファームウェア)",
|
||
library: "ライブラリ", libSearch: "名前・タグで検索", allEngines: "全エンジン", allTags: "全タグ",
|
||
sortModified: "更新順", sortCreated: "作成順", sortName: "名前順", sortEngine: "エンジン順",
|
||
name: "名前", tagsCol: "タグ", date: "更新",
|
||
audition: "試聴", toSlot: "本体スロットへ", rename: "名前変更", tags: "タグ", duplicate: "複製", delete: "削除",
|
||
exportPatch: "書き出し", saveToLib: "今の音色をライブラリへ", import: "読み込み", exportLib: "ライブラリを書き出し",
|
||
factoryToLib: "ライブラリへコピー", libEmpty: "ライブラリは空です。「今の音色をライブラリへ」やファクトリープリセットのコピー、本体スロットからの取り込み、ファイルの読み込みで追加できます。",
|
||
noMatch: "該当なし", noLibDB: "(ブラウザに保存できません。再読み込みで消えます)",
|
||
bank: "本体のユーザープリセット", bankLoad: "読込", bankStore: "今の音色を保存", bankGet: "ライブラリへ",
|
||
exportBank: "バンクを書き出し", dndHelp: "ライブラリとスロットの間はドラッグでもコピーできます。",
|
||
confirmOverwrite: "スロット {n}({name})を上書きしますか?", confirmEraseSlot: "スロット {n}({name})を消去しますか?",
|
||
confirmDelete: "「{name}」をライブラリから削除しますか?",
|
||
promptName: "名前(本体では英数字 12 文字まで)", promptTags: "タグ(カンマ区切り)",
|
||
promptNameAuto: "名前(英数字 12 文字まで。空なら本体が自動で付けます)",
|
||
auditioning: "試聴の準備中 ", auditioned: "試聴中: ", auditionedPat: "試聴中(パターンも書き込みました): ",
|
||
savedLib: "ライブラリに保存しました: ", copiedLib: "ライブラリにコピーしました: ", imported: "読み込みました: ",
|
||
skippedN: " 件(読めないもの {n} 件)", patchesN: " 件",
|
||
putDone: "本体に書き込みました: スロット ", storedSlot: "本体に保存しました: スロット ", erasedSlot: "消去しました: スロット ",
|
||
loadedUser: "読み込みました: ", reloaded: "本体で音色が変わったので読み直しました", readingBank: "スロットを読み込み中",
|
||
badEngine: "このファームウェアにないエンジンです: ", flashFail: "書き込みに失敗しました(rc {rc})",
|
||
installer: "SLOOP インストーラー",
|
||
tabSeq: "シーケンサー", tabTracks: "トラック", tabSettings: "設定",
|
||
needDevice: "FM-1 を接続すると編集できます。", smpNone: "このファームウェアにはユーザーサンプルのスロットがありません。",
|
||
bankConnect: "FM-1 を接続すると本体のユーザープリセットも扱えます。", bankNone: "このファームウェアにはユーザープリセットがありません。",
|
||
drumNote: "ドラムトラックにはエンジンもプリセットもありません。レベル・パン・ミュートは「トラック」、キットとパターンは「シーケンサー」で。",
|
||
drumGridHelp: "クリック:ヒット/消去(同じレベルとロールなら)。Shift+クリック:ヒットを一段強く(GHOST・SOFT・NORM・HARD)。白鍵 F3〜G5 の 16 音。",
|
||
drumNoSound: "ドラムトラックにはサウンドがありません:トラック 1〜3 を選んでください。",
|
||
kit: "キット", hitLevel: "レベル", ratchet: "ロール", solo: "SOLO",
|
||
drumHelp: "ドラムは KICK SNARE CHH のように GM の名前か番号で入力(最大 4 音)。",
|
||
mixer: "ミキサー", mixHelp: "本体の TRACKS ページと同じ 4 トラック。フェーダーはレベル(ドラムは GLO > DRUMS LEVEL)。パンはどのトラックも選択を変えずに書き込みます(0.8 のファームウェアでは一瞬そのトラックを選びます)。REC は本体での録音待機の表示です。",
|
||
level: "レベル", pan: "パン", mute: "ミュート", rec: "REC", selectTrack: "選択", selectedTrack: "選択中",
|
||
projHelp: "プロジェクトは本体の状態をまとめて保存します: 4 トラックの音色とパターン、選択中のトラック、グローバル設定。",
|
||
system: "システム", firmware: "ファームウェア", sync: "同期", tracksN: "トラック", stepsN: "ステップ数", enginesL: "エンジン",
|
||
smpSlots: "サンプルスロット", userBank: "ユーザープリセット", none: "なし",
|
||
},
|
||
en: {
|
||
other: "日本語", connect: "Connect", disconnect: "Disconnect", mock: "Mock device (no hardware)",
|
||
sound: "Sound", engine: "Engine", presets: "Presets", initSound: "Init sound",
|
||
track: "Track", drum: "Drums",
|
||
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).",
|
||
notes: "Notes", 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: "SLOOP not found. Connect the FM-1 by USB and press Connect again.",
|
||
connecting: "Connecting", reading: "Reading ", steploading: "Reading steps ",
|
||
ready: "Connected", disconnected: "Disconnected", lost: "The FM-1 was unplugged",
|
||
noreply: "No reply from the device", error: "Error: ", busy: "Busy",
|
||
applying: "Writing ", applied: "Loaded", badfile: "Cannot read the file: ",
|
||
savedSlot: "Saved to slot ", loadedSlot: "Loaded slot ", emptySlot: "Empty slot: ",
|
||
confirmSave: "Overwrite slot {n}?", confirmLoad: "Load slot {n}? The current sound and pattern will be replaced.",
|
||
confirmClear: "Clear the whole sequence?", confirmInit: "Reset the sound to the engine defaults?",
|
||
samples: "Samples", smpHelp: "Drop or choose WAV files. Up to 16 files per slot, stored as mono 22050 Hz ADPCM (about 7 s in all). Select USR1–USR3 with SET on the SAMPLE engine (or SRC on the SLICE engine).",
|
||
zones: "zones", smpName: "Name", chooseFiles: "Choose files", upload: "Upload", erase: "Erase", clearList: "Clear list",
|
||
file: "File", root: "Root", keys: "Keys", length: "Length", remove: "Remove",
|
||
chopOpen: "Open a sound", chopHelp: "Open or drop a recording (WAV, MP3, AIFF…), mark the chops, send them to a slot: one chop per key.",
|
||
chopDrop: "Drop a recording here, or click", chopPlay: "▶ Play", chopStop: "■ Stop", chopTap: "TAP",
|
||
chopSnap: "snap to the hit", chopClear: "Clear markers", chopHits: "Find hits", chopSens: "sensitivity",
|
||
chopGrid: "Grid", chopEqual: "Equal parts", chopKey: "First key", chopModeKeys: "one key per chop",
|
||
chopModeOne: "selected chop, whole keyboard", chopMax: "max length", chopTo: "Send to", chopZip: "Download WAVs",
|
||
chopChops: "chops", chopTooLong: "too long for a slot", chopTooMany: "(16 chops at most: the rest are left out)",
|
||
chopLoaded: "Loaded: ", chopSent: "Chops in ",
|
||
chopHint: "space: TAP while it plays (play/stop when stopped) · 1–9 0: listen · double-click: add · drag: move · ← →: nudge · Del: remove · wheel: zoom",
|
||
smpTooBig: "too large", smpDecodeFail: "Cannot read: ", smpUploading: "Uploading USR", smpDone: "Uploaded USR",
|
||
smpFail: "Sample upload failed: ", smpErased: "Erased USR",
|
||
confirmErase: "Erase USR{n}?", confirmUpload: "Write to USR{n}? Its current contents will be replaced.",
|
||
layout: "(The firmware has a different parameter count; showing a plain list.)",
|
||
ctlHelp: "Sliders: click, then fine-tune with the wheel or arrow keys (Shift: steps of 10); double-click resets.",
|
||
live: "● Live", polling: "○ Polling (older firmware)",
|
||
library: "Library", libSearch: "Search name or tag", allEngines: "All engines", allTags: "All tags",
|
||
sortModified: "Recently changed", sortCreated: "Recently added", sortName: "Name", sortEngine: "Engine",
|
||
name: "Name", tagsCol: "Tags", date: "Changed",
|
||
audition: "Audition", toSlot: "To device slot", rename: "Rename", tags: "Tags", duplicate: "Duplicate", delete: "Delete",
|
||
exportPatch: "Export", saveToLib: "Save current sound", import: "Import", exportLib: "Export library",
|
||
factoryToLib: "Copy to library", libEmpty: "The library is empty. Add sounds with \"Save current sound\", by copying a factory preset or a device slot, or by importing a file.",
|
||
noMatch: "No match", noLibDB: "(this browser cannot store it: it is gone after a reload)",
|
||
bank: "User presets on the device", bankLoad: "Load", bankStore: "Store current sound", bankGet: "To library",
|
||
exportBank: "Export bank", dndHelp: "You can also drag between the library and the slots.",
|
||
confirmOverwrite: "Overwrite slot {n} ({name})?", confirmEraseSlot: "Erase slot {n} ({name})?",
|
||
confirmDelete: "Delete \"{name}\" from the library?",
|
||
promptName: "Name (the device keeps 12 ASCII characters)", promptTags: "Tags (comma separated)",
|
||
promptNameAuto: "Name (12 ASCII characters; empty: the device names it)",
|
||
auditioning: "Preparing audition ", auditioned: "Auditioning: ", auditionedPat: "Auditioning (pattern written too): ",
|
||
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: "Loaded ", 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: "SLOOP installer",
|
||
tabSeq: "Sequencer", tabTracks: "Tracks", tabSettings: "Settings",
|
||
needDevice: "Connect the FM-1 to edit.", smpNone: "This firmware has no user sample slots.",
|
||
bankConnect: "Connect the FM-1 to see its user presets too.", bankNone: "This firmware has no user presets.",
|
||
drumNote: "The drum track has no engine or presets. Level, pan and mute: Tracks; the kit and the pattern: Sequencer.",
|
||
drumGridHelp: "Click: a hit / clear it (same level and roll). Shift+click: a hit one level louder (GHOST, SOFT, NORM, HARD). The 16 sounds of the white keys F3..G5.",
|
||
drumNoSound: "The drum track has no sound: select track 1, 2 or 3.",
|
||
kit: "Kit", hitLevel: "Level", ratchet: "Roll", solo: "SOLO",
|
||
drumHelp: "Enter drums by GM name or number, like KICK SNARE CHH (up to 4).",
|
||
mixer: "Mixer", mixHelp: "The four tracks of the device's TRACKS page. The fader is the level (drums: GLO > DRUMS 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 whole device state: the sound and pattern of all four tracks, the selected track and the global settings.",
|
||
system: "System", firmware: "Firmware", sync: "Sync", tracksN: "Tracks", stepsN: "Steps", enginesL: "Engines",
|
||
smpSlots: "Sample slots", userBank: "User presets", none: "none",
|
||
},
|
||
};
|
||
let lang = (navigator.language || "en").toLowerCase().startsWith("ja") ? "ja" : "en";
|
||
const t = (k) => TEXT[lang][k] ?? k;
|
||
let lastKey = null, lastArg = "";
|
||
function sayK(k, arg = "") { lastKey = k; lastArg = arg; $("status").textContent = t(k) + arg; }
|
||
function applyLang() {
|
||
document.documentElement.lang = lang;
|
||
document.querySelectorAll("[data-t]").forEach((e) => setLabel(e, t(e.dataset.t)));
|
||
$("lang").textContent = t("other");
|
||
setLabel($("connect"), t(dev ? "disconnect" : "connect"));
|
||
if (lastKey) $("status").textContent = t(lastKey) + lastArg;
|
||
$("libq").placeholder = t("libSearch");
|
||
renderLive();
|
||
renderLib();
|
||
renderBank();
|
||
renderPanels();
|
||
if (dev) { renderSlots(); renderStepHead(); renderSamples(); renderTrackbar(); renderMixer(); renderSysinfo(); }
|
||
}
|
||
$("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", "sequencer", "tracks", "library", "samples", "projects", "settings"];
|
||
const TAB_KEY = "felucca-editor-tab";
|
||
const TRACK_TABS = new Set(["sound", "sequencer", "tracks"]);
|
||
let tab = (() => {
|
||
const h = location.hash.slice(1);
|
||
if (TABS.includes(h)) return h;
|
||
try { const v = localStorage.getItem(TAB_KEY); if (TABS.includes(v)) return v; } catch (e) { /* no storage */ }
|
||
return "sound";
|
||
})();
|
||
const hasTracks = () => !!dev && !!dev.info && !!dev.info.ntrk;
|
||
function showTab(name) {
|
||
if (!TABS.includes(name)) name = "sound";
|
||
const prev = tab;
|
||
tab = name;
|
||
try { localStorage.setItem(TAB_KEY, name); } catch (e) { /* no storage */ }
|
||
if (location.hash !== "#" + name) history.replaceState(null, "", location.pathname + location.search + "#" + name);
|
||
renderPanels();
|
||
if (name === "tracks" && prev !== "tracks" && hasTracks() && dev.dump) op(readMixer);
|
||
}
|
||
function renderPanels() {
|
||
/* the Tracks tab only with a four-track firmware */
|
||
const tracksOk = !dev || hasTracks() || !dev.info;
|
||
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 = "needDevice"; /* (while connecting the status line says it) */
|
||
if (show && want === "samples" && !dev.smp) { show = false; hint = "smpNone"; }
|
||
p.hidden = !show;
|
||
}
|
||
$("hint").hidden = !hint;
|
||
if (hint) $("hint").textContent = t(hint);
|
||
$("trackbar").hidden = !(ready && hasTracks() && TRACK_TABS.has(want));
|
||
}
|
||
$("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 */
|
||
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 (SET of G_ENGSEL, PRESET, PROJECT load,
|
||
UP_LOAD); the editor re-reads after those anyway, so it skips that many RELOADs for a moment */
|
||
const selfReload = { n: 0, until: 0 };
|
||
function selfLoad() {
|
||
if (!dev || !dev.watch) 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: 58, gcount: 32, pe0: 50 };
|
||
const P = { LEVEL: 0, SLEN: 29, CHORD: 49 };
|
||
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]]] },
|
||
{ 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]]] },
|
||
{ t: "VOICE", pages: [["LEVEL", 0, [0]], ["VOICE", 0, [37, 38, 41, 42]], ["VOICE 2", 0, [43, 44, 39, 40]]] },
|
||
{ t: "FX", pages: [["FX", 0, [33, 34, 35, 36]], ["SLICER", 0, [45, 46, 47, 48]], ["DLY", 1, [4, 5, 6, 7]], ["REV/CHO", 1, [8, 9, 10, 11]]] },
|
||
{ t: "SCL", pages: [["SCL", 0, [25, 26, 27, 49]], ["SCL 2", 0, [28]]] },
|
||
{ 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]]] },
|
||
{ t: "GLOBAL", tab: "setgroups", pages: [["GLOBAL", 1, [0, 1, 2, 3]]] },
|
||
{ t: "MASTER", tab: "setgroups", pages: [["MASTER", 1, [27, 28, 29, 30]]] },
|
||
{ t: "DRUMS", tab: "setgroups", pages: [["DRUMS", 1, [24, 25, 26]]] },
|
||
];
|
||
/* 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", "ROUT", "CPU", "NEW"]);
|
||
const key = (s, id) => s + ":" + id;
|
||
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, G_DRLVL 25) */
|
||
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);
|
||
const gDrLvl = () => { const i = dev.gdesc.findIndex((d, k) => d && k > gEng() && (d.label === "LVL" || d.label === "LEVEL")); return i >= 0 ? i : 25; };
|
||
const isDrum = () => !!dev && !!dev.dump && dev.dump.engine >= dev.info.nengines;
|
||
/* v5 (SLOOP 2.0): the drum track is edited as its 16 lanes (DRUM_STEP); older firmware: as GM notes */
|
||
const drumGrid = () => isDrum() && !!dev.info.proto && dev.info.proto >= 5;
|
||
|
||
/* -------------------------------------------------------------- MIDI --- */
|
||
async function connect() {
|
||
wantConnected = true;
|
||
if (!MOCK && !navigator.requestMIDIAccess) { sayK("nomidi"); return; }
|
||
$("connect").disabled = true;
|
||
sayK("connecting");
|
||
try {
|
||
if (!access) {
|
||
if (MOCK) { mock = makeMockDevice({ legacy: QS.get("legacy") === "1" }); access = mock.access; }
|
||
else {
|
||
try { access = await navigator.requestMIDIAccess({ sysex: true }); }
|
||
catch (e) { sayK("denied"); return; }
|
||
}
|
||
access.onstatechange = onState;
|
||
}
|
||
const isF = (p) => /felucca/i.test(p.name || "") && p.state !== "disconnected";
|
||
const input = [...access.inputs.values()].find(isF);
|
||
const output = [...access.outputs.values()].find(isF);
|
||
if (!input || !output) { sayK("nodevice"); return; }
|
||
const link = new Link((d) => output.send(d), {
|
||
timeout: 300,
|
||
onUnknown: (f) => console.debug("ignored reply", f),
|
||
onTimeout: () => sayK("noreply"),
|
||
onPush: (f) => onPush(f),
|
||
onGap: () => { rewatch = true; },
|
||
});
|
||
input.onmidimessage = (e) => link.receive(e.data);
|
||
if (input.open) await input.open().catch(() => {});
|
||
dev = { link, input, output, info: null, pdesc: [], gdesc: [], names: [], dump: null, steps: [], slotUsed: [null, null, null, null],
|
||
keys: null, watch: false, bank: null };
|
||
setLabel($("connect"), t("disconnect"));
|
||
await load(dev);
|
||
} catch (e) {
|
||
console.error(e);
|
||
if (dev) { /* not unplugged meanwhile (that says "lost") */
|
||
const timeout = /^timeout/.test(e.message);
|
||
disconnect();
|
||
sayK(timeout ? "noreply" : "error", timeout ? "" : e.message);
|
||
}
|
||
} finally {
|
||
$("connect").disabled = false;
|
||
}
|
||
}
|
||
|
||
function disconnect(reasonKey = "disconnected") {
|
||
if (dev) {
|
||
dev.link.close();
|
||
dev.input.onmidimessage = null;
|
||
}
|
||
dev = null;
|
||
busy = 0;
|
||
needReload = false;
|
||
renderPanels();
|
||
renderMixer();
|
||
renderSysinfo();
|
||
renderLive();
|
||
renderLib();
|
||
renderBank();
|
||
$("version").textContent = "";
|
||
setLabel($("connect"), t("connect"));
|
||
sayK(reasonKey);
|
||
}
|
||
|
||
function onState(e) {
|
||
const p = e.port;
|
||
if (!p || !/felucca/i.test(p.name || "")) return;
|
||
if (dev && p.state === "disconnected" && (p.id === dev.input.id || p.id === dev.output.id)) {
|
||
disconnect("lost");
|
||
} else if (!dev && wantConnected && p.state === "connected" && p.type === "output") {
|
||
clearTimeout(onState.tm); /* the device came back: reconnect */
|
||
onState.tm = setTimeout(() => { if (!dev && wantConnected) connect(); }, 800);
|
||
}
|
||
}
|
||
|
||
const rq = (r, opt) => dev.link.request(r, opt);
|
||
async function getDesc(scope, id) { return parse[CMD.DESC](await rq(req.desc(scope, id))); }
|
||
async function getDump() { lastDump = Date.now(); return parse[CMD.DUMP](await rq(req.dump()), dev.info); }
|
||
async function getStep(i) { return parse[CMD.STEP_GET](await rq(req.stepGet(i))); }
|
||
async function getDrumStep(i) { return parse[CMD.DRUM_STEP](await rq(req.drumStep(i))); }
|
||
/* a drum step as an old step (firmware ed_dstep_old): for what still reads dev.steps */
|
||
function drumAsStep(d) {
|
||
const notes = [];
|
||
for (let l = 0; l < 16 && notes.length < 4; l++) if ((d.on >> l) & 1) notes.push(DRUM_LANES[l][0]);
|
||
return { index: d.index, n: notes.length, notes: [...notes, 0, 0, 0, 0].slice(0, 4), time: notes.length ? 0 : 2, flags: 0, vel: notes.length ? 100 : 0 };
|
||
}
|
||
|
||
/* the whole connect sequence */
|
||
async function load(d) {
|
||
busy++;
|
||
try {
|
||
/* the first frame after opening the port can be lost: a few tries */
|
||
d.info = parse[CMD.INFO](await d.link.request(req.info(), { timeout: 500, retries: 3 }));
|
||
$("version").textContent = d.info.version;
|
||
const total = d.info.pcount + d.info.gcount;
|
||
for (let i = 0; i < d.info.pcount; i++) { sayK("reading", `${i + 1}/${total}`); d.pdesc[i] = await getDescOrNull(0, i); }
|
||
for (let i = 0; i < d.info.gcount; i++) { sayK("reading", `${d.info.pcount + i + 1}/${total}`); d.gdesc[i] = await getDescOrNull(1, i); }
|
||
const kd = d.pdesc[d.info.pe0];
|
||
if (kd && kd.label === "KIT" && kd.names.length) d.kitNames = kd.names; /* (the drum track was selected) */
|
||
d.titles = [];
|
||
for (let e = 0; e < d.info.nengines; e++) {
|
||
const r = parse[CMD.NAMES](await d.link.request(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 d.link.request(req.project(2, k))).used; }
|
||
catch (e) { if (e.message === "closed") throw e; }
|
||
}
|
||
try { d.smp = parse[CMD.SMP_INFO](await d.link.request(req.smpInfo())); }
|
||
catch (e) { if (e.message === "closed") throw e; d.smp = null; } /* older firmware, or no flash */
|
||
d.keys = paramKeys(d.pdesc, d.info.pe0, d.info.pcount);
|
||
await libAdopt(d);
|
||
if (d.info.ntrk) d.sel = parse[CMD.TRACK](await d.link.request(req.track())).sel; /* v3: the selected track */
|
||
d.dump = await getDump();
|
||
buildUI();
|
||
renderPanels();
|
||
await loadSteps();
|
||
if (d.info.ntrk) await readMixer();
|
||
/* protocol v2: live pushes and the user bank; older firmware: DUMP polling, no bank */
|
||
const rqd = (r, o) => d.link.request(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) => d.link.request(r, { ...o, quiet: true })); }
|
||
catch (e) { if (e.message === "closed") throw e; d.bank = null; }
|
||
}
|
||
renderLive();
|
||
renderLib();
|
||
renderBank();
|
||
renderSysinfo();
|
||
sayK("ready");
|
||
} finally { busy--; }
|
||
}
|
||
async function getDescOrNull(s, i) { try { return await getDesc(s, i); } catch (e) { if (e.message === "closed") throw e; return null; } }
|
||
|
||
/* rebuilds the controls only when the engine or its parameters changed (a slider being dragged survives) */
|
||
async function rereadEngineDesc() {
|
||
const pe0 = dev.info.pe0;
|
||
const before = JSON.stringify(dev.pdesc.slice(pe0));
|
||
for (let i = 0; i < 8 && pe0 + i < dev.info.pcount; i++) dev.pdesc[pe0 + i] = await getDescOrNull(0, pe0 + i);
|
||
const kd = dev.pdesc[pe0];
|
||
if (kd && kd.label === "KIT" && kd.names.length) dev.kitNames = kd.names; /* the drum track's kits, for the mixer */
|
||
if (dev.built !== dev.dump.engine || JSON.stringify(dev.pdesc.slice(pe0)) !== before) buildGroups();
|
||
}
|
||
|
||
async function loadSteps() {
|
||
const n = dev.info.nstep, drum = drumGrid();
|
||
if (!dev.dsteps) dev.dsteps = [];
|
||
for (let i = 0; i < n; i++) {
|
||
if (i % 8 === 0) sayK("steploading", `${i}/${n}`);
|
||
if (drum) { dev.dsteps[i] = await getDrumStep(i); dev.steps[i] = drumAsStep(dev.dsteps[i]); }
|
||
else dev.steps[i] = await getStep(i);
|
||
}
|
||
dev.dstepsOk = drum;
|
||
renderSteps();
|
||
}
|
||
|
||
/* --------------------------------------------------------------- UI --- */
|
||
function buildUI() {
|
||
const sel = $("engine");
|
||
sel.replaceChildren(...dev.info.engines.map((n, i) => el("option", { value: i, text: n })));
|
||
dev.mix = null;
|
||
buildGroups();
|
||
updateBrowser();
|
||
renderSlots();
|
||
renderSamples();
|
||
renderSysinfo();
|
||
}
|
||
|
||
/* the track selector (v3): T1..T3 synth parts, T4 the drum track; 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) }, `${i + 1}${i === ntrk - 1 ? " " + t("drum") : ""}`)));
|
||
}
|
||
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)],
|
||
["smpSlots", dev.smp ? `${dev.smp.nslots} × ${dev.smp.slotKiB} KiB` : t("none")],
|
||
["userBank", dev.bank ? String(dev.bank.total) : t("none")],
|
||
];
|
||
box.replaceChildren(...rows.map(([k, v]) => el("tr", {}, el("th", { text: t(k) }), el("td", { text: v }))));
|
||
}
|
||
|
||
function updateBrowser() {
|
||
const e = dev.dump.engine;
|
||
const sel = $("engine");
|
||
const drum = e >= dev.info.nengines; /* the drum track: no engine, no presets */
|
||
renderTrackbar();
|
||
sel.disabled = drum;
|
||
$("preset").disabled = drum;
|
||
$("init").disabled = drum;
|
||
$("factlib").disabled = drum;
|
||
$("drumnote").hidden = !drum;
|
||
$("browser").hidden = drum;
|
||
$("groups").hidden = drum;
|
||
$("ctlhelp").hidden = drum;
|
||
if (document.activeElement !== sel) sel.value = drum ? "" : 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 })));
|
||
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 !== "-"; }
|
||
|
||
function buildGroups() {
|
||
ctl.clear();
|
||
dev.built = dev.dump.engine;
|
||
/* Sound: the selected track's parameters; Sequencer: its pattern settings; Settings: globals and drums */
|
||
const groups = { groups: [], seqgroups: [], setgroups: [] };
|
||
const { info } = dev;
|
||
if (info.pcount === EXPECT.pcount && info.gcount === EXPECT.gcount && info.pe0 === EXPECT.pe0) {
|
||
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 }));
|
||
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;
|
||
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 (let v = d.min; v <= d.max; v++) {
|
||
const [txt] = fmtValue(d, v);
|
||
const name = d.fmt === F.ENUM && d.names[v - d.min] == null ? String(v) : txt;
|
||
input.append(el("option", { value: v, ic: wave && WAVE_IC[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;
|
||
}
|
||
|
||
function showValue(k, v, force) {
|
||
const c = ctl.get(k);
|
||
if (!c || v == null) return;
|
||
const [txt, unit] = fmtValue(c.desc, v);
|
||
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();
|
||
}
|
||
} 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;
|
||
busy++;
|
||
try {
|
||
selfLoad();
|
||
parse[CMD.PRESET](await rq(req.preset(e, p)));
|
||
await afterSoundChange();
|
||
} catch (err) { report(err); } finally { busy--; }
|
||
}
|
||
async function afterSoundChange(msg = "ready") {
|
||
needReload = false; /* this re-reads everything a RELOAD asks for */
|
||
dev.dump = await getDump();
|
||
await rereadEngineDesc();
|
||
updateBrowser();
|
||
refreshAll();
|
||
await loadSteps(); /* a preset can bring a pattern */
|
||
if (hasTracks()) await readMixer(); /* the sound names and the selected strip */
|
||
sayK(msg);
|
||
}
|
||
$("init").addEventListener("click", async () => {
|
||
if (!dev || !confirm(t("confirmInit"))) return;
|
||
busy++;
|
||
try { selfLoad(); await rq(req.set(1, gEng(), dev.dump.engine)); await afterSoundChange(); }
|
||
catch (err) { report(err); } finally { busy--; }
|
||
});
|
||
|
||
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() {
|
||
const box = $("slots");
|
||
box.replaceChildren();
|
||
for (let i = 0; i < 4; i++) {
|
||
const u = dev.slotUsed[i];
|
||
box.append(el("span", { text: String(i + 1) }),
|
||
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;
|
||
busy++;
|
||
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 }));
|
||
if (r.busy) throw new Error("Stop playback before loading or saving a section.");
|
||
dev.slotUsed[slot] = r.used;
|
||
renderSlots();
|
||
if (!op && r.used) await afterSoundChange();
|
||
sayK(op ? "savedSlot" : r.used ? "loadedSlot" : "emptySlot", String(slot + 1));
|
||
} catch (err) { report(err); } finally { busy--; }
|
||
}
|
||
|
||
/* ---------------------------------------------------------- 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: GM drum names on the drum track */
|
||
const stepNotes = (s) => s.notes.slice(0, s.n).map(isDrum() ? drumName : noteName).join(" ");
|
||
function renderSteps() {
|
||
if (!dev || !dev.steps.length) return;
|
||
const dg = drumGrid() && !!dev.dstepsOk;
|
||
$("drumbar").hidden = $("drumgrid").hidden = !dg;
|
||
$("stepgrid").hidden = $("steptables").hidden = dg;
|
||
if (dg) { $("noteshelp").textContent = t("drumGridHelp"); renderDrums(); return; }
|
||
const len = stepLen();
|
||
const box = $("steptables");
|
||
const shape = len + (isDrum() ? "d" : "");
|
||
$("noteshelp").textContent = t(isDrum() ? "drumHelp" : "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("time") }),
|
||
el("th", { text: t("acc") }), el("th", { text: t("slide") }), el("th", { text: t("vel") })));
|
||
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 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 tr = el("tr", { "data-i": i }, el("td", { class: "i", text: String(i + 1) }),
|
||
el("td", {}, notes), el("td", {}, time), el("td", {}, acc), el("td", {}, sl), el("td", {}, vel));
|
||
tr._c = { notes, time, acc, sl, vel };
|
||
fillStep(tr, dev.steps[i]);
|
||
const send = () => writeStep(i, tr);
|
||
notes.addEventListener("change", send);
|
||
time.addEventListener("change", send);
|
||
acc.addEventListener("change", send);
|
||
sl.addEventListener("change", send);
|
||
vel.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.time.value = String(s.time);
|
||
c.acc.checked = !!(s.flags & 1);
|
||
c.sl.checked = !!(s.flags & 2);
|
||
c.vel.value = String(s.vel);
|
||
tr.classList.toggle("off", !s.n || s.time === 2);
|
||
}
|
||
function updateStepRows() {
|
||
if (drumGrid() && dev.dstepsOk) { renderDrums(); return; }
|
||
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 = !!s && s.n > 0 && s.time === 0, tie = !!s && s.time === 1;
|
||
const txt = on ? stepNotes(s) : tie ? "—" : "";
|
||
const marks = s && on ? (s.flags & 1 ? " >" : "") + (s.flags & 2 ? " ~" : "") : "";
|
||
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);
|
||
if (!notes) { c.notes.classList.add("bad"); return; }
|
||
c.notes.classList.remove("bad");
|
||
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 && !old.n && time === 2) time = 0; /* typing notes 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)), lvl: old.lvl, rat: old.rat }; /* v5: level / ratchet kept */
|
||
if (s.n && !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); }
|
||
}
|
||
/* ---- v5: the drum track's 16 lanes. A click puts a hit with the level / roll chosen above, or takes it
|
||
away when it already has them; Shift+click steps the level of a hit. One DRUM_STEP per step in flight
|
||
and one queued with the latest lanes (Link coalesces by key). */
|
||
const paint = { lvl: 0, rat: 0 };
|
||
function renderDrumBar() {
|
||
const box = $("drumbar");
|
||
const kd = dev.pdesc[dev.info.pe0], pe0 = dev.info.pe0;
|
||
if (box.dataset.lang !== lang || !box.children.length) {
|
||
box.dataset.lang = lang;
|
||
const kit = el("select", { id: "drumkit", title: t("kit") });
|
||
kit.addEventListener("change", () => userSet(0, pe0, +kit.value, true));
|
||
const seg = (label, vals, name, k) => el("span", { class: "seg", role: "group", "aria-label": label },
|
||
...vals.map((v) => el("button", { type: "button", "data-k": k, "data-v": v, onclick: () => { paint[k] = v; renderDrumBar(); } }, name(v))));
|
||
box.replaceChildren(el("label", {}, t("kit") + " ", kit), el("span", { class: "dim" }, t("hitLevel")),
|
||
seg(t("hitLevel"), LV_ORDER, (v) => LV_NAMES[v], "lvl"),
|
||
el("span", { class: "dim" }, t("ratchet")), seg(t("ratchet"), [0, 1, 2, 3], (v) => "x" + (v + 1), "rat"));
|
||
}
|
||
const kit = $("drumkit");
|
||
const names = kd && kd.fmt === F.ENUM && kd.names.length ? kd.names : null;
|
||
kit.hidden = !names;
|
||
if (names && kit.dataset.n !== String(names.length)) {
|
||
kit.replaceChildren(...names.map((n, i) => el("option", { value: i + kd.min, text: n })));
|
||
kit.dataset.n = String(names.length);
|
||
}
|
||
if (names && document.activeElement !== kit) kit.value = String(dev.dump.p[pe0]);
|
||
for (const b of box.querySelectorAll("button[data-k]")) b.setAttribute("aria-pressed", paint[b.dataset.k] === +b.dataset.v ? "true" : "false");
|
||
}
|
||
function renderDrums() {
|
||
renderDrumBar();
|
||
const box = $("drumgrid"), len = stepLen();
|
||
const shape = `${len}:${lang}`;
|
||
if (box.dataset.shape !== shape) {
|
||
box.dataset.shape = shape;
|
||
const cols = Math.min(16, len);
|
||
box.style.gridTemplateColumns = `auto repeat(${cols}, minmax(16px, 1fr))`;
|
||
const kids = [];
|
||
for (let b0 = 0; b0 < len; b0 += 16) {
|
||
if (b0) kids.push(el("span", { class: "gap" }));
|
||
kids.push(el("span", { class: "hd" }));
|
||
for (let i = b0; i < b0 + cols; i++) kids.push(el("span", { class: "hd", text: i < len && i % 4 === 0 ? String(i + 1) : "" }));
|
||
for (let l = 0; l < 16; l++) {
|
||
kids.push(el("span", { class: "ln", text: DRUM_LANES[l][1] }));
|
||
for (let i = b0; i < b0 + cols; i++) {
|
||
if (i >= len) { kids.push(el("span")); continue; }
|
||
kids.push(el("button", { type: "button", "data-i": i, "data-l": l, class: i % 4 === 0 ? "beat" : null,
|
||
onclick: (e) => drumClick(i, l, e.shiftKey) }));
|
||
}
|
||
}
|
||
}
|
||
box.replaceChildren(...kids);
|
||
}
|
||
for (const b of box.querySelectorAll("button[data-i]")) {
|
||
const i = +b.dataset.i, l = +b.dataset.l, d = dev.dsteps[i];
|
||
const on = !!d && ((d.on >> l) & 1) === 1;
|
||
b.classList.toggle("on", on);
|
||
for (let k = 1; k < 4; k++) b.classList.toggle("l" + k, on && d.lvl[l] === k);
|
||
b.textContent = on && d.rat[l] ? String(d.rat[l] + 1) : "";
|
||
b.title = `${i + 1} ${DRUM_LANES[l][1]}${on ? ` ${LV_NAMES[d.lvl[l]]} x${d.rat[l] + 1}` : ""}`;
|
||
}
|
||
}
|
||
function drumClick(i, l, shift) {
|
||
if (!dev || !dev.dsteps[i]) return;
|
||
const d = { ...dev.dsteps[i], lvl: dev.dsteps[i].lvl.slice(), rat: dev.dsteps[i].rat.slice() };
|
||
const on = (d.on >> l) & 1;
|
||
if (on && shift) d.lvl[l] = LV_ORDER[(LV_ORDER.indexOf(d.lvl[l]) + 1) % 4]; /* louder, then GHOST again */
|
||
else if (on && d.lvl[l] === paint.lvl && d.rat[l] === paint.rat) { d.on &= ~(1 << l); d.lvl[l] = d.rat[l] = 0; }
|
||
else { d.on |= 1 << l; d.lvl[l] = paint.lvl; d.rat[l] = paint.rat; }
|
||
dev.dsteps[i] = d;
|
||
dev.steps[i] = drumAsStep(d);
|
||
stepEdit.set(i, performance.now());
|
||
renderDrums();
|
||
writeDrum(i);
|
||
}
|
||
async function writeDrum(i) {
|
||
const d = dev;
|
||
try {
|
||
const r = parse[CMD.DRUM_STEP](await rq(req.drumStep(i, d.dsteps[i]), { key: "dstep:" + i }));
|
||
if (d !== dev || d.link.hasQueued("dstep:" + i) || r.index !== i) return;
|
||
d.dsteps[i] = r; /* what the device has now */
|
||
d.steps[i] = drumAsStep(r);
|
||
renderDrums();
|
||
} catch (err) { report(err); }
|
||
}
|
||
$("reloadsteps").addEventListener("click", async () => {
|
||
if (!dev) return;
|
||
busy++;
|
||
try { await loadSteps(); sayK("ready"); } catch (err) { report(err); } finally { busy--; }
|
||
});
|
||
$("clearseq").addEventListener("click", async () => {
|
||
if (!dev || !confirm(t("confirmClear"))) return;
|
||
busy++;
|
||
try {
|
||
const drum = drumGrid() && dev.dstepsOk;
|
||
for (let i = 0; i < dev.info.nstep; i++) {
|
||
if (i % 8 === 0) sayK("applying", `${i}/${dev.info.nstep}`);
|
||
if (drum) { dev.dsteps[i] = parse[CMD.DRUM_STEP](await rq(req.drumStep(i, emptyDrum()))); dev.steps[i] = drumAsStep(dev.dsteps[i]); }
|
||
else 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 })));
|
||
}
|
||
$("steptables").dataset.len = "";
|
||
renderSteps();
|
||
sayK("ready");
|
||
} catch (err) { report(err); } finally { busy--; }
|
||
});
|
||
|
||
/* ---------------------------------------------------------- samples --- */
|
||
const smpDraft = [0, 1, 2].map(() => ({ name: "", files: [] }));
|
||
let smpBusy = false;
|
||
const SMP_RC = { 1: "size", 2: "header", 3: "data CRC", 4: "flash", 5: "zones" };
|
||
const kib = (n) => (n / 1024).toFixed(1);
|
||
|
||
/* auto key split, as in buildSlot (for the preview) */
|
||
function splitKeys(files) {
|
||
const z = files.map((f, i) => ({ i, root: f.root })).sort((a, b) => a.root - b.root);
|
||
const out = [];
|
||
z.forEach((x, j) => {
|
||
out[x.i] = [j === 0 ? 0 : Math.floor((z[j - 1].root + x.root) / 2) + 1, j === z.length - 1 ? 127 : Math.floor((x.root + z[j + 1].root) / 2)];
|
||
});
|
||
files.forEach((f, i) => { if (f.lo != null) out[i] = [f.lo, f.hi]; }); /* (chops: their own keys) */
|
||
return out;
|
||
}
|
||
|
||
const draftBytes = (d) => d.files.reduce((a, f) => a + ((f.s.length + 1) >> 1), 0);
|
||
|
||
async function decodeFile(f) {
|
||
const buf = await f.arrayBuffer();
|
||
let x;
|
||
try {
|
||
const w = parseWav(buf);
|
||
x = resample(w.x, w.sr, SMP.RATE);
|
||
} catch (e) { /* not a plain WAV: let the browser decode it */
|
||
const Ctx = window.OfflineAudioContext || window.webkitOfflineAudioContext;
|
||
const ab = await new Ctx(1, 1, SMP.RATE).decodeAudioData(buf.slice(0));
|
||
x = new Float64Array(ab.length);
|
||
for (let c = 0; c < ab.numberOfChannels; c++) { const d = ab.getChannelData(c); for (let i = 0; i < d.length; i++) x[i] += d[i] / ab.numberOfChannels; }
|
||
}
|
||
if (!x.length) throw new Error("no audio");
|
||
return { fname: f.name, s: normalize(x), root: rootFromName(f.name.replace(/\.[^.]*$/, "")) };
|
||
}
|
||
|
||
async function addFiles(k, list) {
|
||
const d = smpDraft[k];
|
||
for (const f of list) {
|
||
try {
|
||
const z = await decodeFile(f);
|
||
if (d.files.length >= SMP.MAX_ZONES) break;
|
||
d.files.push(z);
|
||
if (!d.name) d.name = f.name.replace(/\.[^.]*$/, "").toUpperCase().replace(/[^\x20-\x7E]/g, "").slice(0, 8);
|
||
} catch (e) { sayK("smpDecodeFail", `${f.name} (${e.message})`); }
|
||
}
|
||
renderSamples();
|
||
}
|
||
|
||
function renderSamples() {
|
||
chopUI(); /* (once; then its send buttons follow the device) */
|
||
chopRender();
|
||
const box = $("smpslots"); /* the tab says when there are no slots (renderPanels) */
|
||
if (!dev || !dev.smp) { box.replaceChildren(); return; }
|
||
const max = SMP.MAX_DATA;
|
||
box.replaceChildren(...dev.smp.slots.map((u, k) => {
|
||
const d = smpDraft[k];
|
||
const status = u.zones ? `${u.name || "—"}, ${u.zones} ${t("zones")}, ${u.kib} KiB` : t("empty");
|
||
const bar = el("progress", { max: dev.smp.slotKiB, value: u.kib, title: `${u.kib} / ${dev.smp.slotKiB} KiB` });
|
||
const file = el("input", { type: "file", accept: ".wav,audio/wav,audio/x-wav,audio/*", multiple: true, hidden: true });
|
||
file.addEventListener("change", () => { addFiles(k, [...file.files]); file.value = ""; });
|
||
const name = el("input", { type: "text", class: "name", maxlength: 8, value: d.name, spellcheck: "false", placeholder: "NAME" });
|
||
name.addEventListener("input", () => {
|
||
const v = name.value.toUpperCase().replace(/[^\x20-\x7E]/g, "").slice(0, 8);
|
||
if (v !== name.value) name.value = v;
|
||
d.name = v;
|
||
});
|
||
const bytes = draftBytes(d), tooBig = bytes > max;
|
||
const size = el("span", { class: tooBig ? "bad" : "dim",
|
||
text: d.files.length ? `${kib(bytes)} / ${kib(max)} KiB` + (tooBig ? " " + t("smpTooBig") : "") : "" });
|
||
const prog = el("progress", { max: 1, value: 0, hidden: true });
|
||
const blk = el("div", { class: "smp", "data-k": k },
|
||
el("div", { class: "head" }, el("b", { text: `USR${k + 1}` }), el("span", { text: status }), bar,
|
||
el("button", { ic: "symbol_trash", disabled: smpBusy || !u.zones, onclick: () => smpErase(k) }, t("erase"))),
|
||
el("div", { class: "head" }, el("span", { text: t("smpName") }), name,
|
||
el("button", { ic: "symbol_folder_open", disabled: smpBusy, onclick: () => file.click() }, t("chooseFiles")), file,
|
||
el("button", { ic: "symbol_upload", disabled: smpBusy || !d.files.length || tooBig || !d.name, onclick: () => smpUpload(k, prog) }, t("upload")),
|
||
d.files.length ? el("button", { text: t("clearList"), disabled: smpBusy, onclick: () => { d.files = []; renderSamples(); } }) : "",
|
||
size, prog));
|
||
if (d.files.length) {
|
||
const keys = splitKeys(d.files);
|
||
const tb = el("table", {}, el("tr", {}, el("th", { text: t("file") }), el("th", { text: t("root") }),
|
||
el("th", { text: t("keys") }), el("th", { text: t("length") }), el("th")));
|
||
d.files.forEach((f, i) => {
|
||
const root = el("input", { type: "text", class: "root", value: noteName(f.root), spellcheck: "false" });
|
||
root.addEventListener("change", () => {
|
||
const n = parseNote(root.value.trim());
|
||
if (n == null) { root.classList.add("bad"); return; }
|
||
f.root = n;
|
||
renderSamples();
|
||
});
|
||
tb.append(el("tr", {}, el("td", { text: f.fname }), el("td", {}, root),
|
||
el("td", { text: `${noteName(keys[i][0])}–${noteName(keys[i][1])}` }),
|
||
el("td", { text: `${(f.s.length / SMP.RATE).toFixed(2)} s` }),
|
||
el("td", {}, el("button", { text: t("remove"), disabled: smpBusy, onclick: () => { d.files.splice(i, 1); renderSamples(); } }))));
|
||
});
|
||
blk.append(tb);
|
||
}
|
||
blk.addEventListener("dragover", (e) => { e.preventDefault(); blk.classList.add("over"); });
|
||
blk.addEventListener("dragleave", () => blk.classList.remove("over"));
|
||
blk.addEventListener("drop", (e) => {
|
||
e.preventDefault();
|
||
blk.classList.remove("over");
|
||
if (!smpBusy && e.dataTransfer.files.length) addFiles(k, [...e.dataTransfer.files]);
|
||
});
|
||
return blk;
|
||
}));
|
||
}
|
||
|
||
async function smpInfo() { dev.smp = parse[CMD.SMP_INFO](await rq(req.smpInfo())); }
|
||
|
||
async function smpUpload(k, prog, ask = true) {
|
||
const d = smpDraft[k];
|
||
let built, done = false;
|
||
try { built = buildSlot(d.name, d.files.map((f) => ({ s: f.s, root: f.root, lo: f.lo, hi: f.hi }))); }
|
||
catch (e) { sayK("smpFail", e.message); return false; }
|
||
if (ask && !confirm(t("confirmUpload").replace("{n}", k + 1))) return false;
|
||
const { hdr, data } = built;
|
||
busy++;
|
||
smpBusy = true;
|
||
renderSamples();
|
||
prog = $("smpslots").querySelector(`[data-k="${k}"] progress[max="1"]`);
|
||
prog.hidden = false;
|
||
try {
|
||
const t0 = performance.now();
|
||
let r = parse[CMD.SMP_BEGIN](await rq(req.smpBegin(k), { timeout: 1000, retries: 0 }));
|
||
if (r.rc) throw new Error("begin rc " + r.rc);
|
||
for (let off = 0; off < data.length; off += 256) {
|
||
const a = SMP.DATA_OFF + off;
|
||
const w = parse[CMD.SMP_WRITE](await rq(req.smpWrite(k, a, data.subarray(off, off + 256)), { timeout: 1000, retries: 1 }));
|
||
if (w.rc) throw new Error(`write at 0x${a.toString(16)} rc ${w.rc}`);
|
||
prog.value = (off + 256) / data.length;
|
||
sayK("smpUploading", `${k + 1} ${kib(Math.min(data.length, off + 256))} / ${kib(data.length)} KiB`);
|
||
}
|
||
r = parse[CMD.SMP_END](await rq(req.smpEnd(k, hdr), { timeout: 2000, retries: 0 }));
|
||
if (r.rc) throw new Error(`end rc ${r.rc} (${SMP_RC[r.rc] || "?"})`);
|
||
sayK("smpDone", `${k + 1} ${((performance.now() - t0) / 1000).toFixed(1)} s`);
|
||
done = true;
|
||
} catch (e) {
|
||
if (e.message !== "closed") sayK("smpFail", e.message);
|
||
} finally {
|
||
try { if (dev) await smpInfo(); } catch (e) { /* shown by the next action */ }
|
||
smpBusy = false;
|
||
busy--;
|
||
renderSamples();
|
||
}
|
||
return done;
|
||
}
|
||
|
||
async function smpErase(k) {
|
||
if (!dev || !confirm(t("confirmErase").replace("{n}", k + 1))) return;
|
||
busy++;
|
||
smpBusy = true;
|
||
renderSamples();
|
||
try {
|
||
const r = parse[CMD.SMP_ERASE](await rq(req.smpErase(k), { timeout: 2500, retries: 0 }));
|
||
if (r.rc) throw new Error("erase rc " + r.rc);
|
||
sayK("smpErased", String(k + 1));
|
||
} catch (e) {
|
||
if (e.message !== "closed") sayK("smpFail", e.message);
|
||
} finally {
|
||
try { if (dev) await smpInfo(); } catch (e) { /* ignore */ }
|
||
smpBusy = false;
|
||
busy--;
|
||
renderSamples();
|
||
}
|
||
}
|
||
|
||
/* ---------------------------------------------------------------- CHOP --- */
|
||
/* Load a recording, mark the chops (live: TAP / space while it plays, each tap moved to the hit it
|
||
meant; or by hits, a tempo grid, equal parts; double-click adds, drag moves, Delete removes),
|
||
audition them (click, keys 1-9 0), then one chop per key into USR1..3 or as WAV files. */
|
||
const CH = { x: null, nov: null, name: "", marks: [], sel: -1, v0: 0, v1: 1, ctx: null, src: null, t0: 0, raf: 0,
|
||
drag: -1, key0: 60, mode: 0, maxLen: 0, ui: null };
|
||
const chR = () => SMP.RATE;
|
||
const chSecs = (n) => (n / SMP.RATE).toFixed(2) + " s";
|
||
|
||
function chopChops() { return CH.x ? chopList(CH.marks, CH.x.length, Math.round(CH.maxLen * SMP.RATE)) : []; }
|
||
function chopUsed() { /* the chops the slot gets, and their samples */
|
||
const c = chopChops(), use = CH.mode === 1 ? (c[CH.sel] ? [c[CH.sel]] : c.slice(0, 1)) : c.slice(0, CHOP.MAX);
|
||
return { all: c, use, n: use.reduce((a, q) => a + (q.end - q.start), 0) };
|
||
}
|
||
|
||
async function chopDecode(buf) { /* any file the browser decodes -> mono Float64 at SMP.RATE */
|
||
try { const w = parseWav(buf); return resample(w.x, w.sr, SMP.RATE); } catch (e) { /* not a plain WAV */ }
|
||
const Ctx = window.OfflineAudioContext || window.webkitOfflineAudioContext;
|
||
const ab = await new Ctx(1, 1, SMP.RATE).decodeAudioData(buf.slice(0));
|
||
const x = new Float64Array(ab.length);
|
||
for (let c = 0; c < ab.numberOfChannels; c++) { const d = ab.getChannelData(c); for (let i = 0; i < d.length; i++) x[i] += d[i] / ab.numberOfChannels; }
|
||
return x;
|
||
}
|
||
|
||
async function chopLoad(f) {
|
||
chopStop();
|
||
try {
|
||
const x = await chopDecode(await f.arrayBuffer());
|
||
if (!x.length) throw new Error("no audio");
|
||
CH.x = x;
|
||
CH.nov = chopNovelty(x);
|
||
CH.name = f.name.replace(/\.[^.]*$/, "").toUpperCase().replace(/[^A-Z0-9]/g, "").slice(0, 8) || "CHOP";
|
||
CH.marks = [];
|
||
CH.sel = -1;
|
||
CH.v0 = 0;
|
||
CH.v1 = x.length;
|
||
sayK("chopLoaded", `${f.name} (${chSecs(x.length)})`);
|
||
} catch (e) { sayK("smpDecodeFail", `${f.name} (${e.message})`); }
|
||
chopRender();
|
||
}
|
||
|
||
function chopSetMarks(m) {
|
||
CH.marks = [...new Set(m.map((v) => Math.max(0, Math.min(CH.x.length - 1, Math.round(v)))))].sort((a, b) => a - b);
|
||
if (CH.sel >= CH.marks.length) CH.sel = CH.marks.length - 1;
|
||
chopRender();
|
||
}
|
||
function chopAdd(pos) { /* a new marker; one within 30 ms is moved there instead */
|
||
const near = CH.marks.findIndex((m) => Math.abs(m - pos) < 0.03 * chR());
|
||
const m = CH.marks.slice();
|
||
if (near >= 0) m[near] = pos; else m.push(pos);
|
||
chopSetMarks(m);
|
||
CH.sel = CH.marks.indexOf(Math.round(pos));
|
||
chopDraw();
|
||
}
|
||
|
||
/* ---- audio */
|
||
function chopCtx() {
|
||
if (!CH.ctx) CH.ctx = new (window.AudioContext || window.webkitAudioContext)();
|
||
if (CH.ctx.state === "suspended") CH.ctx.resume();
|
||
return CH.ctx;
|
||
}
|
||
function chopBuffer(a, b) {
|
||
const ctx = chopCtx(), n = Math.max(1, b - a), buf = ctx.createBuffer(1, n, SMP.RATE), d = buf.getChannelData(0);
|
||
for (let i = 0; i < n; i++) d[i] = CH.x[a + i];
|
||
return buf;
|
||
}
|
||
function chopStop() {
|
||
if (CH.src) { try { CH.src.stop(); } catch (e) { /* ended */ } CH.src = null; }
|
||
cancelAnimationFrame(CH.raf);
|
||
if (CH.ui) { CH.ui.play.textContent = t("chopPlay"); chopDraw(); }
|
||
}
|
||
/* play a..b; whole = the transport (a playhead, TAP marks), else an audition */
|
||
function chopPlay(a, b, whole) {
|
||
if (!CH.x) return;
|
||
chopStop();
|
||
const ctx = chopCtx(), src = ctx.createBufferSource();
|
||
const g = ctx.createGain();
|
||
src.buffer = chopBuffer(a, b);
|
||
src.connect(g).connect(ctx.destination);
|
||
if (!whole) { /* the fades the slot will have */
|
||
const n = b - a, fo = Math.min(CHOP.FADE_OUT, n >> 2) / SMP.RATE, now = ctx.currentTime + 0.005, end = now + n / SMP.RATE;
|
||
g.gain.setValueAtTime(1, now);
|
||
g.gain.setValueAtTime(1, Math.max(now, end - fo));
|
||
g.gain.linearRampToValueAtTime(0, end);
|
||
}
|
||
CH.t0 = ctx.currentTime + 0.005 - a / SMP.RATE;
|
||
src.start(ctx.currentTime + 0.005);
|
||
src.onended = () => { if (CH.src === src) { CH.src = null; if (whole) chopStop(); } };
|
||
CH.src = src;
|
||
CH.src.whole = whole;
|
||
if (whole) {
|
||
CH.ui.play.textContent = t("chopStop");
|
||
const tick = () => { chopDraw(); if (CH.src === src) CH.raf = requestAnimationFrame(tick); };
|
||
CH.raf = requestAnimationFrame(tick);
|
||
}
|
||
}
|
||
/* where the listener is now, in samples (what comes out of the speakers, not what is computed) */
|
||
function chopHeard(ev) {
|
||
const ctx = CH.ctx;
|
||
let ct = ctx.currentTime - (ctx.outputLatency || ctx.baseLatency || 0);
|
||
if (ev && ctx.getOutputTimestamp) {
|
||
const ts = ctx.getOutputTimestamp();
|
||
if (ts.performanceTime > 0) ct = ts.contextTime + (ev.timeStamp - ts.performanceTime) / 1000;
|
||
}
|
||
return (ct - CH.t0) * SMP.RATE;
|
||
}
|
||
function chopTap(ev) { /* TAP while it plays: a marker on the hit you meant */
|
||
if (!CH.src || !CH.src.whole) return;
|
||
const p = chopHeard(ev);
|
||
if (p < 0 || p >= CH.x.length) return;
|
||
chopAdd(CH.ui.snap.checked ? chopSnap(CH.x, CH.nov, p) : Math.round(p));
|
||
}
|
||
function chopAudition(i) {
|
||
const c = chopChops()[i];
|
||
if (!c) return;
|
||
CH.sel = i;
|
||
chopPlay(c.start, c.end, false);
|
||
chopRender();
|
||
}
|
||
|
||
/* ---- drawing (the page's own two colours) */
|
||
function chopDraw() {
|
||
const u = CH.ui;
|
||
if (!u) return;
|
||
const cv = u.cv, dpr = window.devicePixelRatio || 1, W = Math.max(200, cv.clientWidth), Hh = 150;
|
||
if (cv.width !== Math.round(W * dpr)) { cv.width = Math.round(W * dpr); cv.height = Math.round(Hh * dpr); }
|
||
const g = cv.getContext("2d"), cs = getComputedStyle(document.documentElement);
|
||
const FG = cs.getPropertyValue("--fg").trim(), DIM = cs.getPropertyValue("--dim").trim(), LINE = cs.getPropertyValue("--line").trim();
|
||
g.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||
g.clearRect(0, 0, W, Hh);
|
||
if (!CH.x) { g.fillStyle = DIM; g.font = "12px sans-serif"; g.fillText(t("chopDrop"), 8, Hh / 2); return; }
|
||
const x = CH.x, v0 = CH.v0, span = CH.v1 - CH.v0, X = (p) => (p - v0) / span * W, mid = Hh / 2 + 6;
|
||
const { all: chops, use } = chopUsed();
|
||
chops.forEach((c, i) => { /* the chops: the selected one filled, unused ones hatched */
|
||
const a = X(c.start), b = X(c.end);
|
||
if (b < 0 || a > W) return;
|
||
if (i === CH.sel) { g.fillStyle = LINE; g.fillRect(a, 12, b - a, Hh - 12); }
|
||
if (!use.includes(c)) { g.strokeStyle = LINE; for (let q = Math.floor(a / 8) * 8; q < b; q += 8) { g.beginPath(); g.moveTo(q, Hh); g.lineTo(q + 8, 12); g.stroke(); } }
|
||
});
|
||
g.fillStyle = FG;
|
||
for (let px = 0; px < W; px++) { /* the wave: min / max per pixel */
|
||
const a = Math.floor(v0 + px / W * span), b = Math.min(x.length, Math.max(a + 1, Math.floor(v0 + (px + 1) / W * span)));
|
||
let lo = 0, hi = 0;
|
||
for (let i = a; i < b; i += Math.max(1, (b - a) >> 6)) { if (x[i] < lo) lo = x[i]; if (x[i] > hi) hi = x[i]; }
|
||
g.fillRect(px, mid - hi * (Hh / 2 - 8), 1, Math.max(1, (hi - lo) * (Hh / 2 - 8)));
|
||
}
|
||
g.font = "10px sans-serif";
|
||
CH.marks.forEach((m, i) => { /* the markers, numbered; the chop's key above */
|
||
const px = X(m);
|
||
if (px < -1 || px > W + 1) return;
|
||
g.fillStyle = FG;
|
||
g.fillRect(Math.round(px), 0, i === CH.sel ? 2 : 1, Hh);
|
||
const key = CH.mode === 1 ? "" : (i < CHOP.MAX ? " " + noteName(Math.min(127, CH.key0 + i)) : "");
|
||
g.fillText(String(i + 1) + key, px + 3, 10);
|
||
});
|
||
if (CH.src && CH.src.whole && CH.ctx) { /* the playhead, as heard */
|
||
const p = X(chopHeard());
|
||
g.fillStyle = DIM;
|
||
g.fillRect(Math.round(p), 12, 1, Hh - 12);
|
||
}
|
||
}
|
||
|
||
/* ---- the block */
|
||
function chopUI() {
|
||
const box = $("chop");
|
||
if (!box || CH.ui) return;
|
||
const u = CH.ui = {};
|
||
const file = el("input", { type: "file", accept: "audio/*,.wav,.mp3,.aif,.aiff,.flac,.ogg,.m4a", hidden: true });
|
||
file.addEventListener("change", () => { if (file.files[0]) chopLoad(file.files[0]); file.value = ""; });
|
||
u.info = el("span", { class: "dim" });
|
||
u.cv = el("canvas", { class: "wave", tabindex: "0", title: t("chopHint") });
|
||
u.play = el("button", { onclick: () => { if (CH.src && CH.src.whole) chopStop(); else if (CH.x) chopPlay(Math.round(CH.v0), CH.x.length, true); } }, t("chopPlay"));
|
||
u.tap = el("button", { class: "tap", onpointerdown: (e) => { e.preventDefault(); chopTap(e); } }, t("chopTap"));
|
||
u.snap = el("input", { type: "checkbox", checked: true });
|
||
u.sens = el("input", { type: "range", min: 1, max: 10, value: 5, title: t("chopSens") });
|
||
u.bpm = el("input", { type: "number", min: 40, max: 240, step: 0.1, value: 90, class: "num" });
|
||
u.div = el("select", {}, ...[["1 bar", 4], ["1/2", 2], ["1/4", 1], ["1/8", 0.5], ["1/16", 0.25]].map(([n, v]) => el("option", { value: v, text: n })));
|
||
u.div.value = "1";
|
||
u.n = el("select", {}, ...[2, 3, 4, 6, 8, 12, 16].map((n) => el("option", { value: n, text: String(n) })));
|
||
u.n.value = "8";
|
||
u.key = el("select", {}, ...Array.from({ length: 49 }, (_, i) => 36 + i).map((n) => el("option", { value: n, text: noteName(n) })));
|
||
u.key.value = String(CH.key0);
|
||
u.mode = el("select", {}, el("option", { value: 0, text: t("chopModeKeys") }), el("option", { value: 1, text: t("chopModeOne") }));
|
||
u.max = el("select", {}, ...[["—", 0], ["0.25 s", 0.25], ["0.5 s", 0.5], ["1 s", 1], ["2 s", 2]].map(([n, v]) => el("option", { value: v, text: n })));
|
||
u.meter = el("progress", { max: SMP.MAX_DATA * 2, value: 0 });
|
||
u.room = el("span", { class: "dim" });
|
||
u.list = el("div", { class: "chops" });
|
||
u.send = [0, 1, 2].map((k) => el("button", { ic: "symbol_upload", onclick: () => chopSend(k) }, `USR${k + 1}`));
|
||
const region = () => { /* first..last marker when there are two, else all */
|
||
const m = CH.marks;
|
||
return m.length >= 2 ? [m[0], m[m.length - 1]] : [m[0] || 0, CH.x.length];
|
||
};
|
||
u.key.addEventListener("change", () => { CH.key0 = +u.key.value; chopRender(); });
|
||
u.mode.addEventListener("change", () => { CH.mode = +u.mode.value; chopRender(); });
|
||
u.max.addEventListener("change", () => { CH.maxLen = +u.max.value; chopRender(); });
|
||
box.append(
|
||
el("div", { class: "head" }, el("b", { text: "CHOP" }),
|
||
el("button", { ic: "symbol_folder_open", onclick: () => file.click() }, t("chopOpen")), file, u.info),
|
||
u.cv,
|
||
el("div", { class: "head" }, u.play, u.tap, el("label", {}, u.snap, " " + t("chopSnap")),
|
||
el("button", { onclick: () => { if (CH.x) chopSetMarks([]); } }, t("chopClear")),
|
||
el("span", { class: "dim", text: t("chopHint") })),
|
||
el("div", { class: "head" },
|
||
el("button", { onclick: () => { if (CH.x) chopSetMarks(chopHits(CH.x, CH.nov, +u.sens.value)); } }, t("chopHits")), u.sens,
|
||
el("span", { class: "sep" }),
|
||
el("button", { onclick: () => { if (CH.x) { const [a, b] = region(); chopSetMarks(chopGrid(a, b, Math.max(40, +u.bpm.value || 90), +u.div.value)); } } }, t("chopGrid")),
|
||
u.bpm, el("span", { text: "BPM" }), u.div,
|
||
el("span", { class: "sep" }),
|
||
el("button", { onclick: () => { if (CH.x) { const [a, b] = region(); chopSetMarks(chopEqual(a, b, +u.n.value)); } } }, t("chopEqual")), u.n),
|
||
el("div", { class: "head" }, el("span", { text: t("chopKey") }), u.key, u.mode,
|
||
el("span", { text: t("chopMax") }), u.max, u.meter, u.room),
|
||
el("div", { class: "head" }, el("span", { text: t("chopTo") }), ...u.send,
|
||
el("button", { ic: "symbol_download", onclick: chopZip }, t("chopZip"))),
|
||
u.list);
|
||
/* the wave: click = select + listen, double-click = a marker, drag a marker, wheel = zoom */
|
||
const posAt = (e) => { const r = u.cv.getBoundingClientRect(); return CH.v0 + (e.clientX - r.left) / r.width * (CH.v1 - CH.v0); };
|
||
const markAt = (e) => {
|
||
const r = u.cv.getBoundingClientRect(), per = (CH.v1 - CH.v0) / r.width;
|
||
return CH.marks.findIndex((m) => Math.abs(m - posAt(e)) < 5 * per);
|
||
};
|
||
u.cv.addEventListener("pointerdown", (e) => {
|
||
if (!CH.x) { file.click(); return; }
|
||
u.cv.focus();
|
||
const k = markAt(e);
|
||
if (k >= 0) { CH.drag = k; CH.sel = k; u.cv.setPointerCapture(e.pointerId); chopDraw(); return; }
|
||
const p = posAt(e), i = chopChops().findIndex((c) => p >= c.start && p < c.end);
|
||
if (i >= 0) chopAudition(i);
|
||
});
|
||
u.cv.addEventListener("pointermove", (e) => {
|
||
if (CH.drag < 0) { u.cv.style.cursor = CH.x && markAt(e) >= 0 ? "ew-resize" : "default"; return; }
|
||
const m = CH.marks, k = CH.drag, lo = k ? m[k - 1] + 1 : 0, hi = k + 1 < m.length ? m[k + 1] - 1 : CH.x.length - 1;
|
||
m[k] = Math.round(Math.max(lo, Math.min(hi, posAt(e))));
|
||
chopDraw();
|
||
});
|
||
u.cv.addEventListener("pointerup", () => { if (CH.drag >= 0) { CH.drag = -1; chopRender(); } });
|
||
u.cv.addEventListener("dblclick", (e) => { if (CH.x) chopAdd(u.snap.checked ? chopSnap(CH.x, CH.nov, posAt(e), 0.02) : Math.round(posAt(e))); });
|
||
u.cv.addEventListener("wheel", (e) => {
|
||
if (!CH.x) return;
|
||
e.preventDefault();
|
||
const n = CH.x.length, span = CH.v1 - CH.v0;
|
||
if (e.shiftKey || Math.abs(e.deltaX) > Math.abs(e.deltaY)) {
|
||
const d = (e.deltaX || e.deltaY) / 400 * span, v0 = Math.max(0, Math.min(n - span, CH.v0 + d));
|
||
CH.v0 = v0; CH.v1 = v0 + span;
|
||
} else {
|
||
const p = posAt(e), z = Math.exp(e.deltaY / 300), ns = Math.max(SMP.RATE * 0.05, Math.min(n, span * z));
|
||
CH.v0 = Math.max(0, Math.min(n - ns, p - (p - CH.v0) / span * ns));
|
||
CH.v1 = CH.v0 + ns;
|
||
}
|
||
chopDraw();
|
||
}, { passive: false });
|
||
u.cv.addEventListener("keydown", (e) => {
|
||
if (!CH.x) return;
|
||
const k = e.key;
|
||
if (k === " ") { e.preventDefault(); if (CH.src && CH.src.whole) chopTap(e); else chopPlay(Math.round(CH.v0), CH.x.length, true); }
|
||
else if (k === "Enter" || k === "Escape") { e.preventDefault(); if (CH.src) chopStop(); else chopPlay(Math.round(CH.v0), CH.x.length, true); }
|
||
else if (/^[0-9]$/.test(k)) { e.preventDefault(); chopAudition(k === "0" ? 9 : +k - 1); }
|
||
else if ((k === "Delete" || k === "Backspace") && CH.sel >= 0) { e.preventDefault(); chopSetMarks(CH.marks.filter((_, i) => i !== CH.sel)); }
|
||
else if ((k === "ArrowLeft" || k === "ArrowRight") && CH.sel >= 0) { /* nudge the selected marker: 2 ms, shift 20 ms */
|
||
e.preventDefault();
|
||
const m = CH.marks.slice();
|
||
m[CH.sel] += (k === "ArrowLeft" ? -1 : 1) * Math.round((e.shiftKey ? 0.02 : 0.002) * SMP.RATE);
|
||
const keep = CH.sel;
|
||
chopSetMarks(m);
|
||
CH.sel = keep;
|
||
chopRender();
|
||
}
|
||
});
|
||
box.addEventListener("dragover", (e) => { e.preventDefault(); box.classList.add("over"); });
|
||
box.addEventListener("dragleave", () => box.classList.remove("over"));
|
||
box.addEventListener("drop", (e) => { e.preventDefault(); box.classList.remove("over"); if (e.dataTransfer.files[0]) chopLoad(e.dataTransfer.files[0]); });
|
||
window.addEventListener("resize", () => chopDraw());
|
||
chopRender();
|
||
}
|
||
|
||
function chopRender() {
|
||
const u = CH.ui;
|
||
if (!u) return;
|
||
const { all, use, n } = chopUsed(), room = SMP.MAX_DATA * 2, over = n > room;
|
||
u.info.textContent = CH.x ? `${CH.name} · ${chSecs(CH.x.length)} · ${all.length} ${t("chopChops")}` : t("chopHelp");
|
||
u.meter.value = Math.min(room, n);
|
||
u.room.textContent = `${chSecs(n)} / ${chSecs(room)}` + (over ? " " + t("chopTooLong") : "") +
|
||
(CH.mode === 0 && all.length > CHOP.MAX ? " " + t("chopTooMany") : "");
|
||
u.room.className = over ? "bad" : "dim";
|
||
u.send.forEach((b) => { b.disabled = !use.length || over || smpBusy || !dev || !dev.smp; });
|
||
u.list.replaceChildren(...all.map((c, i) => el("button", {
|
||
class: "chip" + (i === CH.sel ? " on" : "") + (use.includes(c) ? "" : " off"),
|
||
title: `${chSecs(c.start)} · ${chSecs(c.end - c.start)}`, onclick: () => chopAudition(i),
|
||
}, `${i + 1}` + (CH.mode === 1 ? "" : i < CHOP.MAX ? " " + noteName(Math.min(127, CH.key0 + i)) : ""))));
|
||
chopDraw();
|
||
}
|
||
|
||
/* the chops into slot k's list (it shows below), then the usual upload */
|
||
async function chopSend(k) {
|
||
if (!CH.x || smpBusy) return;
|
||
const { use } = chopUsed();
|
||
if (!use.length) return;
|
||
const zones = chopZones(CH.x, chopChops(), CH.key0, CH.mode, Math.max(0, CH.sel));
|
||
smpDraft[k].name = CH.name;
|
||
smpDraft[k].files = zones;
|
||
renderSamples();
|
||
if (await smpUpload(k)) sayK("chopSent", `USR${k + 1}: ${zones.length} ${t("chopChops")}, ${noteName(zones[0].lo === 0 ? zones[0].root : zones[0].lo)}…`);
|
||
}
|
||
|
||
function chopZip() {
|
||
if (!CH.x) return;
|
||
const zones = chopZones(CH.x, chopChops(), CH.key0, CH.mode, Math.max(0, CH.sel));
|
||
if (!zones.length) return;
|
||
const blob = new Blob([zipStore(zones.map((z) => ({ name: `${CH.name}/${z.fname}`, data: wavFile(z.s) })))], { type: "application/zip" });
|
||
const a = el("a", { href: URL.createObjectURL(blob), download: `${CH.name}-chops.zip` });
|
||
document.body.append(a);
|
||
a.click();
|
||
a.remove();
|
||
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
|
||
}
|
||
|
||
/* ---------------------------------------------------------- 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))));
|
||
const drumTrack = (i) => !!dev && !!dev.mix && i === dev.mix.ntrk - 1;
|
||
function trackName(x) {
|
||
if (x.engine >= dev.info.nengines) return ["DRUMS", (dev.kitNames || [])[x.e0]].filter(Boolean).join(" ");
|
||
return [dev.info.engines[x.engine], (dev.names[x.engine] || [])[x.preset]].filter(Boolean).join(" ");
|
||
}
|
||
|
||
async function readMixer() {
|
||
const d = dev;
|
||
if (!d || !hasTracks()) return;
|
||
const m = await mixer.read(rq, 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 (and the drum level, a global) -> the strips */
|
||
function mixFromDump() {
|
||
if (!dev || !dev.mix || !dev.dump || panning) return;
|
||
const m = dev.mix, ds = m.ntrk - 1, x = m.tracks[dev.sel];
|
||
if (!mixTouched("lv", ds)) m.tracks[ds].level = dev.dump.g[gDrLvl()];
|
||
if (x) {
|
||
if (!mixTouched("lv", dev.sel)) {
|
||
if (dev.sel !== ds) 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 (selected track; the drum level always) */
|
||
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 (drumTrack(i)) put(1, gDrLvl(), x.level);
|
||
if (i !== dev.sel) return;
|
||
if (!drumTrack(i)) 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 drum = drumTrack(i);
|
||
const lvDesc = (drum ? dev.gdesc[gDrLvl()] : 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")),
|
||
solo: el("span", { class: "solo", text: t("solo") }),
|
||
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, c.solo, 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.solo.classList.toggle("on", !!((dev.mix.solo >> i) & 1)); /* v5: soloed on the device (GLO + key) */
|
||
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 */
|
||
busy++;
|
||
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; busy--; }
|
||
} catch (e) { report(e); } finally { panOther.run = false; panWant.clear(); }
|
||
}
|
||
|
||
/* ------------------------------------------------- live sync / polling --- */
|
||
/* With WATCH (protocol v2) the device pushes CHANGED / RELOAD / STEP_CHANGED; the editor PINGs about
|
||
once a second so the watch stays on (it ends 3 s after the last request), and DUMPs every 5 s as a
|
||
safety net. Older firmware: DUMP every 400 ms and two steps per round. */
|
||
function onPush(f) {
|
||
const d = dev;
|
||
if (!d || !d.dump || !d.info) return;
|
||
try {
|
||
if (f.cmd === CMD.CHANGED) {
|
||
const c = parse[CMD.CHANGED](f.a);
|
||
if (panning && !c.scope) return; /* about the track selected for a moment, not ours */
|
||
const arr = c.scope ? d.dump.g : d.dump.p;
|
||
if (c.id >= arr.length) return;
|
||
const k = key(c.scope, c.id);
|
||
if (touched(k)) return; /* the user's value wins; their SET follows */
|
||
const old = arr[c.id];
|
||
arr[c.id] = c.value;
|
||
showValue(k, c.value, false);
|
||
blink(k);
|
||
mixFromDump();
|
||
if (!c.scope && c.id === pSlen() && old !== c.value) { $("steptables").dataset.len = ""; renderSteps(); }
|
||
if (!c.scope && c.id === d.info.pe0 && drumGrid() && d.dstepsOk) renderDrumBar(); /* the kit, changed on the device */
|
||
} 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 && !drumTrack(c.track)) { 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 {
|
||
if (drumGrid() && d.dstepsOk) {
|
||
const r = parse[CMD.DRUM_STEP](await rq(req.drumStep(i), { key: "dstep:" + i }));
|
||
if (d !== dev || r.index !== i || !drumGrid()) return;
|
||
d.dsteps[i] = r;
|
||
d.steps[i] = drumAsStep(r);
|
||
renderDrums();
|
||
return;
|
||
}
|
||
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;
|
||
busy++;
|
||
try { await fn(); } catch (err) { report(err); } finally { busy--; }
|
||
}
|
||
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) => d.link.request(r, o));
|
||
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;
|
||
busy++;
|
||
const d = dev;
|
||
try {
|
||
const dump = await getDump();
|
||
if (d !== dev) return;
|
||
const soundChanged = dump.engine !== d.dump.engine || dump.preset !== d.dump.preset;
|
||
const engineChanged = dump.engine !== d.dump.engine;
|
||
const oldLen = d.dump.p[pSlen()];
|
||
for (const [k, c] of ctl) {
|
||
const v = c.scope ? dump.g[c.id] : dump.p[c.id];
|
||
if (touched(k)) { (c.scope ? dump.g : dump.p)[c.id] = c.scope ? d.dump.g[c.id] : d.dump.p[c.id]; continue; }
|
||
showValue(k, v, false);
|
||
}
|
||
d.dump = dump;
|
||
if (engineChanged) await rereadEngineDesc();
|
||
if (hasTracks()) await readMixer(); /* the strips (other tracks push nothing) */
|
||
if (soundChanged) { updateBrowser(); await 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;
|
||
if (drumGrid() && d.dstepsOk) {
|
||
const r = await getDrumStep(stepRR), o = d.dsteps[stepRR];
|
||
d.dsteps[stepRR] = r;
|
||
d.steps[stepRR] = drumAsStep(r);
|
||
if (JSON.stringify(o) !== JSON.stringify(r)) renderDrums();
|
||
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 { busy--; }
|
||
}, 400);
|
||
|
||
/* ------------------------------------------------------------ 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;
|
||
let data;
|
||
try {
|
||
data = JSON.parse(await f.text());
|
||
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) { sayK("badfile", e.message); return; }
|
||
busy++;
|
||
try {
|
||
selfLoad();
|
||
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 { busy--; }
|
||
});
|
||
|
||
/* ----------------------------------------------------------- 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 */
|
||
async function libAdopt(d) {
|
||
const keys = d.keys, engines = d.info.engines, changed = [];
|
||
if ((libMeta.keys && !sameKeys(libMeta.keys, keys)) || (libMeta.engines && !sameKeys(libMeta.engines, engines))) {
|
||
for (const p of lib) {
|
||
const name = p.engineName || (libMeta.engines || [])[p.engine];
|
||
const e = name ? engines.indexOf(name) : p.engine;
|
||
p.p = remapParams(p.p, libMeta.keys, keys);
|
||
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;
|
||
}
|
||
|
||
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) => (a.engineName || "").localeCompare(b.engineName || "") || a.name.localeCompare(b.name),
|
||
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 engs = [...new Set([...(dev ? dev.info.engines : libMeta.engines || []), ...lib.map((p) => p.engineName).filter(Boolean)])];
|
||
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 ? 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 ? dev.info.engines[x.engine] || String(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;
|
||
libBusy = true;
|
||
busy++;
|
||
renderLib(); renderBank();
|
||
try { await fn(); } catch (err) { report(err); } finally { busy--; libBusy = false; renderLib(); renderBank(); }
|
||
}
|
||
const rqf = (r, o) => rq(r, o);
|
||
const checkRc = (rc) => { if (rc) throw new Error(t("flashFail").replace("{rc}", rc)); };
|
||
async function refreshSlot(slot) {
|
||
const r = parse[CMD.UP_LIST](await rq(req.upList(slot, 1)));
|
||
if (dev && dev.bank && r.slots[0]) dev.bank.slots[slot] = r.slots[0];
|
||
}
|
||
|
||
function libAudition(id) {
|
||
const p = lib.find((x) => x.id === id);
|
||
if (!p || !dev || libBusy) return;
|
||
if (isDrum()) { sayK("drumNoSound"); return; }
|
||
libOp(async () => {
|
||
if (!engineOk(p)) throw new Error(t("badEngine") + (p.engineName || p.engine));
|
||
sayK("auditioning", p.name);
|
||
selfLoad();
|
||
const r = await auditionPatch(rqf, dev.info, p, { gEng: gEng(),
|
||
progress: (i, n) => { if (i % 8 === 0) sayK("auditioning", `${p.name} ${i}/${n}`); } });
|
||
await afterSoundChange();
|
||
sayK(r.wrote ? "auditionedPat" : "auditioned", p.name);
|
||
});
|
||
}
|
||
$("libaud").addEventListener("click", () => libAudition(libSel));
|
||
|
||
$("libsave").addEventListener("click", () => libOp(async () => {
|
||
if (isDrum()) { sayK("drumNoSound"); return; }
|
||
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, then DUMP + steps; its pattern only if it brought one (the device
|
||
loads a preset's pattern into an empty sequencer, or over one that is still an untouched preset pattern) */
|
||
$("factlib").addEventListener("click", () => libOp(async () => {
|
||
const e = dev.dump.engine, pi = $("preset").value === "" ? dev.dump.preset : +$("preset").value;
|
||
const name = (dev.names[e] || [])[pi] || "PRESET";
|
||
const before = dev.steps.length >= UP.PAT ? patternFromSteps(dev.steps) : null;
|
||
const wasEmpty = dev.steps.length && dev.steps.every((s) => !s || !s.n);
|
||
selfLoad();
|
||
await rq(req.preset(e, pi));
|
||
const { patch } = await capturePatch(rqf, dev.info, name);
|
||
const brought = wasEmpty || !before || JSON.stringify(before) !== JSON.stringify(patch.pattern || patternFromSteps([]));
|
||
if (!brought) patch.pattern = null;
|
||
patch.tags = ["factory"];
|
||
await libAdd([patch]);
|
||
await afterSoundChange();
|
||
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 () => {
|
||
checkRc(await bank.put(rqf, slot, { ...p, name: upName(p.name), p: fullParams(p) }));
|
||
await refreshSlot(slot);
|
||
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;
|
||
if (isDrum()) { sayK("drumNoSound"); return; }
|
||
const s = dev.bank.slots[slot];
|
||
libOp(async () => {
|
||
selfLoad();
|
||
const rc = await bank.load(rqf, slot);
|
||
if (rc) { sayK("emptySlot", slotName(slot)); return; }
|
||
await afterSoundChange();
|
||
sayK("loadedUser", `${slotName(slot)} ${s.name}`);
|
||
});
|
||
}
|
||
$("bkload").addEventListener("click", () => bankLoad(bankSel));
|
||
$("bkstore").addEventListener("click", () => {
|
||
const slot = bankSel;
|
||
if (!dev || !dev.bank || slot == null) return;
|
||
if (isDrum()) { sayK("drumNoSound"); 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 () => {
|
||
checkRc(await bank.store(rqf, slot, name.trim()));
|
||
await refreshSlot(slot);
|
||
sayK("storedSlot", `${slotName(slot)} ${dev.bank.slots[slot].name}`);
|
||
});
|
||
});
|
||
function bankGet(slot) {
|
||
if (!dev || !dev.bank || slot == null || libBusy) return;
|
||
libOp(async () => {
|
||
const u = await bank.get(rqf, dev.info, slot);
|
||
if (!u.used) { sayK("emptySlot", slotName(slot)); return; }
|
||
await libAdd([{ name: u.name, engine: u.engine, engineName: dev.info.engines[u.engine], p: u.p, pattern: u.pattern, tags: ["device"] }]);
|
||
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 () => {
|
||
checkRc(await bank.erase(rqf, slot));
|
||
await refreshSlot(slot);
|
||
sayK("erasedSlot", slotName(slot));
|
||
});
|
||
});
|
||
$("bkrefresh").addEventListener("click", () => libOp(async () => {
|
||
sayK("readingBank");
|
||
dev.bank = await bank.list(rqf);
|
||
sayK("ready");
|
||
}));
|
||
$("bkexport").addEventListener("click", () => libOp(async () => {
|
||
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, engineName: dev.info.engines[u.engine], p: u.p, pattern: u.pattern, slot: x.slot });
|
||
}
|
||
download(`felucca-bank-${today()}.json`, libraryFile("bank", out, libCtx()));
|
||
sayK("ready");
|
||
}));
|
||
|
||
$("connect").addEventListener("click", () => {
|
||
if (dev) { wantConnected = false; disconnect(); } else connect();
|
||
});
|
||
applyLang();
|
||
showTab(tab);
|
||
libInit();
|
||
if (!MOCK && !navigator.requestMIDIAccess) sayK("nomidi");
|
||
})();
|
||
</script>
|
||
</body>
|
||
</html>
|