mirror of
https://github.com/juanjiant-bit/JIANT.git
synced 2026-12-05 20:34:27 +01:00
A user (via JIANT Studio): "the sound editor used to show modules, for a few updates now it is a vertical list". knownLayout knew G_COUNT up to 73; the firmware has 77 since the OTT / GATE globals, so the editor fell back to the plain list. Now any G_COUNT from 73 up and any P_COUNT from 123 up with the engine block last (P_E0 = P_COUNT - 8) is known: the firmware appends, the ids the layout names stay. web/editor_layout_test.mjs compiles P_COUNT, G_COUNT, P_E0 from core.h of web/STABLE and web/PREVIEW and checks them (fails on the old editor:32099feandb983fbbboth 123 / 77 / 115); emulator.yml runs it before the site is deployed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KMHk6yH4XbP1xxHYKCo9Mh
7584 lines
496 KiB
HTML
7584 lines
496 KiB
HTML
<!doctype html>
|
||
<!-- SPDX-License-Identifier: GPL-3.0-only
|
||
Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments
|
||
Portions Copyright (C) 2026 Juan Ignacio Antonucci (Juan Jiant) -->
|
||
<!-- Felucca web editor. One file, no libraries. Protocol: EDITOR_PROTOCOL.md.
|
||
Add ?mock=1 to the URL to use a built-in simulated device. -->
|
||
<html lang="ja" data-skin="fm">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
<title>JIANT Editor</title>
|
||
<style>
|
||
/* Fukiai: Hügelton Instruments' icon font (MIT, FUKIAI-LICENSE.txt). Icons are text in .ic spans;
|
||
they stay hidden until the face has loaded (html.fk), so a missing font never shows boxes. */
|
||
@font-face { font-family: "Fukiai"; src: url("fukiai.ttf") format("truetype"); font-display: block; unicode-range: U+EA00-EB09; }
|
||
:root { --bg: #fff; --fg: #000; --dim: #777; --line: #ccc; }
|
||
@media (prefers-color-scheme: dark) {
|
||
:root:not([data-theme="light"]) { --bg: #000; --fg: #fff; --dim: #888; --line: #444; }
|
||
}
|
||
:root[data-theme="dark"] { --bg: #000; --fg: #fff; --dim: #888; --line: #444; }
|
||
html { color-scheme: light dark; }
|
||
body { margin: 0; background: var(--bg); color: var(--fg);
|
||
font: 13px/1.4 -apple-system, BlinkMacSystemFont, "Helvetica Neue", Arial, sans-serif;
|
||
font-variant-numeric: tabular-nums; }
|
||
main { max-width: 1100px; margin: 0 auto; padding: 16px; }
|
||
h1 { font-size: 18px; font-weight: 600; margin: 0 0 8px; }
|
||
h2 { font-size: 13px; font-weight: 600; margin: 0 0 4px; padding-bottom: 2px; border-bottom: 1px solid var(--fg); }
|
||
h3 { font-size: 11px; font-weight: 400; color: var(--dim); margin: 4px 0 0; }
|
||
a { color: inherit; }
|
||
.lang { float: right; font-size: 12px; color: var(--dim); text-decoration: underline; background: none; padding: 0; }
|
||
button { font: inherit; background: var(--fg); color: var(--bg); border: 0; padding: 2px 10px; cursor: pointer; }
|
||
button:disabled { opacity: .3; cursor: default; }
|
||
button.lang { color: var(--dim); background: none; }
|
||
select, input[type=text], input[type=number], input[type=search] {
|
||
font: inherit; color: var(--fg); background: var(--bg); border: 1px solid var(--line); padding: 1px 3px; border-radius: 0; }
|
||
input[type=range] { width: 100%; margin: 0; accent-color: var(--fg); }
|
||
input[type=checkbox] { accent-color: var(--fg); margin: 0; }
|
||
.bar { display: flex; flex-wrap: wrap; gap: 6px 12px; align-items: center; margin: 0 0 8px; }
|
||
.dim { color: var(--dim); }
|
||
#status { min-height: 1.4em; }
|
||
section { margin: 12px 0; }
|
||
.groups { columns: 250px; column-gap: 20px; }
|
||
.group { break-inside: avoid; margin: 0 0 12px; }
|
||
.row { display: grid; grid-template-columns: 46px 1fr 70px; gap: 6px; align-items: center; min-height: 22px; }
|
||
.row .v { text-align: right; white-space: nowrap; }
|
||
.row select { width: 100%; }
|
||
.browser { display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-start; }
|
||
.browser select[size] { min-width: 150px; }
|
||
.slots { display: grid; grid-template-columns: auto auto auto auto; gap: 3px 8px; align-items: center; justify-content: start; }
|
||
table { border-collapse: collapse; }
|
||
th { font-weight: 400; color: var(--dim); text-align: left; padding: 0 6px 2px 0; }
|
||
td { padding: 1px 6px 1px 0; }
|
||
td.i { color: var(--dim); text-align: right; }
|
||
#steps input[type=text] { width: 120px; }
|
||
#steps input[type=number] { width: 48px; }
|
||
#steps .bad { outline: 1px solid var(--fg); text-decoration: underline wavy; }
|
||
.fm6ops { overflow-x: auto; }
|
||
.fm6ops td, .fm6ops th { padding: 0 2px; }
|
||
input.fm6n { width: 3.2em; }
|
||
#steps tr.off td { color: var(--dim); }
|
||
.stepcols { columns: 470px; column-gap: 24px; }
|
||
.stepcols table { break-inside: avoid; }
|
||
@media (max-width: 600px) {
|
||
.stepcols { columns: auto; overflow-x: auto; }
|
||
#steps input[type=text] { width: 84px; }
|
||
#steps input[type=number] { width: 42px; }
|
||
#steps th, #steps td { padding-right: 3px; }
|
||
}
|
||
footer { margin-top: 24px; font-size: 11px; color: var(--dim); }
|
||
.row.pushed .v { font-weight: 600; }
|
||
.row.modrow { grid-template-columns: 16px 1fr 1fr 1fr 52px; }
|
||
/* librarian: local library and the device's user bank side by side, stacked on a phone */
|
||
.libcols { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 340px), 1fr)); gap: 8px 24px; margin-top: 6px; }
|
||
.libcols > div { min-width: 0; }
|
||
.libcols .bar input[type=search] { flex: 1 1 120px; min-width: 0; }
|
||
.list { height: 260px; overflow: auto; border: 1px solid var(--line); resize: vertical; }
|
||
.list table { width: 100%; table-layout: fixed; }
|
||
.list th { position: sticky; top: 0; background: var(--bg); padding: 1px 6px; }
|
||
.list td { padding: 1px 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||
.list tr[data-id], .list tr[data-slot] { cursor: pointer; }
|
||
.list tr.sel td { background: var(--fg); color: var(--bg); }
|
||
.list tr.empty td { color: var(--dim); }
|
||
.list tr.over td { outline: 1px dashed var(--fg); outline-offset: -1px; }
|
||
.list.over { outline: 1px solid var(--fg); }
|
||
.list .none { padding: 6px; color: var(--dim); }
|
||
.list col.n { width: 40px; } .list col.e { width: 72px; } .list col.d { width: 78px; }
|
||
.ic { font-family: "Fukiai"; font-style: normal; font-weight: 400; font-synthesis: none; line-height: 1; margin-right: .3em; }
|
||
html:not(.fk) .ic { display: none; }
|
||
/* wave choices: a page-drawn picker so the options can carry an icon (Chrome 135+); native menus get words only */
|
||
@supports (appearance: base-select) {
|
||
select.wave, select.wave::picker(select) { appearance: base-select; }
|
||
select.wave { padding: 1px 3px; min-block-size: 0; border: 1px solid var(--line); border-radius: 0; background: var(--bg); color: var(--fg); }
|
||
select.wave > button { font: inherit; background: none; color: inherit; padding: 0; text-align: start; }
|
||
select.wave::picker(select) { border: 1px solid var(--line); background: var(--bg); color: var(--fg); padding: 0; }
|
||
select.wave option { padding: 1px 6px; min-block-size: 0; }
|
||
select.wave option:checked { font-weight: 600; }
|
||
select.wave option:hover, select.wave option:focus-visible { background: var(--fg); color: var(--bg); }
|
||
select.wave option::checkmark { display: none; }
|
||
}
|
||
/* tabs: a wrapping row of plain buttons, the open one inverted; header stays at the top on wide screens */
|
||
.top { position: sticky; top: 0; z-index: 5; background: var(--bg); padding: 4px 0 0; }
|
||
@media (max-width: 600px) { .top { position: static; } }
|
||
.tabs { display: flex; flex-wrap: wrap; gap: 0; border-bottom: 1px solid var(--fg); margin: 6px 0 0; }
|
||
.tabs button { background: none; color: var(--dim); padding: 4px 10px; border: 1px solid transparent; border-bottom: 0; white-space: nowrap; }
|
||
.tabs button:hover { color: var(--fg); }
|
||
.tabs button[aria-selected="true"] { background: var(--fg); color: var(--bg); }
|
||
.trackbar { display: flex; flex-wrap: wrap; gap: 4px 8px; align-items: center; padding: 6px 0; border-bottom: 1px solid var(--line); }
|
||
.seg { display: inline-flex; flex-wrap: wrap; }
|
||
.seg button, button.tog { background: var(--bg); color: var(--fg); border: 1px solid var(--fg); padding: 1px 10px; }
|
||
.seg button + button { border-left: 0; }
|
||
.seg button[aria-pressed="true"], button.tog[aria-pressed="true"] { background: var(--fg); color: var(--bg); }
|
||
.panel { margin: 12px 0; }
|
||
.hint { margin: 16px 0; color: var(--dim); }
|
||
/* sequencer: a step grid over the selected track (16 per row, 8 on a phone) */
|
||
.grid { display: grid; grid-template-columns: repeat(16, minmax(0, 1fr)); gap: 2px; margin: 6px 0 12px; }
|
||
@media (max-width: 600px) { .grid { grid-template-columns: repeat(8, minmax(0, 1fr)); } }
|
||
.grid button { background: var(--bg); color: var(--fg); border: 1px solid var(--line); padding: 2px; min-width: 0; height: 52px;
|
||
display: flex; flex-direction: column; justify-content: flex-start; gap: 1px; text-align: left; overflow: hidden; font-size: 10px; line-height: 1.15; }
|
||
.grid button .n { color: var(--dim); }
|
||
.grid button .x { overflow: hidden; overflow-wrap: anywhere; flex: 1; }
|
||
.grid button.on { background: var(--fg); color: var(--bg); border-color: var(--fg); }
|
||
.grid button.on .n { color: inherit; opacity: .6; }
|
||
.grid button.acc .x { font-weight: 700; }
|
||
.grid button.tie { border-style: dashed; border-color: var(--fg); }
|
||
.grid button.beat { border-left-color: var(--fg); }
|
||
#steps tr.hl td { outline: 1px solid var(--fg); }
|
||
/* mixer: four channel strips as on the device's TRACKS page */
|
||
.mixer { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; max-width: 640px; margin: 6px 0; }
|
||
.strip { border: 1px solid var(--line); padding: 6px 4px; display: flex; flex-direction: column; align-items: center; gap: 6px; min-width: 0; }
|
||
.strip.sel { border-color: var(--fg); box-shadow: inset 0 0 0 1px var(--fg); }
|
||
.strip .num { font-size: 18px; font-weight: 600; line-height: 1; }
|
||
.strip .snd { font-size: 11px; line-height: 1.3; width: 100%; text-align: center; overflow-wrap: anywhere; min-height: 2.6em; }
|
||
.strip .rec { font-size: 11px; color: var(--dim); }
|
||
.strip .rec.on { color: var(--fg); font-weight: 600; }
|
||
.strip .rec:not(.on) .ic { visibility: hidden; }
|
||
.strip input.fader { writing-mode: vertical-lr; direction: rtl; width: 28px; height: 150px; }
|
||
.strip .v { font-size: 11px; white-space: nowrap; }
|
||
.strip .pan { width: 100%; }
|
||
.strip.muted .fader, .strip.muted .lv { opacity: .35; }
|
||
.strip button { width: 100%; padding: 1px 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||
.strip button.selb:disabled { opacity: 1; background: none; color: var(--dim); }
|
||
#sysinfo th { padding-right: 16px; }
|
||
/* the screen mirror: the page's colours around the picture, the picture as big as it fits (square), its pixels
|
||
sharp or smoothed */
|
||
.mirror { position: fixed; inset: 0; z-index: 100; display: flex; flex-direction: column; background: var(--bg); color: var(--fg);
|
||
padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left); }
|
||
.mirror-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; padding: 8px 16px; font-size: 13px; }
|
||
.mirror-bar #mirrorstat { color: var(--dim); flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||
.mirror-btns { display: flex; gap: 8px; margin-left: auto; }
|
||
.mirror-btns button { min-height: 36px; padding: 6px 12px; }
|
||
.mirror-btns button[aria-pressed="false"] { color: var(--dim); }
|
||
.mirror-stage { flex: 1; min-height: 0; display: flex; align-items: center; justify-content: center; padding: 0 8px 8px; }
|
||
.mirror canvas { display: block; width: 100%; height: 100%; object-fit: contain; image-rendering: crisp-edges;
|
||
image-rendering: pixelated; touch-action: manipulation; }
|
||
.mirror.smooth canvas { image-rendering: auto; }
|
||
.mirror:fullscreen .mirror-bar { opacity: 0.35; transition: opacity 0.3s; }
|
||
.mirror:fullscreen .mirror-bar:hover, .mirror:fullscreen .mirror-bar:focus-within { opacity: 1; }
|
||
body.mirroring { overflow: hidden; }
|
||
:root { --r0: #08080b; --r1: #262330; --r2: #f4f1ea; --r3: #aaa8a3; --r4: #1c1b20; --r5: #000; --r6: #fb7800; --r7: #050508; --r8: #bb72ff; --r9: #ff4a49; --r10: #7be0a8; } /* (the roll: the FM-1's JIANT palette, ui_palettes.h) */
|
||
/* the piano roll: the FM-1's screen colours (JIANT palette) whatever the page's skin; >= 40 px targets on a phone */
|
||
.rhud { display: grid; grid-template-columns: repeat(auto-fill, minmax(112px, 1fr)); gap: 6px; margin: 4px 0 8px; }
|
||
.rcard { position: relative; background: var(--r0); border: 1px solid var(--r1); border-radius: 8px; padding: 6px 8px 8px; touch-action: none;
|
||
user-select: none; font-family: "Chakra Petch", "IBM Plex Mono", monospace; text-transform: uppercase; color: var(--r2); }
|
||
.rcard .rl { display: block; font: 500 11px/1.2 "Chakra Petch", monospace; color: var(--r3); letter-spacing: .06em; }
|
||
.rcard .rv { display: block; font: 600 20px/1.15 "Inter Tight", "Instrument Sans", sans-serif; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||
.rcard .rb { display: block; height: 3px; background: var(--r4); border-radius: 2px; margin: 3px 0 4px; }
|
||
.rcard .rb i { display: block; height: 100%; border-radius: 2px; }
|
||
.rcard .rpm { display: flex; gap: 4px; }
|
||
#p-roll .rcard .rpm button, #p-roll .rtools button, #p-roll .rinsp button, #p-roll .rdet button { min-height: 40px; min-width: 40px; }
|
||
.rcard .rpm button { flex: 1; padding: 0; font-size: 18px; }
|
||
.rtools { gap: 6px; }
|
||
.rtools #rollstat { flex: 1 1 100%; font-family: "Chakra Petch", monospace; text-transform: uppercase; }
|
||
.rmain { display: grid; grid-template-columns: minmax(0, 1fr) 280px; gap: 10px; align-items: start; }
|
||
#rollcv { display: block; width: 100%; height: min(70vh, 640px); min-height: 340px; background: var(--r5); border-radius: 8px; touch-action: none; outline: none; }
|
||
#rollcv:focus-visible { box-shadow: 0 0 0 2px var(--r6); }
|
||
.rinsp { background: var(--r7); border: 1px solid var(--r1); border-radius: 8px; padding: 8px 10px; min-width: 0; color: var(--r2);
|
||
font: 13px/1.4 "Chakra Petch", "IBM Plex Mono", monospace; }
|
||
.rinsp h3 { margin: 6px 0 4px; font: 600 12px/1.2 "Chakra Petch", monospace; letter-spacing: .08em; color: var(--r8); text-transform: uppercase; }
|
||
.rinsp .rrow { display: grid; grid-template-columns: 58px 1fr auto auto; gap: 6px; align-items: center; min-height: 40px; }
|
||
.rinsp .rrow input[type=range] { min-height: 32px; }
|
||
.rinsp .rrow input[type=number] { width: 72px; }
|
||
.rinsp .rseg button { min-width: 44px; }
|
||
.rnotes { display: flex; flex-wrap: wrap; gap: 6px; margin: 6px 0; }
|
||
.rchip { display: inline-flex; align-items: center; gap: 2px; border: 2px solid var(--nc); border-radius: 8px; padding: 0 2px; }
|
||
.rchip b { color: var(--nc); min-width: 3em; text-align: center; font: 600 15px "Inter Tight", sans-serif; }
|
||
.rchip button { padding: 0 6px; }
|
||
.rk { font-size: 10px; padding: 2px 4px; border-radius: 4px; color: var(--r5); }
|
||
.rk.lock { background: var(--r6); } .rk.auto { background: var(--r8); }
|
||
.rmiss { font-size: 11px; }
|
||
.rdet { margin-top: 10px; }
|
||
.rdet summary { min-height: 40px; display: flex; align-items: center; cursor: pointer; font: 600 13px "Chakra Petch", monospace; letter-spacing: .1em; }
|
||
.reu { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 6px 16px; }
|
||
.reu label { display: grid; grid-template-columns: 70px 1fr 40px; align-items: center; gap: 6px; min-height: 40px; font: 500 12px "Chakra Petch", monospace; }
|
||
.reu label select { grid-column: 2 / 4; }
|
||
.rstrip { display: block; width: 100%; height: 140px; border-radius: 6px; touch-action: none; }
|
||
@media (max-width: 760px) { .rmain { grid-template-columns: 1fr; } }
|
||
/* MATH: the formula, its picture (the formula's samples as heat), the device's knobs */
|
||
#p-math button, #p-math select, #p-math input[type=range] { min-height: 40px; }
|
||
.mchaos { display: inline-flex; align-items: center; gap: 6px; } #mchaos { width: 140px; } #mchaosv { min-width: 2.2em; font: 600 14px "Inter Tight", sans-serif; }
|
||
#p-math .seg button { min-width: 52px; }
|
||
.mgrid { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 12px; align-items: start; }
|
||
#mf { width: 100%; box-sizing: border-box; font: 500 15px/1.45 "IBM Plex Mono", ui-monospace, monospace; resize: vertical; min-height: 96px; }
|
||
#mf[readonly] { opacity: .8; font-size: 12px; }
|
||
.merr { min-height: 1.4em; font: 12px/1.4 "IBM Plex Mono", monospace; margin: 4px 0; overflow-wrap: anywhere; }
|
||
.merr.bad { color: var(--r9); } .merr.ok { color: var(--r10); }
|
||
.mops { display: flex; flex-wrap: wrap; gap: 4px; }
|
||
#p-math .mops button { min-width: 40px; padding: 4px 8px; font: 500 13px "IBM Plex Mono", monospace; }
|
||
#mscope { width: 100%; aspect-ratio: 2 / 1; image-rendering: pixelated; border-radius: 6px; background: var(--r5); }
|
||
.mknobs { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 4px 16px; margin: 8px 0; }
|
||
.mk { display: grid; grid-template-columns: 66px 1fr 90px; gap: 6px; align-items: center; min-height: 40px; font: 500 12px "Chakra Petch", monospace; }
|
||
.mk b { font: 600 14px "Inter Tight", sans-serif; }
|
||
.mgram p { white-space: pre-line; font-size: 12px; }
|
||
@media (max-width: 760px) { .mgrid { grid-template-columns: 1fr; } }
|
||
[hidden] { display: none !important; }
|
||
</style>
|
||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Michroma&family=Chakra+Petch:wght@500;600&family=Inter+Tight:wght@600&family=IBM+Plex+Mono:wght@400;500;600&family=Instrument+Sans:wght@400;500;600&family=Noto+Sans+JP:wght@400;500&family=Silkscreen&family=VT323&display=swap">
|
||
<style id="jiant-brand">/*JIANT_UI*/</style>
|
||
<style id="jiant-skin">
|
||
/*SKIN-BEGIN*/
|
||
/* (studio) The editor in the firmware's own look, JIANT FM's or JIANT BYTE's (html[data-skin]; JIANT Studio sets it):
|
||
each parameter a card as the FM-1's screen draws one (its name small, its value big in the accent, a bar of how much),
|
||
the sections as the firmware's tabs, each track its colour; the same tokens and type as JIANT Studio. The same block in
|
||
both sites' editor.html; nothing of the page's markup or code changes for it (one script below: the bars' fill). */
|
||
:root[data-skin="fm"] {
|
||
--bg:#050409; --fg:#efe6c8; --dim:#a39bb6; --line:rgba(239,230,200,.16); --sk-panel:#0d0b14; --sk-field:#08070e;
|
||
--sk-accent:#c9a2ff; --sk-on:#050409; --sk-frame:#3fe0e6; --sk-ok:#7be0a8; --sk-warn:#ffc07a;
|
||
--sk-heat:linear-gradient(90deg,#3b6cff,#9d6bff 25%,#ff4a7a 50%,#ff8a1f 75%,#ffe14d);
|
||
--sk-k1:#ff9a4d; --sk-k2:#ff9a4d; --sk-k3:#ff9a4d; --sk-k4:#ff9a4d;
|
||
--sk-t1:#9d97ff; --sk-t2:#d39bff; --sk-t3:#ff9fd2; --sk-t4:#ff9a8a; --sk-t5:#ffc07a; --sk-t6:#fff3a8;
|
||
--sk-display:"Michroma","Arial Black",system-ui,sans-serif; --sk-body:"Instrument Sans","Noto Sans JP",system-ui,sans-serif;
|
||
--sk-mono:"IBM Plex Mono","Noto Sans JP",ui-monospace,monospace; --sk-value:"Instrument Sans",system-ui,sans-serif; --sk-value-size:22px;
|
||
--sk-r:12px; --sk-rs:8px; --sk-b:1px; color-scheme:dark;
|
||
}
|
||
:root[data-skin="byte"] {
|
||
--bg:#000; --fg:#f2f0f7; --dim:#9d94b8; --line:rgba(167,123,255,.32); --sk-panel:#0b0912; --sk-field:#05040a;
|
||
--sk-accent:#a77bff; --sk-on:#000; --sk-frame:#a77bff; --sk-ok:#6bff9e; --sk-warn:#ffb21a;
|
||
--sk-heat:linear-gradient(90deg,#ff3b3b,#ff7a1a 40%,#ffb21a 60%,#a77bff);
|
||
--sk-k1:#ff6fae; --sk-k2:#a77bff; --sk-k3:#ff7a1a; --sk-k4:#6bc8ff;
|
||
--sk-t1:#ff7a1a; --sk-t2:#a77bff; --sk-t3:#ff3b3b; --sk-t4:#6bc8ff; --sk-t5:#ffd23f; --sk-t6:#f2f0f7;
|
||
--sk-display:"Silkscreen","VT323",ui-monospace,monospace; --sk-body:"IBM Plex Mono","Noto Sans JP",ui-monospace,monospace;
|
||
--sk-mono:"IBM Plex Mono","Noto Sans JP",ui-monospace,monospace; --sk-value:"VT323",ui-monospace,monospace; --sk-value-size:25px;
|
||
--sk-r:3px; --sk-rs:2px; --sk-b:2px; color-scheme:dark;
|
||
}
|
||
:root[data-skin] body { background:var(--bg); color:var(--fg); font:14px/1.5 var(--sk-body); }
|
||
:root[data-skin="fm"] body { background:radial-gradient(1200px 500px at 70% -10%,#1b1030 0,transparent 60%),var(--bg); }
|
||
:root[data-skin="byte"] body { background:
|
||
radial-gradient(1px 1px at 12% 18%,#fff8,transparent),radial-gradient(1px 1px at 72% 12%,#fff6,transparent),
|
||
radial-gradient(1px 1px at 33% 64%,#fff5,transparent),radial-gradient(1px 1px at 86% 48%,#fff7,transparent),
|
||
radial-gradient(1px 1px at 52% 31%,#fff4,transparent),radial-gradient(1px 1px at 8% 82%,#fff6,transparent),#000;
|
||
background-size:340px 340px; }
|
||
:root[data-skin] main { max-width:1180px; padding:24px 16px 56px; }
|
||
:root[data-skin] a { color:inherit; }
|
||
/* the wordmark: JIANT and the firmware's word in its colours */
|
||
:root[data-skin] h1.jiant-wordmark { font:400 clamp(28px,5vw,44px)/1 var(--sk-display); letter-spacing:.02em; margin:0 0 6px; }
|
||
:root[data-skin] h1.jiant-wordmark a { text-decoration:none; }
|
||
:root[data-skin] h1.jiant-wordmark .fm { background:var(--sk-heat); -webkit-background-clip:text; background-clip:text; color:transparent; }
|
||
:root[data-skin] h1.jiant-wordmark .jiant-tool { font:500 11px/1 var(--sk-mono); letter-spacing:.16em; color:var(--sk-frame);
|
||
border:var(--sk-b) solid var(--line); border-radius:var(--sk-rs); padding:6px 8px; margin-left:12px; vertical-align:middle; }
|
||
/* the connection bar and the tabs: a panel, the firmware's tabs (the one shown filled) */
|
||
:root[data-skin] header.top { background:var(--sk-panel); border:var(--sk-b) solid var(--line); border-radius:var(--sk-r); padding:14px 14px 0; margin:14px 0 18px; }
|
||
:root[data-skin] nav.tabs { display:flex; flex-wrap:wrap; gap:6px; border:0; margin-top:12px; padding-bottom:12px; border-bottom:var(--sk-b) solid var(--line); }
|
||
:root[data-skin] nav.tabs button { font:500 11px/1 var(--sk-mono); letter-spacing:.08em; text-transform:uppercase; color:var(--dim);
|
||
background:var(--sk-field); border:var(--sk-b) solid var(--line); border-radius:var(--sk-rs); padding:10px 12px; min-height:38px; cursor:pointer; }
|
||
:root[data-skin="byte"] nav.tabs button { font:11px/1 var(--sk-display); }
|
||
:root[data-skin] nav.tabs button[aria-selected="true"] { background:var(--sk-accent); border-color:var(--sk-accent); color:var(--sk-on); }
|
||
:root[data-skin] nav.tabs button .ic { margin-right:6px; }
|
||
/* buttons, fields, lists */
|
||
:root[data-skin] button, :root[data-skin] select, :root[data-skin] input[type="text"], :root[data-skin] input[type="number"],
|
||
:root[data-skin] input:not([type]), :root[data-skin] textarea {
|
||
font:500 13px/1.3 var(--sk-mono); color:var(--fg); background:var(--sk-field); border:var(--sk-b) solid var(--line); border-radius:var(--sk-rs); }
|
||
:root[data-skin] button { padding:8px 12px; min-height:36px; cursor:pointer; }
|
||
:root[data-skin] button:hover:not(:disabled) { border-color:var(--sk-accent); }
|
||
:root[data-skin] button:disabled { opacity:.45; cursor:default; }
|
||
:root[data-skin] #connect { background:var(--fg); color:var(--bg); border-color:var(--fg); font-weight:600; }
|
||
:root[data-skin="byte"] #connect { background:var(--sk-accent); border-color:var(--sk-accent); color:var(--sk-on); font:12px/1 var(--sk-display); text-transform:uppercase; }
|
||
:root[data-skin] select { padding:6px 8px; }
|
||
:root[data-skin] select[size] { padding:4px; }
|
||
:root[data-skin] select[size] option { padding:3px 6px; border-radius:var(--sk-rs); }
|
||
:root[data-skin] select[size] option:checked { background:var(--sk-accent); color:var(--sk-on); }
|
||
:root[data-skin] :focus-visible { outline:2px solid var(--sk-accent); outline-offset:2px; }
|
||
:root[data-skin] summary { cursor:pointer; color:var(--sk-frame); font:12px/1.6 var(--sk-mono); }
|
||
:root[data-skin] .dim, :root[data-skin] #status { color:var(--dim); }
|
||
:root[data-skin] #status { font:12px/1.6 var(--sk-mono); color:var(--sk-frame); }
|
||
:root[data-skin] .hint { border-left:3px solid var(--sk-warn); background:color-mix(in srgb,var(--sk-warn) 9%,transparent); padding:8px 12px; border-radius:0 var(--sk-rs) var(--sk-rs) 0; }
|
||
/* the track buttons: each track its colour, the selected one filled */
|
||
:root[data-skin] #trackbtns { display:inline-flex; gap:6px; }
|
||
:root[data-skin] #trackbtns button { --tc:var(--sk-t1); min-width:38px; min-height:34px; font:600 14px/1 var(--sk-mono);
|
||
color:var(--tc); border-color:color-mix(in srgb,var(--tc) 55%,transparent); background:var(--sk-field); }
|
||
:root[data-skin] #trackbtns button:nth-child(2) { --tc:var(--sk-t2); } :root[data-skin] #trackbtns button:nth-child(3) { --tc:var(--sk-t3); }
|
||
:root[data-skin] #trackbtns button:nth-child(4) { --tc:var(--sk-t4); } :root[data-skin] #trackbtns button:nth-child(5) { --tc:var(--sk-t5); }
|
||
:root[data-skin] #trackbtns button:nth-child(6) { --tc:var(--sk-t6); }
|
||
:root[data-skin] #trackbtns button[aria-pressed="true"], :root[data-skin] #trackbtns button.sel { background:var(--tc); color:var(--sk-on); border-color:var(--tc); }
|
||
/* the sections: a panel each, its title as the firmware's tab, its parameters as cards */
|
||
:root[data-skin] .groups { columns:auto; display:grid; grid-template-columns:repeat(auto-fill,minmax(340px,1fr)); gap:14px; align-items:start; }
|
||
:root[data-skin] .group { background:var(--sk-panel); border:var(--sk-b) solid var(--line); border-radius:var(--sk-r); padding:14px;
|
||
margin:0; display:grid; grid-template-columns:repeat(auto-fill,minmax(98px,1fr)); gap:8px; break-inside:avoid; }
|
||
:root[data-skin] .group > :not(.row), :root[data-skin] .group > .row.modrow { grid-column:1/-1; }
|
||
:root[data-skin] .group h2 { display:flex; align-items:center; gap:8px; margin:0 0 4px; padding:0 0 10px; border-bottom:var(--sk-b) solid var(--line);
|
||
font:500 12px/1 var(--sk-mono); letter-spacing:.12em; text-transform:uppercase; color:var(--fg); }
|
||
:root[data-skin="byte"] .group h2 { font:13px/1 var(--sk-display); color:var(--sk-accent); }
|
||
:root[data-skin] .group h2::after { content:""; flex:1; height:3px; border-radius:3px; background:var(--sk-heat); opacity:.55; max-width:80px; margin-left:auto; }
|
||
:root[data-skin] .group h3 { margin:6px 0 0; font:500 10px/1.2 var(--sk-mono); letter-spacing:.14em; text-transform:uppercase; color:var(--sk-frame); }
|
||
:root[data-skin] .group p { margin:0; }
|
||
/* a parameter: name, value, how much (the firmware's card) */
|
||
:root[data-skin] .group .row:not(.modrow) { --kc:var(--sk-k1); display:grid; grid-template-columns:1fr; grid-template-areas:"l" "v" "c";
|
||
gap:2px; align-content:start; min-height:0; padding:8px 9px 9px; background:var(--sk-field);
|
||
border:var(--sk-b) solid color-mix(in srgb,var(--kc) 28%,transparent); border-radius:var(--sk-rs); }
|
||
:root[data-skin] .group .row:not(.modrow):nth-of-type(4n+2) { --kc:var(--sk-k2); }
|
||
:root[data-skin] .group .row:not(.modrow):nth-of-type(4n+3) { --kc:var(--sk-k3); }
|
||
:root[data-skin] .group .row:not(.modrow):nth-of-type(4n+4) { --kc:var(--sk-k4); }
|
||
:root[data-skin] .group .row:not(.modrow):hover, :root[data-skin] .group .row:not(.modrow):focus-within { border-color:var(--kc); }
|
||
:root[data-skin] .group .row:not(.modrow) > span:first-child { grid-area:l; font:500 10px/1.2 var(--sk-mono); letter-spacing:.08em;
|
||
text-transform:uppercase; color:var(--fg); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||
:root[data-skin] .group .row:not(.modrow) > .v { grid-area:v; font:400 var(--sk-value-size)/1.1 var(--sk-value); color:var(--kc);
|
||
text-align:left; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||
:root[data-skin] .group .row:not(.modrow) > input, :root[data-skin] .group .row:not(.modrow) > select,
|
||
:root[data-skin] .group .row:not(.modrow) > .sel, :root[data-skin] .group .row:not(.modrow) > div { grid-area:c; width:100%; min-width:0; }
|
||
:root[data-skin] .group .row.pushed { border-color:var(--sk-ok); box-shadow:0 0 0 1px var(--sk-ok); }
|
||
/* a list's card: the choice is the value (the select itself, large) */
|
||
:root[data-skin] .group .row:not(.modrow):has(> select) > .v { display:none; }
|
||
:root[data-skin] .group .row:not(.modrow) > select { grid-area:v; font:400 var(--sk-value-size)/1.1 var(--sk-value); color:var(--kc);
|
||
background:transparent; border:0; padding:0; appearance:none; -webkit-appearance:none; cursor:pointer; text-overflow:ellipsis; }
|
||
:root[data-skin="fm"] .group .row:not(.modrow) > select { font-size:14px; }
|
||
:root[data-skin] .group .row:not(.modrow) > select option { font:13px var(--sk-mono); background:var(--sk-panel); color:var(--fg); }
|
||
/* the bars: a range as the firmware's bar, filled to its value (--p: the script below) */
|
||
:root[data-skin] input[type="range"] { -webkit-appearance:none; appearance:none; height:16px; background:transparent; cursor:pointer; margin:2px 0 0;
|
||
--kcol:var(--kc,var(--sk-accent)); }
|
||
:root[data-skin] input[type="range"]::-webkit-slider-runnable-track { height:5px; border-radius:var(--sk-rs);
|
||
background:linear-gradient(90deg,var(--kcol) 0 var(--p,0%),color-mix(in srgb,var(--fg) 14%,transparent) var(--p,0%) 100%); }
|
||
:root[data-skin] input[type="range"]::-moz-range-track { height:5px; border-radius:var(--sk-rs); background:color-mix(in srgb,var(--fg) 14%,transparent); }
|
||
:root[data-skin] input[type="range"]::-moz-range-progress { height:5px; border-radius:var(--sk-rs); background:var(--kcol); }
|
||
:root[data-skin] input[type="range"]::-webkit-slider-thumb { -webkit-appearance:none; width:11px; height:15px; margin-top:-5px;
|
||
border-radius:var(--sk-rs); background:var(--fg); border:0; box-shadow:0 0 0 2px var(--bg); }
|
||
:root[data-skin] input[type="range"]::-moz-range-thumb { width:11px; height:15px; border-radius:var(--sk-rs); background:var(--fg); border:0; }
|
||
:root[data-skin] input[type="range"]:disabled { opacity:.35; }
|
||
/* the mixer: each strip its track's colour */
|
||
:root[data-skin] .strip { background:var(--sk-panel); border:var(--sk-b) solid var(--line); border-radius:var(--sk-r); --kc:var(--sk-t1); }
|
||
:root[data-skin] .strip:nth-child(2) { --kc:var(--sk-t2); } :root[data-skin] .strip:nth-child(3) { --kc:var(--sk-t3); }
|
||
:root[data-skin] .strip:nth-child(4) { --kc:var(--sk-t4); } :root[data-skin] .strip:nth-child(5) { --kc:var(--sk-t5); }
|
||
:root[data-skin] .strip:nth-child(6) { --kc:var(--sk-t6); }
|
||
:root[data-skin] .strip.sel { border-color:var(--kc); box-shadow:0 0 0 1px var(--kc); }
|
||
:root[data-skin] .strip button.selb:disabled, :root[data-skin] .strip .num { color:var(--kc); }
|
||
/* the steps: the grid as the firmware's step row */
|
||
:root[data-skin] .grid button { background:var(--sk-field); color:var(--dim); border:var(--sk-b) solid var(--line); border-radius:var(--sk-rs); font:11px/1.3 var(--sk-mono); }
|
||
:root[data-skin] .grid button.on { background:var(--sk-accent); color:var(--sk-on); border-color:var(--sk-accent); }
|
||
:root[data-skin] table { border-collapse:separate; border-spacing:0 4px; }
|
||
:root[data-skin] th { font:500 10px/1.3 var(--sk-mono); letter-spacing:.08em; text-transform:uppercase; color:var(--dim); text-align:left; }
|
||
:root[data-skin] .seg button[aria-pressed="true"], :root[data-skin] button.tog[aria-pressed="true"] { background:var(--sk-accent); border-color:var(--sk-accent); color:var(--sk-on); }
|
||
/* the FM6 page and the steps' table: small fields as the firmware's values (the accent, the value type), the table's
|
||
rows as cards */
|
||
:root[data-skin] input[type="number"], :root[data-skin] td input:not([type="checkbox"]):not([type="range"]), :root[data-skin] td select {
|
||
font:400 calc(var(--sk-value-size) * .7)/1.1 var(--sk-value); color:var(--sk-k1); background:var(--sk-field); text-align:center;
|
||
border:var(--sk-b) solid color-mix(in srgb,var(--sk-k1) 30%,transparent); border-radius:var(--sk-rs); padding:4px 4px; min-height:32px; min-width:3.6em; }
|
||
:root[data-skin] input[type="number"]:focus, :root[data-skin] td input:focus { border-color:var(--sk-k1); }
|
||
:root[data-skin] tbody tr { background:var(--sk-panel); }
|
||
:root[data-skin] tbody tr:hover { background:color-mix(in srgb,var(--sk-accent) 8%,var(--sk-panel)); }
|
||
:root[data-skin] td { padding:4px 6px; border-top:var(--sk-b) solid var(--line); border-bottom:var(--sk-b) solid var(--line); }
|
||
:root[data-skin] td:first-child { border-left:var(--sk-b) solid var(--line); border-radius:var(--sk-rs) 0 0 var(--sk-rs); font:500 12px var(--sk-mono); color:var(--sk-frame); }
|
||
:root[data-skin] td:last-child { border-right:var(--sk-b) solid var(--line); border-radius:0 var(--sk-rs) var(--sk-rs) 0; }
|
||
:root[data-skin] .group label, :root[data-skin] .group .bar { font:500 11px/1.4 var(--sk-mono); letter-spacing:.06em; color:var(--dim); }
|
||
:root[data-skin] input[type="checkbox"] { accent-color:var(--sk-accent); width:16px; height:16px; }
|
||
/* the support line and the footer */
|
||
:root[data-skin] p.kofi { border-left:3px solid; border-image:var(--sk-heat) 1; padding-left:12px; }
|
||
:root[data-skin] footer { color:var(--dim); font:11px/1.6 var(--sk-mono); border-top:var(--sk-b) solid var(--line); padding-top:14px; }
|
||
@media (max-width:640px) {
|
||
:root[data-skin] .groups { grid-template-columns:1fr; }
|
||
:root[data-skin] .group { grid-template-columns:repeat(auto-fill,minmax(96px,1fr)); padding:12px; }
|
||
:root[data-skin] nav.tabs { overflow-x:auto; flex-wrap:nowrap; }
|
||
}
|
||
/*SKIN-END*/
|
||
</style>
|
||
<script id="jiant-skin-fill">
|
||
/* (studio) each range's fill (--p) at its value: when it moves, and when the page shows a new value (a push, a load) */
|
||
(() => {
|
||
const fill = (r) => { const lo = +r.min || 0, hi = r.max === "" ? 100 : +r.max; r.style.setProperty("--p", `${((+r.value - lo) * 100 / ((hi - lo) || 1)).toFixed(1)}%`); };
|
||
let raf = 0;
|
||
const all = () => { raf = 0; document.querySelectorAll('input[type="range"]').forEach(fill); };
|
||
document.addEventListener("input", (e) => { if (e.target.type === "range") fill(e.target); }, true);
|
||
addEventListener("DOMContentLoaded", () => {
|
||
all();
|
||
new MutationObserver(() => { if (!raf) raf = requestAnimationFrame(all); }).observe(document.body, { subtree: true, childList: true, characterData: true });
|
||
});
|
||
})();
|
||
</script>
|
||
</head>
|
||
<body class="jiant-editor">
|
||
<main>
|
||
<button class="lang" id="lang"></button>
|
||
<h1 class="jiant-wordmark"><a href="https://juanjiant-bit.github.io/JIANT/" aria-label="JIANT FM home">JIANT <span class="fm">FM</span></a><span class="jiant-tool">EDITOR</span></h1>
|
||
<p class="dim"><a href="../installer/" style="color:inherit" data-t="installer"></a></p>
|
||
<!-- always visible: connection, version, sync mode, the tabs and (Sound / Sequencer / Tracks) the track selector -->
|
||
<header class="top">
|
||
<div class="bar">
|
||
<button id="connect" data-t="connect" data-ic="port_usb_c"></button>
|
||
<span id="version" class="dim"></span>
|
||
<span id="live" class="dim"></span>
|
||
<span id="mock" class="dim" hidden data-t="mock"></span>
|
||
<button id="screenbtn" data-t="screenBtn" hidden></button>
|
||
</div>
|
||
<div id="status"></div>
|
||
<details id="midiports"><summary data-t="midiPorts"></summary><p id="midiportcounts" class="dim"></p><p class="dim" data-t="midiPortHelp"></p><p class="bar">
|
||
<label><span data-t="midiInput"></span> <select id="midiinput"><option value="">Auto</option></select></label>
|
||
<label><span data-t="midiOutput"></span> <select id="midioutput"><option value="">Auto</option></select></label>
|
||
</p></details>
|
||
<nav class="tabs" id="tabs" role="tablist">
|
||
<button role="tab" data-tab="sound" data-t="sound" data-ic="symbol_audio"></button>
|
||
<button role="tab" data-tab="fm6" data-t="tabFm6" data-ic="ui_knob"></button>
|
||
<button role="tab" data-tab="sequencer" data-t="tabSeq" data-ic="symbol_grid"></button>
|
||
<button role="tab" data-tab="roll" data-t="tabRoll" data-ic="symbol_keyboard"></button>
|
||
<button role="tab" data-tab="math" data-t="tabMath" data-ic="waveform_harmonic"></button>
|
||
<button role="tab" data-tab="tracks" data-t="tabTracks" data-ic="ui_slider_vertical"></button>
|
||
<button role="tab" data-tab="library" data-t="library" data-ic="symbol_books"></button>
|
||
<button role="tab" data-tab="projects" data-t="projects" data-ic="symbol_folder"></button>
|
||
<button role="tab" data-tab="settings" data-t="tabSettings" data-ic="symbol_cog"></button>
|
||
</nav>
|
||
<div class="trackbar" id="trackbar" hidden><span class="dim" data-t="track"></span><span class="seg" id="trackbtns" role="group"></span></div>
|
||
</header>
|
||
<p class="hint" id="hint" hidden></p>
|
||
<!-- the screen mirror: the FM-1's screen as big as this screen (a phone: the FM-1 on its USB-C port) -->
|
||
<div class="mirror" id="mirror" role="dialog" aria-modal="true" aria-labelledby="mirrortitle" hidden>
|
||
<div class="mirror-bar">
|
||
<strong id="mirrortitle" data-t="screenTitle"></strong>
|
||
<span id="mirrorstat"></span>
|
||
<span class="mirror-btns">
|
||
<button id="mirrorsharp" data-t="screenSharp" aria-pressed="true"></button>
|
||
<button id="mirrorfull" data-t="screenFull"></button>
|
||
<button id="mirrorclose" data-t="screenClose"></button>
|
||
</span>
|
||
</div>
|
||
<div class="mirror-stage"><canvas id="mirrorcv" width="240" height="240" aria-label=""></canvas></div>
|
||
</div>
|
||
|
||
<section class="panel" id="p-sound" data-tab="sound" data-dev hidden>
|
||
<div class="browser" id="browser">
|
||
<label><span data-t="engine"></span><br><select id="engine"></select></label>
|
||
<label><span data-t="presets"></span><br><select id="preset" size="8"></select></label>
|
||
<div>
|
||
<p class="bar"><button id="init" data-t="initSound"></button>
|
||
<button id="factlib" data-t="factoryToLib" data-ic="symbol_folder"></button></p>
|
||
<p class="bar"><button id="savefile" data-t="saveFile" data-ic="symbol_download"></button>
|
||
<button id="loadfile" data-t="loadFile" data-ic="symbol_upload"></button>
|
||
<input type="file" id="file" accept=".json,application/json" hidden></p>
|
||
</div>
|
||
</div>
|
||
<p class="dim" id="ctlhelp" data-t="ctlHelp"></p>
|
||
<div class="groups" id="groups"></div>
|
||
<div class="group" id="lyricbox" hidden><h3 data-t="lyricT"></h3>
|
||
<p class="dim" data-t="lyricHelp"></p>
|
||
<p class="bar"><label><span data-t="lyricLang"></span> <select id="lyrlang"></select></label>
|
||
<label><span data-t="lyricSrc"></span> <select id="lyrsrc"></select></label></p>
|
||
<p class="bar"><input id="lyric" maxlength="63" size="56" autocomplete="off" spellcheck="false">
|
||
<button id="lyricsend" data-t="lyricSend"></button></p></div>
|
||
</section>
|
||
|
||
<section class="panel" id="p-fm6" data-tab="fm6" data-dev hidden>
|
||
<p class="dim" data-t="fm6Help"></p>
|
||
<div class="group">
|
||
<h2 data-t="fm6Source" data-ic="symbol_folder"></h2>
|
||
<p class="bar"><label><span data-t="track"></span> <select id="fm6trk"></select></label>
|
||
<button id="fm6read" data-t="fm6ReadBtn"></button> <button id="fm6send" data-t="fm6SendBtn"></button>
|
||
<label><input type="checkbox" id="fm6live"> <span data-t="fm6Live"></span></label></p>
|
||
<p class="bar"><button id="fm6import" data-t="fm6Import" data-ic="symbol_upload"></button>
|
||
<input type="file" id="fm6file" accept=".syx,.SYX,.bin,application/octet-stream" hidden>
|
||
<button id="fm6export" data-t="fm6Export" data-ic="symbol_download"></button>
|
||
<button id="fm6init" data-t="fm6Init"></button></p>
|
||
<div id="fm6imported"></div>
|
||
<p class="bar"><label><span data-t="fm6Factories"></span> <select id="fm6slot"></select></label>
|
||
<button id="fm6load" data-t="load"></button></p>
|
||
<p class="dim" id="fm6keep" data-t="fm6Keep"></p>
|
||
</div>
|
||
<div class="group">
|
||
<h2 data-t="fm6Voice" data-ic="ui_knob"></h2>
|
||
<div id="fm6voice"></div>
|
||
</div>
|
||
<div class="group">
|
||
<h2 data-t="fm6Ops" data-ic="function_env_adsr_exp"></h2>
|
||
<div id="fm6ops"></div>
|
||
</div>
|
||
</section>
|
||
|
||
<section class="panel" id="p-sequencer" data-tab="sequencer" data-dev hidden>
|
||
<div class="groups" id="seqgroups"></div>
|
||
<div id="steps">
|
||
<h2 data-t="steps" data-ic="note_eight"></h2>
|
||
<p class="bar"><button id="reloadsteps" data-t="reload" data-ic="control_arrow_loop"></button>
|
||
<button id="clearseq" data-t="clearSeq" data-ic="symbol_trash"></button>
|
||
<span class="dim" id="noteshelp"></span></p>
|
||
<div class="grid" id="stepgrid"></div>
|
||
<div class="stepcols" id="steptables"></div>
|
||
</div>
|
||
<div id="motion-panel" hidden style="margin-top:16px">
|
||
<h2 data-t="motion"></h2>
|
||
<p class="bar"><label><input id="motion-on" type="checkbox"> <span data-t="motionOn"></span></label>
|
||
<button id="motion-clear" data-t="motionClear"></button><span id="motion-count" class="dim"></span></p>
|
||
<table id="motion-rows"></table>
|
||
</div>
|
||
</section>
|
||
|
||
<!-- the piano roll of every sequencer, drawn as the FM-1 draws it (nothing runs while it is closed) -->
|
||
<section class="panel" id="p-roll" data-tab="roll" data-dev hidden>
|
||
<div class="rhud" id="rollhud"></div>
|
||
<div class="bar rtools">
|
||
<span id="rollstat" class="dim" aria-live="polite"></span>
|
||
<span class="seg" id="rollvl" role="group"><button type="button" data-v="vel" aria-pressed="true">VEL</button><button type="button" data-v="chance" aria-pressed="false">CHNC</button><button type="button" data-v="ratch" aria-pressed="false">RATCH</button></span>
|
||
<button type="button" id="rollzout" aria-label="zoom out">−</button><button type="button" id="rollzin" aria-label="zoom in">+</button>
|
||
<button type="button" id="rollfit" data-t="rollFit"></button>
|
||
<button type="button" id="rollundo" data-t="rollUndo"></button>
|
||
<button type="button" id="rollreload" data-t="reload" data-ic="control_arrow_loop"></button>
|
||
</div>
|
||
<div class="rmain">
|
||
<canvas id="rollcv" tabindex="0" aria-label="piano roll"></canvas>
|
||
<div class="rinsp" id="rollinsp"></div>
|
||
</div>
|
||
<p class="dim" data-t="rollHelp"></p>
|
||
<details class="group rdet" id="rolleubox"><summary>EUCLID</summary>
|
||
<p class="dim" data-t="rollEuHelp"></p>
|
||
<form id="rolleu" class="reu" onsubmit="return false">
|
||
<label><span data-hits>HITS</span> <input type="range" name="hits" min="0" max="16" value="4"><b data-o="hits"></b></label>
|
||
<label><span>STEPS</span> <input type="range" name="steps" min="1" max="64" value="16"><b data-o="steps"></b></label>
|
||
<label><span>ROTATE</span> <input type="range" name="rot" min="0" max="15" value="0"><b data-o="rot"></b></label>
|
||
<label><span>LANE</span> <select name="lane"></select></label>
|
||
<label><span>NOTE</span> <input type="range" name="note" min="24" max="96" value="48"><b data-o="note"></b></label>
|
||
</form>
|
||
<p class="bar"><button type="button" id="rolleuprev" data-t="rollPreview"></button><button type="button" id="rolleuwrite" data-t="rollWriteSteps"></button></p>
|
||
</details>
|
||
<details class="group rdet" id="rollms"><summary>MOD SEQ</summary><p class="dim" data-t="rollMsHelp"></p><div class="rstripbox"></div></details>
|
||
<details class="group rdet" id="rollslc"><summary>SLICER STEPS</summary><p class="dim" data-t="rollSlcHelp"></p><div class="rstripbox"></div></details>
|
||
</section>
|
||
|
||
<!-- MATH's formulas: written, heard, generated, sent (works without a device; the send needs one) -->
|
||
<section class="panel" id="p-math" data-tab="math" hidden>
|
||
<p class="dim" data-t="mathHelp"></p>
|
||
<div class="bar"><span class="seg" id="mwave" role="group"><button type="button" data-w="5" aria-pressed="true">BYTE</button><button type="button" data-w="6" aria-pressed="false">FLOAT</button></span>
|
||
<select id="mstock" aria-label="ALGO"></select></div>
|
||
<div class="mgrid">
|
||
<div>
|
||
<textarea id="mf" rows="4" spellcheck="false" autocomplete="off" autocapitalize="off" aria-label="formula"></textarea>
|
||
<p id="merr" class="merr" aria-live="polite"></p>
|
||
<div class="mops" id="mops"></div>
|
||
<details class="mgram"><summary data-t="mathGrammarT"></summary><p data-t="mathGrammar"></p></details>
|
||
</div>
|
||
<canvas id="mscope" width="256" height="128" aria-label="the formula's picture"></canvas>
|
||
</div>
|
||
<div class="bar"><span class="seg" id="mchip" role="group"><button type="button" data-c="0">4BIT</button><button type="button" data-c="1">4B/2</button><button type="button" data-c="2">8BIT</button><button type="button" data-c="3">1BIT</button></span>
|
||
<label id="msyncl"><input type="checkbox" id="msync"> SYNC</label></div>
|
||
<div class="mknobs" id="mknobs"></div>
|
||
<p class="bar"><button type="button" id="mplay" data-t="mathPlay"></button><button type="button" id="mstop" data-t="mathStop"></button>
|
||
<label><input type="checkbox" id="mloop"> <span data-t="mathLoop"></span></label><span id="msrc" class="dim" aria-live="polite"></span></p>
|
||
<p class="bar mgenbar"><label><span data-t="mathSeed"></span> <input type="number" id="mseed" min="1" value="1" style="width:7em"></label>
|
||
<label><span data-t="mathFamily"></span> <select id="mfam"></select></label>
|
||
<label class="mchaos"><span data-t="mathChaos"></span> <input type="range" id="mchaos" min="0" max="100" value="40"> <b id="mchaosv">40</b></label>
|
||
<button type="button" id="mgen" data-t="mathGen"></button><button type="button" id="mgenp" data-t="mathGenPatch"></button></p>
|
||
<p class="bar"><label><span data-t="track"></span> <select id="mtrk" onchange="this.dataset.touched=1"></select></label>
|
||
<button type="button" id="msend" data-t="mathSend"></button><button type="button" id="mread" data-t="mathRead"></button>
|
||
<span id="msendmsg" class="dim"></span></p>
|
||
</section>
|
||
|
||
<section class="panel" id="p-tracks" data-tab="tracks" data-dev hidden>
|
||
<h2 data-t="mixer" data-ic="ui_slider_vertical"></h2>
|
||
<div class="mixer" id="mixer"></div>
|
||
<p class="dim" data-t="mixHelp"></p>
|
||
</section>
|
||
|
||
<!-- works without a device too (the device bank shows while connected) -->
|
||
<section class="panel" id="p-library" data-tab="library" hidden>
|
||
<div class="group" id="device-presets" hidden>
|
||
<h2 data-t="devicePresets"></h2>
|
||
<p class="dim" data-t="deviceFavHelp"></p>
|
||
<label><span data-t="deviceList"></span> <select id="device-filter"></select></label>
|
||
<div class="list" id="device-preset-list" style="margin-top:8px"></div>
|
||
</div>
|
||
<div class="libcols" id="libsec">
|
||
<div id="libpane">
|
||
<h2 data-t="library" data-ic="symbol_books"></h2>
|
||
<div class="bar">
|
||
<input type="search" id="libq" spellcheck="false">
|
||
<select id="libeng"></select>
|
||
<select id="libtag"></select>
|
||
<select id="libsort"></select>
|
||
</div>
|
||
<div class="list" id="liblist"></div>
|
||
<p class="bar" style="margin-top:6px">
|
||
<button id="libaud" data-t="audition" data-ic="symbol_audio"></button>
|
||
<button id="libput" data-t="toSlot" data-ic="symbol_upload"></button>
|
||
<button id="libren" data-t="rename"></button>
|
||
<button id="libtags" data-t="tags"></button>
|
||
<button id="libdup" data-t="duplicate"></button>
|
||
<button id="libdel" data-t="delete" data-ic="symbol_trash"></button>
|
||
<button id="libexp1" data-t="exportPatch" data-ic="symbol_download"></button>
|
||
</p>
|
||
<p class="bar">
|
||
<button id="libsave" data-t="saveToLib" data-ic="port_disk"></button>
|
||
<button id="libimport" data-t="import" data-ic="symbol_upload"></button>
|
||
<button id="libexport" data-t="exportLib" data-ic="symbol_download"></button>
|
||
<input type="file" id="libfile" accept=".json,application/json" multiple hidden>
|
||
<span class="dim" id="libcount"></span>
|
||
</p>
|
||
</div>
|
||
<div>
|
||
<h2 data-t="bank" data-ic="port_disk"></h2>
|
||
<p class="dim" id="bankhint"></p>
|
||
<div id="bankpane" hidden>
|
||
<div class="bar"><b id="bankhead"></b></div>
|
||
<div class="list" id="banklist"></div>
|
||
<p class="bar" style="margin-top:6px">
|
||
<button id="bkload" data-t="bankLoad" data-ic="symbol_folder_open"></button>
|
||
<button id="bkstore" data-t="bankStore" data-ic="port_disk"></button>
|
||
<button id="bkget" data-t="bankGet" data-ic="symbol_download"></button>
|
||
<button id="bkerase" data-t="erase" data-ic="symbol_trash"></button>
|
||
</p>
|
||
<p class="bar">
|
||
<button id="bkrefresh" data-t="reload" data-ic="control_arrow_loop"></button>
|
||
<button id="bkexport" data-t="exportBank" data-ic="symbol_download"></button>
|
||
<span class="dim" data-t="dndHelp"></span>
|
||
</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
|
||
<section class="panel" id="p-projects" data-tab="projects" data-dev hidden>
|
||
<h2 data-t="projects" data-ic="symbol_folder"></h2>
|
||
<p class="dim" data-t="projHelp"></p>
|
||
<div class="slots" id="slots"></div>
|
||
<div id="backup-panel" style="margin-top:16px">
|
||
<h2 data-t="backupTitle"></h2>
|
||
<p class="bar"><button id="backup-export" data-t="backupExport"></button>
|
||
<button id="backup-import" data-t="backupImport"></button><input id="backup-file" type="file" accept=".json,application/json" hidden></p>
|
||
<p class="dim" id="backup-help"></p>
|
||
</div>
|
||
<div class="group" id="songchain" hidden style="margin-top:16px">
|
||
<h2 data-t="songTitle"></h2>
|
||
<p class="dim" data-t="songHelp"></p>
|
||
<p class="bar"><button id="songplay"></button><button id="songadd" data-t="songAdd"></button>
|
||
<button id="songremove" data-t="songRemove"></button><span id="songstatus" aria-live="polite"></span></p>
|
||
<div id="songrows"></div>
|
||
</div>
|
||
</section>
|
||
|
||
<section class="panel" id="p-settings" data-tab="settings" data-dev hidden>
|
||
<div class="groups" id="setgroups"></div>
|
||
<div class="group" id="device-display" hidden style="margin-top:12px">
|
||
<h2 data-t="deviceDisplay"></h2>
|
||
<p class="dim" data-t="deviceDisplayHelp"></p>
|
||
<div id="device-display-controls"></div>
|
||
</div>
|
||
<div class="group" style="margin-top:12px">
|
||
<h2 data-t="system" data-ic="symbol_cog"></h2>
|
||
<table id="sysinfo"></table>
|
||
</div>
|
||
</section>
|
||
|
||
<p class="kofi" style="margin-top:24px;border-left:3px solid #ec6e50;padding:4px 0 4px 12px">If you resonate with my work, consider supporting me on <a href="https://ko-fi.com/juanjiant" target="_blank" rel="noopener" style="color:inherit;font-weight:600">Ko-fi</a> (in Argentina: <a href="https://cafecito.app/juanjiant" target="_blank" rel="noopener" style="color:inherit;font-weight:600">Cafecito</a>). Thanks for all the good energy, hope you enjoy this little beast 🫶✨🎹</p>
|
||
<footer>JIANT FM by Juan Jiant. GPL-3.0.<br>
|
||
<span data-t="foot"></span> M-VAVE and FM-1 are trademarks of their respective owners.<br>
|
||
<a href="FUKIAI-LICENSE.txt" data-t="iconsCredit"></a></footer>
|
||
</main>
|
||
<script>
|
||
"use strict";
|
||
/*PROTO-BEGIN*/
|
||
/* ---------------------------------------------------------------- protocol --- */
|
||
const HDR = [0x7D, 0x46, 0x4C];
|
||
const CMD = { INFO: 1, GET: 2, SET: 3, DUMP: 4, DESC: 5, STEP_GET: 6, STEP_SET: 7, PRESET: 8, PROJECT: 9, NAMES: 10,
|
||
UP_LIST: 16, UP_GET: 17, UP_PUT: 18, UP_STORE: 19, UP_LOAD: 20, UP_ERASE: 21,
|
||
WATCH: 22, CHANGED: 23, RELOAD: 24, PING: 25, STEP_CHANGED: 26,
|
||
TRACK: 27, TRACK_MIX: 28, TRACK_DUMP: 29, TRACK_STEP: 30,
|
||
TRACK_PARAM: 31, TRACK_CHANGED: 32, SONG: 33,
|
||
UI_STATE: 34, UI_SET: 35, UI_PALETTES: 36, FAV_GET: 37, FAV_SET: 38, LYRIC: 39,
|
||
MOTION: 64, BACKUP_LIST: 65, BACKUP_GET: 66, BACKUP_PUT: 67,
|
||
FM6_GET: 68, FM6_PUT: 69, FM6_LIST: 70, FM6_ERASE: 71,
|
||
FM6B_BEGIN: 74, FM6B_WRITE: 75, FM6B_END: 76, FM6B_LIST: 77, /* (JIANT 0.6.11, Felucca 1.4.1) FM6's voice bank */
|
||
SCREEN: 78, SCREEN_DATA: 79, /* the screen mirror (EDITOR_PROTOCOL.md "Screen mirror") */
|
||
FORMULA: 100, /* (V10.8.75, 1.5) MATH USER's formula of a track */
|
||
};
|
||
/* 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, CMD.SCREEN_DATA]);
|
||
|
||
/* ---- the screen mirror (78 SCREEN, 79 SCREEN_DATA; firmware/src/editor_screen.c): a SCREEN_DATA frame is the pixels
|
||
of a box (a strip, or a fill) from pixel `start` on, row by row (type 0, the only one), as tokens:
|
||
0x00..0x3F the colour at that hash, 0x40..0x67 the colour before 1..40 times more, 0x68..0x6F then a byte: 41..1064
|
||
times, 0x70..0x7F then two bytes: a colour in full (RGB565: 4 + 7 + 5 bits). Each frame starts with an empty hash table
|
||
and the colour before 0. */
|
||
const SCR = { W: 240, H: 240, CAP: 256 };
|
||
const scrHash = (c) => ((c >> 11) * 3 + ((c >> 5) & 63) * 5 + (c & 31) * 7) & 63;
|
||
/* a = the frame's bytes after the command; fb: Uint16Array(240 * 240) of RGB565. -> the box drawn {x, y, w, h}, or null */
|
||
function scrDecode(a, fb) {
|
||
if (a.length < 17) return null;
|
||
const x = a[1] | a[2] << 7, y = a[3] | a[4] << 7, w = a[5] | a[6] << 7, h = a[7] | a[8] << 7, end = w * h;
|
||
let k = a[9] | a[10] << 7 | a[11] << 14;
|
||
if (!w || !h || x + w > SCR.W || y + h > SCR.H) return null;
|
||
const put = (c, r) => { for (; r > 0 && k < end; r--, k++) fb[(y + (k / w | 0)) * SCR.W + x + k % w] = c; };
|
||
if (a[0] !== 0) return null;
|
||
const tab = new Uint16Array(64);
|
||
let prev = 0;
|
||
for (let j = 12; j < a.length;) {
|
||
const t = a[j++];
|
||
if (t < 0x40) { prev = tab[t]; put(prev, 1); }
|
||
else if (t < 0x68) put(prev, t - 0x40 + 1);
|
||
else if (t < 0x70) put(prev, 41 + ((t & 7) << 7 | (a[j++] | 0)));
|
||
else { prev = (t & 15) << 12 | (a[j] | 0) << 5 | (a[j + 1] | 0); j += 2; tab[scrHash(prev)] = prev; put(prev, 1); }
|
||
}
|
||
return { x, y, w, h };
|
||
}
|
||
/* the device's side (editor_screen.c scr_tap), for the mock device and the tests: px[] RGB565, a row every `stride`
|
||
pixels -> the frames' argument arrays (type 0) */
|
||
function scrEncode(px, x, y, w, h, stride = w, cap = SCR.CAP) {
|
||
const frames = [];
|
||
let out, tab, prev, run, k = 0;
|
||
const hdr = (start) => { out = [0, x & 127, x >> 7, y & 127, y >> 7, w & 127, w >> 7, h & 127, h >> 7,
|
||
start & 127, (start >> 7) & 127, start >> 14]; tab = new Uint16Array(64); prev = 0; run = 0; };
|
||
const flushRun = () => {
|
||
if (!run) return;
|
||
if (run <= 40) out.push(0x40 + run - 1); else { const r = run - 41; out.push(0x68 | r >> 7, r & 127); }
|
||
run = 0;
|
||
};
|
||
hdr(0);
|
||
for (let j = 0; j < h; j++) for (let i = 0; i < w; i++, k++) {
|
||
const c = px[j * stride + i] & 0xFFFF;
|
||
if (out.length + 5 > 12 + cap) { flushRun(); frames.push(out); hdr(k); }
|
||
if (c === prev) { if (++run === 1064) flushRun(); continue; }
|
||
flushRun();
|
||
const hh = scrHash(c);
|
||
if (tab[hh] === c) out.push(hh); else { out.push(0x70 | c >> 12, (c >> 5) & 127, c & 31); tab[hh] = c; }
|
||
prev = c;
|
||
}
|
||
flushRun();
|
||
if (out.length > 12) frames.push(out);
|
||
return frames;
|
||
}
|
||
/* user preset bank: name 1..12 printable ASCII, a 16-step pattern of (note, flags 1 acc 2 slide 4 tie) */
|
||
const UP = { NAME_MAX: 12, PAT: 16, LIST_MAX: 16 };
|
||
const F = { INT: 0, PCT: 1, BIPCT: 2, TIME: 3, LFOHZ: 4, CUTOFF: 5, DB: 6, SEMI: 7, ENUM: 8, BPM: 9, NOTE: 10, ONOFF: 11, OCT: 12, STEPS: 13 };
|
||
|
||
const v14enc = (v) => { const u = Math.max(-8192, Math.min(8191, Math.round(v))) + 8192; return [u & 0x7F, (u >> 7) & 0x7F]; };
|
||
const v14dec = (lo, hi) => (lo | (hi << 7)) - 8192;
|
||
function strEnc(s) { const a = []; for (const c of String(s)) a.push(c.charCodeAt(0) & 0x7F); a.push(0); return a; }
|
||
|
||
/* only ever builds F0 7D 46 4C ... F7 */
|
||
function frame(cmd, args = []) {
|
||
for (const b of args) if (!(Number.isInteger(b) && b >= 0 && b <= 0x7F)) throw new Error("bad data byte " + b);
|
||
return [0xF0, ...HDR, cmd & 0x7F, ...args, 0xF7];
|
||
}
|
||
/* -> {cmd, a} or null when it is not an editor frame */
|
||
function unframe(d) {
|
||
if (!d || d.length < 6 || d[0] !== 0xF0 || d[d.length - 1] !== 0xF7) return null;
|
||
if (d[1] !== HDR[0] || d[2] !== HDR[1] || d[3] !== HDR[2]) return null;
|
||
return { cmd: d[4], a: Array.from(d.slice(5, d.length - 1)) };
|
||
}
|
||
|
||
/* the DRUM grid (firmware v5): a step's lane hits and their accents, bit l = lane l. Each lane plays its GM note
|
||
(eng_drum.c DRUM_LANE_NOTE) on any engine; LANE_OF: the lane a GM note 35..81 strikes (drum_lane; others fold
|
||
to their octave of 36..47) */
|
||
const LANES = ["KICK", "SNARE", "CLAP", "HATCL", "HATOP", "TOM", "RIM", "BELL"];
|
||
const LANE_NOTE = [36, 38, 39, 42, 46, 45, 37, 56];
|
||
const LANE_OF = "00612153535455757773777675555555773366336665577";
|
||
const LANE_ALIAS = { CONGA: 5, CLAVE: 6, CYM: 7, BD: 0, SD: 1, CP: 2, CH: 3, OH: 4 };
|
||
const drumLane = (n) => +LANE_OF[(n >= 35 && n <= 81 ? n : 36 + ((n + 120 - 36) % 12)) - 35];
|
||
/* the lanes a step strikes (its hits, its notes on their lanes) and which are accented (step_lanes / step_accents) */
|
||
const stepLanes = (s) => (s.time !== 0 ? 0 : s.notes.slice(0, s.n).reduce((m, n) => m | (1 << drumLane(n)), s.hit | 0));
|
||
const stepAccents = (s) => (s.flags & 1 ? stepLanes(s) : (s.acc | 0) & stepLanes(s));
|
||
/* hits as text, an accent marked ">" ("KICK >SNARE HATCL"), and back: null when a word is not a lane */
|
||
const hitsText = (hit, acc) => LANES.map((nm, l) => (hit >> l & 1 ? (acc >> l & 1 ? ">" : "") + nm : "")).filter(Boolean).join(" ");
|
||
function parseHits(text) {
|
||
let hit = 0, acc = 0;
|
||
for (const w of String(text).toUpperCase().split(/[\s,]+/).filter(Boolean)) {
|
||
const a = w.startsWith(">"), nm = a ? w.slice(1) : w, l = LANES.includes(nm) ? LANES.indexOf(nm) : LANE_ALIAS[nm];
|
||
if (l == null) return null;
|
||
hit |= 1 << l;
|
||
if (a) acc |= 1 << l;
|
||
}
|
||
return { hit, acc };
|
||
}
|
||
/* the 3 bytes after a step (v5): hit & 127, acc & 127, bit 7 of each; an older firmware's step has none (0) */
|
||
const hitsEnc = (hit, acc) => [hit & 0x7F, acc & 0x7F, (hit >> 7 & 1) | (acc >> 7 & 1) << 1];
|
||
function readHits(r, o) {
|
||
o.hit = 0; o.acc = 0;
|
||
if (r.i + 3 <= r.a.length) { const h = r.b(), c = r.b(), x = r.b(); o.hit = h | (x & 1) << 7; o.acc = (c | (x & 2) << 6) & o.hit; }
|
||
o.chance = r.i < r.a.length ? r.b() : 100;
|
||
if (o.chance > 100) throw new Error("Invalid step chance");
|
||
o.ratchet = r.i < r.a.length ? r.b() : 1; /* RATCH (INFO 52 01): the step's hits 1..4; older firmware: 1 */
|
||
if (o.ratchet < 1 || o.ratchet > 4) throw new Error("Invalid step ratchet");
|
||
if (r.i + 8 <= r.a.length) { /* (0.8.5, INFO 4F 01 07) each DRUM lane's mode 0..6; older firmware: none */
|
||
o.lanes = [];
|
||
for (let l = 0; l < 8; l++) { const m = r.b(); if (m > 6) throw new Error("Invalid step lane mode"); o.lanes.push(m); }
|
||
}
|
||
return o;
|
||
}
|
||
|
||
class Reader {
|
||
constructor(a) { this.a = a; this.i = 0; }
|
||
b() { if (this.i >= this.a.length) throw new Error("short reply"); return this.a[this.i++]; }
|
||
v() { const lo = this.b(); return v14dec(lo, this.b()); }
|
||
s() { let s = ""; for (;;) { const c = this.b(); if (!c) return s; s += String.fromCharCode(c); } }
|
||
}
|
||
|
||
const parse = {
|
||
[CMD.SCREEN](a) { const r = new Reader(a); return { op: r.b(), rc: r.b(), on: r.b(), w: r.b() | r.b() << 7, h: r.b() | r.b() << 7 }; },
|
||
[CMD.INFO](a) {
|
||
const r = new Reader(a);
|
||
const o = { version: r.s(), nengines: r.b(), pcount: r.b(), gcount: r.b(), nstep: r.b(), pe0: r.b(), engines: [] };
|
||
for (let i = 0; i < o.nengines; i++) o.engines.push(r.s());
|
||
o.chainRows = 0;
|
||
o.ntrk = r.i < a.length ? r.b() : 0; /* v3: tracks (0 = older firmware, one instrument) */
|
||
o.uiCaps = 0;
|
||
const trailer = a.slice(r.i);
|
||
if (trailer[0] === 16) o.chainRows = 16; /* existing v6 SONG capability */
|
||
if (trailer.length >= 4 && trailer[0] === 16 && trailer[1] === 0x55 && trailer[2] === 1)
|
||
o.uiCaps = trailer[3] & 15; /* tagged preferences; never interpret old PR bytes as SONG */
|
||
o.motionMax = 0; o.chance = false; o.backupCaps = 0;
|
||
if (o.uiCaps && trailer[4] === 0x4d && trailer[5] === 1 && trailer[6] === 64) {
|
||
o.motionMax = 64; o.chance = trailer[7] === 1;
|
||
if (trailer[8] === 0x42 && trailer[9] === 1) o.backupCaps = trailer[10] & 3;
|
||
}
|
||
o.fm6 = null; /* FM6 patches (cmds 68..71): the factory and bank slot counts */
|
||
o.syncCaps = 0; /* live sync: bit 0 WATCH while on keeps pending pushes, bit 1 no RELOAD */
|
||
o.ratchet = 0; /* a step's ratchet (STEP_SET's byte after the chance), 0 = none */
|
||
o.fm6Bank = 0; /* (JIANT 0.6.11) FM6's voice bank: its voices (cmds 74..77), 0 = none */
|
||
o.laneModes = 0; /* (JIANT 0.8.5) a step's DRUM lane modes (7: none x2 x4 x8 SHORT GHOST FLAM) */
|
||
for (const p of [8, 11]) if (o.motionMax && trailer[p] === 0x46 && trailer[p + 1] === 1) { /* for the editor's */
|
||
o.fm6 = { factory: trailer[p + 2], bank: trailer[p + 3], caps: 0 }; /* PRESET / G_ENGSEL */
|
||
if (trailer[p + 4] === 0x53 && trailer[p + 5] === 1) o.syncCaps = trailer[p + 6] & 3;
|
||
/* FM6 v2 (1.0.3): bit 0 no bank (SLOT F1..F8, 8 = OWN), bit 1 the user presets carry their patch (target 3) */
|
||
if (trailer[p + 7] === 0x50 && trailer[p + 8] === 1) o.fm6.caps = trailer[p + 9] & 3;
|
||
let r = trailer[p + 7] === 0x50 ? p + 10 : p + 7; /* RATCH after FM6 v2 */
|
||
if (trailer[r] === 0x4E && trailer[r + 1] === 1) r += 3; /* and the MENU settings (1.0.4) */
|
||
if (o.syncCaps && trailer[r] === 0x52 && trailer[r + 1] === 1) { o.ratchet = trailer[r + 2]; r += 3; } /* RATCH: max hits */
|
||
if (trailer[r] === 0x4C && trailer[r + 1] === 1) { o.locks = trailer[r + 2]; r += 3; } /* parameter locks (1.1): MOTION ops 5..7 */
|
||
if (trailer[r] === 0x56 && trailer[r + 1] === 1) o.fm6Bank = trailer[r + 2]; /* (0.6.11) the voice bank's size */
|
||
for (let k = r; k + 2 < trailer.length; k += 3) /* (0.8.5) 'O': the steps' lane modes */
|
||
if (trailer[k] === 0x4F && trailer[k + 1] === 1) { o.laneModes = trailer[k + 2]; break; }
|
||
}
|
||
/* (JIANT 0.8.5) 'Y' 1 n, the last tag: LYRIC (cmd 39), a track's lyric of at most n bytes; 0 = none */
|
||
const ty = trailer.length - 3;
|
||
o.lyric = ty >= 0 && trailer[ty] === 0x59 && trailer[ty + 1] === 1 ? trailer[ty + 2] : 0;
|
||
/* (SMK-37, ports/) just before 'Y': 'D' 1 board (none: an FM-1), 'H' 2 caps slots (a big CPU's engines) */
|
||
o.board = 0; o.hostPower = null;
|
||
if (o.lyric) {
|
||
let k = ty;
|
||
if (trailer[k - 4] === 0x48 && trailer[k - 3] === 2) {
|
||
const c = trailer[k - 2];
|
||
o.hostPower = { caps: c, slots: trailer[k - 1], sample: !!(c & 1), grain: !!(c & 2), drumSamples: !!(c & 4), extra: !!(c & 8) };
|
||
k -= 4;
|
||
}
|
||
if (trailer[k - 3] === 0x44 && trailer[k - 2] === 1) o.board = trailer[k - 1];
|
||
}
|
||
/* (V10.8.75, 1.5) 'E' 2 bytes depth, right before 'C' 2 1 minor: FORMULA (100), MATH USER's formulas; null = none */
|
||
o.formula = null;
|
||
for (let k = trailer.length - 7; k >= 4; k--)
|
||
if (trailer[k] === 0x43 && trailer[k + 1] === 2 && trailer[k + 2] === 1) {
|
||
if (trailer[k - 4] === 0x45 && trailer[k - 3] === 2) o.formula = { max: trailer[k - 2], depth: trailer[k - 1] };
|
||
break;
|
||
}
|
||
|
||
return o;
|
||
},
|
||
[CMD.LYRIC](a) { const r = new Reader(a); return { track: r.b(), rc: r.b(), text: r.s() }; },
|
||
[CMD.FORMULA](a) { const n = a[2] | 0; return { track: a[0], rc: a[1], code: FVM.unpack7(Array.from(a.slice(3))).slice(0, n), n }; }, /* (1.5) */
|
||
[CMD.UI_STATE](a) {
|
||
const r = new Reader(a), o = { caps: r.b(), palette: r.b(), font: r.b(), monitor: r.b(), filter: r.b() };
|
||
const u28 = () => r.b() | r.b() << 7 | r.b() << 14 | r.b() << 21;
|
||
o.favoriteSig = u28(); o.bankSig = u28(); return o;
|
||
},
|
||
[CMD.UI_SET](a) { const r = new Reader(a); return { rc: r.b(), id: r.b(), value: r.b(), ...parse[CMD.UI_STATE](a.slice(3)) }; },
|
||
[CMD.UI_PALETTES](a) { const r = new Reader(a), n = r.b(); return Array.from({ length: n }, () => r.s()); },
|
||
[CMD.FAV_GET](a) {
|
||
const r = new Reader(a), rc = r.b(); if (rc) return { rc };
|
||
const o = { rc, engine: r.b(), start: r.v(), count: r.b() };
|
||
o.values = Array.from({ length: o.count }, () => !!r.b()); return o;
|
||
},
|
||
[CMD.FAV_SET](a) {
|
||
const r = new Reader(a), rc = r.b();
|
||
return rc === 0 || rc === 3 || rc === 4 ? { rc, engine: r.b(), preset: r.v(), on: !!r.b() } : { rc };
|
||
},
|
||
[CMD.GET](a) { const r = new Reader(a); return { scope: r.b(), id: r.b(), value: r.v() }; },
|
||
[CMD.SET](a) { return parse[CMD.GET](a); },
|
||
/* needs the counts from INFO */
|
||
[CMD.DUMP](a, info) {
|
||
const r = new Reader(a);
|
||
const o = { engine: r.b(), preset: r.b(), p: [], g: [] };
|
||
for (let i = 0; i < info.pcount; i++) o.p.push(r.v());
|
||
for (let i = 0; i < info.gcount; i++) o.g.push(r.v());
|
||
return o;
|
||
},
|
||
[CMD.DESC](a) {
|
||
const r = new Reader(a);
|
||
const o = { scope: r.b(), id: r.b(), fmt: r.b(), min: r.v(), max: r.v(), def: r.v(), label: r.s(), unit: r.s(), names: [] };
|
||
if (o.fmt === F.ENUM) for (let i = 0; i <= o.max - o.min && i < 32; i++) o.names.push(r.s()); /* (0.7.0: 32, was 24) */
|
||
return o;
|
||
},
|
||
[CMD.STEP_GET](a) {
|
||
const r = new Reader(a);
|
||
const o = { index: r.b(), n: r.b(), notes: [r.b(), r.b(), r.b(), r.b()], time: r.b(), flags: r.b(), vel: r.b() };
|
||
return readHits(r, o);
|
||
},
|
||
[CMD.STEP_SET](a) { return parse[CMD.STEP_GET](a); },
|
||
[CMD.PRESET](a) { const r = new Reader(a); return { engine: r.b(), preset: r.b() }; },
|
||
[CMD.PROJECT](a) { const r = new Reader(a); return { op: r.b(), slot: r.b(), used: r.b() }; },
|
||
[CMD.SONG](a) {
|
||
const r = new Reader(a);
|
||
const o = { op: r.b(), rc: r.b(), count: r.b(), playing: r.b(), row: r.b(), remaining: r.b(), rows: [] };
|
||
for (let i = 0; i < o.count; i++) o.rows.push({ slot: r.b(), repeat: r.b() });
|
||
return o;
|
||
},
|
||
[CMD.MOTION](a) {
|
||
const r = new Reader(a), o = { track: r.b(), rc: r.b(), on: !!r.b(), count: r.b(), max: r.b(), events: [] };
|
||
if (o.count > o.max || o.max !== 64 || a.length !== 5 + o.count * 4) throw new Error("Invalid motion reply");
|
||
for (let i = 0; i < o.count; i++) o.events.push({ step: r.b(), param: r.b(), value: r.v() });
|
||
return o;
|
||
},
|
||
[CMD.NAMES](a) {
|
||
const r = new Reader(a);
|
||
const o = { engine: r.b(), names: [] };
|
||
const n = r.b();
|
||
for (let i = 0; i < n; i++) o.names.push(r.s());
|
||
o.titles = [];
|
||
try { o.titles.push(r.s(), r.s()); } catch (e) { o.titles = []; } /* older firmware: no page titles */
|
||
return o;
|
||
},
|
||
[CMD.UP_LIST](a) {
|
||
const r = new Reader(a);
|
||
const o = { start: r.b(), count: r.b(), total: r.b(), slots: [] };
|
||
for (let i = 0; i < o.count; i++) o.slots.push({ slot: o.start + i, used: r.b(), engine: r.b(), name: r.s() });
|
||
return o;
|
||
},
|
||
/* needs P_COUNT from INFO */
|
||
[CMD.UP_GET](a, info) {
|
||
const r = new Reader(a);
|
||
const o = { slot: r.b(), used: r.b(), engine: r.b(), name: r.s(), p: [], pattern: [] };
|
||
for (let i = 0; i < info.pcount; i++) o.p.push(r.v());
|
||
for (let i = 0; i < UP.PAT; i++) o.pattern.push([r.b(), r.b()]);
|
||
o.grid = null; /* v5: kind 1 = a drum grid (the pairs its low 7 bits), 16 x hi */
|
||
if (r.i < a.length && r.b() === 1 && r.i + UP.PAT <= a.length) {
|
||
o.grid = o.pattern.map(([h, c]) => { const x = r.b(), hit = h | (x & 1) << 7; return [hit, (c | (x & 2) << 6) & hit]; });
|
||
o.pattern = null;
|
||
}
|
||
return o;
|
||
},
|
||
[CMD.UP_PUT](a) { const r = new Reader(a); return { slot: r.b(), rc: r.b() }; },
|
||
[CMD.UP_STORE](a) { return parse[CMD.UP_PUT](a); },
|
||
[CMD.UP_LOAD](a) { return parse[CMD.UP_PUT](a); },
|
||
[CMD.UP_ERASE](a) { return parse[CMD.UP_PUT](a); },
|
||
[CMD.WATCH](a) { return { on: new Reader(a).b() }; },
|
||
[CMD.CHANGED](a) { return parse[CMD.GET](a); },
|
||
[CMD.RELOAD](a) { const r = new Reader(a); return { engine: r.b(), preset: r.b(), track: r.i < a.length ? r.b() : 0 }; },
|
||
[CMD.PING](a) { return {}; },
|
||
[CMD.STEP_CHANGED](a) { const r = new Reader(a); return { index: r.b(), track: r.i < a.length ? r.b() : 0 }; },
|
||
/* v3: tracks (1.0: four synth parts; earlier firmware: track 4 the drum part, engine byte NENGINES) */
|
||
[CMD.TRACK](a) {
|
||
const r = new Reader(a);
|
||
const o = { sel: r.b(), ntrk: r.b(), tracks: [] };
|
||
for (let i = 0; i < o.ntrk; i++) o.tracks.push({ engine: r.b(), preset: r.b(), level: r.v(), mute: r.b(), armed: r.b() });
|
||
return o;
|
||
},
|
||
[CMD.TRACK_MIX](a) { const r = new Reader(a); return { track: r.b(), level: r.v(), mute: r.b() }; },
|
||
[CMD.TRACK_DUMP](a, info) {
|
||
const r = new Reader(a);
|
||
const o = { track: r.b(), engine: r.b(), preset: r.b(), p: [] };
|
||
for (let i = 0; i < info.pcount; i++) o.p.push(r.v());
|
||
return o;
|
||
},
|
||
[CMD.TRACK_STEP](a) {
|
||
const r = new Reader(a);
|
||
return readHits(r, { track: r.b(), index: r.b(), n: r.b(), notes: [r.b(), r.b(), r.b(), r.b()], time: r.b(), flags: r.b(), vel: r.b() });
|
||
},
|
||
/* v4: a parameter of any track (the selection stays), and its push for a track that is not selected */
|
||
[CMD.TRACK_PARAM](a) { const r = new Reader(a); return { track: r.b(), id: r.b(), value: r.v() }; },
|
||
[CMD.TRACK_CHANGED](a) { return parse[CMD.TRACK_PARAM](a); },
|
||
/* FM6 patches: target 0 a track, 1 the bank (retired in 1.0.3: rc 3), 2 a factory patch, 3 a user preset's patch
|
||
(INFO fm6.caps bit 1); packed: the 128-byte record */
|
||
[CMD.FM6_GET](a) { return { target: a[0], index: a[1], rc: a[2], packed: a[2] ? null : a.slice(3, 3 + 128) }; },
|
||
[CMD.FM6_PUT](a) { return { target: a[0], index: a[1], rc: a[2] }; },
|
||
[CMD.FM6_LIST](a) {
|
||
const r = new Reader(a), o = { factory: r.b(), bank: r.b(), slots: [] };
|
||
for (let i = 0; i < o.factory + o.bank; i++) { const used = r.b(); o.slots.push({ used: !!used, name: r.s() }); }
|
||
return o;
|
||
},
|
||
[CMD.FM6_ERASE](a) { return { index: a[0], rc: a[1] }; },
|
||
/* (JIANT 0.6.11, Felucca 1.4.1) FM6's voice bank, EDITOR_PROTOCOL.md "FM6 voice bank (74-77)" */
|
||
[CMD.FM6B_BEGIN](a) { return { rc: a[0] }; },
|
||
[CMD.FM6B_WRITE](a) { return { index: a[0], rc: a[1] }; },
|
||
[CMD.FM6B_END](a) { return { rc: a[0], voices: a[1] }; },
|
||
[CMD.FM6B_LIST](a) {
|
||
const r = new Reader(a), o = { n: r.b(), valid: !!r.b(), name: r.s(), voices: [] };
|
||
for (let i = 0; i < o.n; i++) { const used = !!r.b(); o.voices.push({ used, name: r.s() }); }
|
||
return o;
|
||
},
|
||
};
|
||
|
||
/* (JIANT 0.8.5) a lyric the device takes: printable ASCII, at most 63 characters; accents dropped (the device has none:
|
||
stress is not marked in singing), the enye as "ny" (as the device reads it: sing.c sy_es) */
|
||
function lyricText(s) {
|
||
return String(s ?? "").replace(/[ñÑ]/g, (c) => (c === "ñ" ? "ny" : "NY")).normalize("NFD").replace(/[\u0300-\u036f]/g, "")
|
||
.replace(/[¿¡]/g, "").replace(/[^\x20-\x7E]/g, " ").slice(0, 63);
|
||
}
|
||
/* a name the device accepts: printable ASCII, 1..12 characters */
|
||
function upName(s) { return String(s ?? "").replace(/[^\x20-\x7E]/g, "").trim().slice(0, UP.NAME_MAX) || "PATCH"; }
|
||
|
||
const req = {
|
||
screen: (op) => [CMD.SCREEN, [op]], /* 0 query, 1 on (the whole screen), 2 keep on, 3 the whole screen again, 4 off */
|
||
uiState: () => [CMD.UI_STATE, []],
|
||
uiSet: (id, value) => [CMD.UI_SET, [id, value]],
|
||
uiPalettes: () => [CMD.UI_PALETTES, []],
|
||
favGet: (engine, start, count) => [CMD.FAV_GET, [engine, ...v14enc(start), count]],
|
||
favSet: (engine, preset, on) => [CMD.FAV_SET, [engine, ...v14enc(preset), on ? 1 : 0]],
|
||
lyric: (track, text) => [CMD.LYRIC, text == null ? [track] : [track, ...strEnc(lyricText(text))]], /* (0.8.5) */
|
||
formula: (track, op, code) => [CMD.FORMULA, [track & 0x7F, op, ...(op === 1 ? FVM.pack7(code) : [])]], /* (1.5) 0 query, 1 set, 2 clear */
|
||
info: () => [CMD.INFO, []],
|
||
get: (scope, id) => [CMD.GET, [scope, id]],
|
||
set: (scope, id, v) => [CMD.SET, [scope, id, ...v14enc(v)]],
|
||
dump: () => [CMD.DUMP, []],
|
||
desc: (scope, id) => [CMD.DESC, [scope, id]],
|
||
stepGet: (i, lanes) => [CMD.STEP_GET, lanes ? [i, 1] : [i]], /* (0.8.5: lanes, INFO 4F 01: the lanes' modes too) */
|
||
stepSet: (i, st) => {
|
||
const n = Math.max(0, Math.min(4, st.n | 0));
|
||
const notes = [0, 1, 2, 3].map((k) => (st.notes[k] | 0) & 0x7F);
|
||
return [CMD.STEP_SET, [i, n, ...notes, Math.max(0, Math.min(2, st.time | 0)), st.flags & 3, (st.vel | 0) & 0x7F,
|
||
...(st.hit == null && st.chance == null ? [] : hitsEnc(st.hit | 0, st.acc | 0)),
|
||
...(st.chance == null ? [] : [Math.max(0, Math.min(100, st.chance | 0))]),
|
||
...(st.chance == null || st.ratchet == null ? [] : [Math.max(1, Math.min(4, st.ratchet | 0))]), /* (only after the chance) */
|
||
...(st.chance == null || st.ratchet == null || !st.lanes ? [] : /* (0.8.5) the lanes' modes: only after the ratchet, */
|
||
Array.from({ length: 8 }, (_, l) => Math.max(0, Math.min(6, st.lanes[l] | 0))))]]; /* read from a device that has them */
|
||
},
|
||
preset: (e, p) => [CMD.PRESET, [e & 0x7F, p & 0x7F]],
|
||
project: (op, slot) => { if (![0, 1, 2].includes(op)) throw new Error("bad PROJECT op"); return [CMD.PROJECT, [op, slot & 3]]; }, /* 0 load, 1 save, 2 query */
|
||
song: (op = 0, rows = []) => {
|
||
if (![0, 1, 2, 3].includes(op) || rows.length > 16 || rows.some((r) => !Number.isInteger(r.slot) || r.slot < 0 || r.slot > 3 || !Number.isInteger(r.repeat) || r.repeat < 1 || r.repeat > 64)) throw new Error("bad SONG rows");
|
||
return [CMD.SONG, op === 1 ? [op, rows.length, ...rows.flatMap((r) => [r.slot, r.repeat])] : [op]];
|
||
},
|
||
motion: (track, op = 0, arg = {}) => {
|
||
if (!Number.isInteger(track) || track < 0 || track > 5 || ![0, 1, 2, 3, 4].includes(op)) throw new Error("Invalid motion request");
|
||
return [CMD.MOTION, [track, ...(op === 0 ? [] : op === 1 ? [op, arg.on ? 1 : 0] : op === 2 ? [op] :
|
||
[op, arg.step & 63, arg.param & 127, ...(op === 3 ? v14enc(arg.value) : [])])]];
|
||
},
|
||
names: (e) => [CMD.NAMES, [e & 0x7F]],
|
||
upList: (start, count) => [CMD.UP_LIST, [start & 0x7F, Math.max(1, Math.min(UP.LIST_MAX, count | 0))]],
|
||
upGet: (s) => [CMD.UP_GET, [s & 0x7F]],
|
||
/* patch: {engine, name, p: P_COUNT values, pattern: 16 x [note, flags] or grid: 16 x [hit, acc] (v5: kind 1)} */
|
||
upPut: (s, pt) => [CMD.UP_PUT, [s & 0x7F, pt.engine & 0x7F, ...strEnc(upName(pt.name)), ...pt.p.flatMap((v) => v14enc(v ?? 0)),
|
||
...(pt.grid
|
||
? [...Array.from({ length: UP.PAT }, (_, i) => hitsEnc(...(pt.grid[i] || [0, 0])).slice(0, 2)).flat(), 1,
|
||
...Array.from({ length: UP.PAT }, (_, i) => hitsEnc(...(pt.grid[i] || [0, 0]))[2])]
|
||
: Array.from({ length: UP.PAT }, (_, i) => { const x = (pt.pattern || [])[i] || [0, 0]; return [x[0] & 0x7F, x[1] & 7]; }).flat())]],
|
||
upStore: (s, name) => [CMD.UP_STORE, [s & 0x7F, ...strEnc(name ? upName(name) : "")]], /* "": the device names it ("ANALOG 07") */
|
||
upLoad: (s) => [CMD.UP_LOAD, [s & 0x7F]],
|
||
upErase: (s) => [CMD.UP_ERASE, [s & 0x7F]],
|
||
/* on: 1 = pushes; 3 = also TRACK_CHANGED (v4 firmware answers 3, older firmware 1) */
|
||
watch: (on) => [CMD.WATCH, [on === 3 ? 3 : on ? 1 : 0]],
|
||
ping: () => [CMD.PING, []],
|
||
/* v3: tracks 0..3 */
|
||
track: (sel) => [CMD.TRACK, sel == null ? [] : [sel & 0x7F]],
|
||
trackMix: (tr, level, mute) => [CMD.TRACK_MIX, level == null ? [tr & 0x7F] : [tr & 0x7F, ...v14enc(level), mute ? 1 : 0]],
|
||
trackDump: (tr) => [CMD.TRACK_DUMP, [tr & 0x7F]],
|
||
trackStep: (tr, i, st, lanes) => [CMD.TRACK_STEP, st ? [tr & 0x7F, ...req.stepSet(i, st)[1]] : lanes ? [tr & 0x7F, i & 0x7F, 1] : [tr & 0x7F, i & 0x7F]],
|
||
/* v4: get (v == null) or set parameter id (P_*) of track tr, clamped as SET */
|
||
trackParam: (tr, id, v) => [CMD.TRACK_PARAM, v == null ? [tr & 0x7F, id & 0x7F] : [tr & 0x7F, id & 0x7F, ...v14enc(v)]],
|
||
/* FM6 patches (firmware with info.fm6) */
|
||
fm6Get: (target, i) => [CMD.FM6_GET, [target & 0x7F, i & 0x7F]],
|
||
fm6Put: (target, i, packed) => [CMD.FM6_PUT, [target & 0x7F, i & 0x7F, ...packed.map((x) => x & 0x7F)]],
|
||
fm6List: () => [CMD.FM6_LIST, []],
|
||
fm6Erase: (i) => [CMD.FM6_ERASE, [i & 0x7F]],
|
||
/* (0.6.11) the voice bank: BEGIN, a WRITE per voice (index, the 128-byte record), END (name, the CRC of the records
|
||
written, in index order: 5 x 7 bits), LIST */
|
||
fm6bBegin: () => [CMD.FM6B_BEGIN, []],
|
||
fm6bWrite: (i, packed) => [CMD.FM6B_WRITE, [i & 0x7F, ...packed.map((x) => x & 0x7F)]],
|
||
fm6bEnd: (name, crc) => [CMD.FM6B_END, [...String(name ?? "").padEnd(10, " ").slice(0, 10)].map((c) => c.charCodeAt(0) & 0x7F)
|
||
.concat([0, 7, 14, 21, 28].map((sh) => (crc >>> sh) & 0x7F))],
|
||
fm6bList: () => [CMD.FM6B_LIST, []],
|
||
};
|
||
|
||
/* which reply belongs to which request (the device echoes these) */
|
||
function replyMatches(cmd, args, a) {
|
||
switch (cmd) {
|
||
case CMD.MOTION: return a[0] === args[0];
|
||
case CMD.BACKUP_GET: return a[0] === args[0] && a.slice(2, 7).every((v, i) => v === args[i + 1]);
|
||
case CMD.BACKUP_PUT: return a[0] === args[0] && a[1] === args[1];
|
||
case CMD.UI_SET: return a[1] === args[0] && a[2] === args[1];
|
||
case CMD.FAV_GET: case CMD.FAV_SET:
|
||
return ![0, 3, 4].includes(a[0]) || (a[1] === args[0] && a[2] === args[1] && a[3] === args[2] && a[4] === args[3]);
|
||
case CMD.LYRIC: return a[0] === args[0];
|
||
case CMD.FORMULA: return a[0] === args[0];
|
||
case CMD.SCREEN: return a[0] === args[0];
|
||
case CMD.GET: case CMD.SET: case CMD.DESC: return a[0] === args[0] && a[1] === args[1];
|
||
case CMD.STEP_GET: case CMD.STEP_SET: case CMD.NAMES: return a[0] === args[0];
|
||
case CMD.SONG: return a[0] === args[0];
|
||
case CMD.FM6_GET: case CMD.FM6_PUT: return a[0] === args[0] && a[1] === args[1];
|
||
case CMD.FM6_ERASE: return a[0] === args[0];
|
||
case CMD.FM6B_WRITE: return a[0] === args[0];
|
||
case CMD.PROJECT: return a[0] === args[0] && a[1] === args[1];
|
||
case CMD.UP_LIST: case CMD.UP_GET: case CMD.UP_PUT: case CMD.UP_STORE: case CMD.UP_LOAD: case CMD.UP_ERASE:
|
||
case CMD.TRACK_MIX: case CMD.TRACK_DUMP: return a[0] === args[0];
|
||
case CMD.WATCH: return (a[0] & 1) === (args[0] & 1); /* bit 1: v4 firmware only */
|
||
case CMD.TRACK_STEP: case CMD.TRACK_PARAM: return a[0] === args[0] && a[1] === args[1];
|
||
default: return true;
|
||
}
|
||
}
|
||
|
||
/* strict request/response: one frame in flight, the rest queued. Push frames (CHANGED, RELOAD,
|
||
STEP_CHANGED) can come at any time, also between a request and its reply: they go to onPush. */
|
||
class Link {
|
||
constructor(send, opts = {}) {
|
||
this.sendRaw = send;
|
||
this.q = [];
|
||
this.cur = null;
|
||
this.closed = false;
|
||
this.lastSent = 0; /* Date.now() of the last frame sent (WATCH keep-alive) */
|
||
this.timeout = opts.timeout || 300;
|
||
this.onUnknown = opts.onUnknown || (() => {});
|
||
this.onTimeout = opts.onTimeout || (() => {});
|
||
this.onPush = opts.onPush || (() => {});
|
||
this.onGap = opts.onGap || (() => {}); /* (ms) nothing was sent for that long (WATCH may have ended) */
|
||
}
|
||
get idle() { return !this.cur && !this.q.length; }
|
||
hasQueued(key) { return this.q.some((r) => r.key === key); }
|
||
/* r = [cmd, args]; opt: {timeout, retries, key (coalesce queued requests: the latest args win), front,
|
||
quiet (a timeout is expected: no onTimeout)} */
|
||
request(r, opt = {}) {
|
||
if (this.closed) return Promise.reject(new Error("closed"));
|
||
const [cmd, args] = r;
|
||
if (opt.key) {
|
||
const old = this.q.find((x) => x.key === opt.key);
|
||
if (old) { old.cmd = cmd; old.args = args; return old.promise; }
|
||
}
|
||
let res, rej;
|
||
const promise = new Promise((a, b) => { res = a; rej = b; });
|
||
const item = { cmd, args, key: opt.key, res, rej, promise, quiet: !!opt.quiet,
|
||
timeout: opt.timeout || this.timeout, retries: opt.retries ?? 1 };
|
||
if (opt.front) this.q.unshift(item); else this.q.push(item);
|
||
this.pump();
|
||
return promise;
|
||
}
|
||
pump() {
|
||
if (this.cur || this.closed || !this.q.length) return;
|
||
this.cur = this.q.shift();
|
||
this.fire();
|
||
}
|
||
fire() {
|
||
const c = this.cur;
|
||
const now = Date.now();
|
||
if (this.lastSent && now - this.lastSent > 2500) this.onGap(now - this.lastSent);
|
||
this.lastSent = now;
|
||
try { this.sendRaw(frame(c.cmd, c.args)); } catch (e) { this.finish(null, e); return; }
|
||
c.timer = setTimeout(() => {
|
||
if (this.cur !== c) return;
|
||
if (c.retries-- > 0) { this.fire(); return; }
|
||
if (!c.quiet) this.onTimeout(c.cmd);
|
||
this.finish(null, new Error("timeout (cmd " + c.cmd + ")"));
|
||
}, c.timeout);
|
||
}
|
||
finish(val, err) {
|
||
const c = this.cur;
|
||
if (!c) return;
|
||
clearTimeout(c.timer);
|
||
this.cur = null;
|
||
if (err) c.rej(err); else c.res(val);
|
||
this.pump();
|
||
}
|
||
/* raw incoming MIDI bytes */
|
||
receive(data) {
|
||
const f = unframe(data);
|
||
if (!f) return; /* not ours (notes, clock, other SysEx) */
|
||
if (PUSH.has(f.cmd)) { this.onPush(f); return; }
|
||
const c = this.cur;
|
||
if (!c || f.cmd !== c.cmd || !replyMatches(c.cmd, c.args, f.a)) { this.onUnknown(f); return; }
|
||
this.finish(f.a);
|
||
}
|
||
close() {
|
||
this.closed = true;
|
||
const all = (this.cur ? [this.cur] : []).concat(this.q);
|
||
if (this.cur) clearTimeout(this.cur.timer);
|
||
this.cur = null;
|
||
this.q = [];
|
||
for (const r of all) r.rej(new Error("closed"));
|
||
}
|
||
}
|
||
|
||
/* (SMK-37, ports/) the device that answers: INFO's 'D' tag, else (an FM-1, or SMK-37 firmware from before the tag)
|
||
the port's name */
|
||
const BOARDS = ["FM-1", "SMK-37 Pro", "SMK-37 Elite", "JIANT FM app / plugin", "MPC Sample", "MPC plugin"];
|
||
function deviceName(info, port) {
|
||
if (info && info.board && BOARDS[info.board]) return BOARDS[info.board];
|
||
const n = String(port || "");
|
||
if (/smk[ _-]*37/i.test(n)) return /elite/i.test(n) ? "SMK-37 Elite" : "SMK-37";
|
||
if (/mpc/i.test(n)) return "MPC";
|
||
return "FM-1";
|
||
}
|
||
/* the names an FM-1 shows under (the installer's fm1ota.js PORT_RE: JIANT, Felucca, Skiff, the stock firmware's, the
|
||
USB composite's, and the generic names Windows gives a USB MIDI device whose name it cached or never read) */
|
||
const editorPort = (p) => /felucca|jiant|skiff|fm[ _-]*1|smk[ _-]*37|mpc sample|m[ _-]*vave|cuvave|composite|sinco|usb[ _-]*midi|usb audio/i.test(p.name || "") && p.state !== "disconnected"; /* (SMK-37: "JIANT SMK-37"; the MPC Sample's gadget: "MPC Sample") */
|
||
/* (2026-10-30) never asked: software ports and other makers' synths a user is likely to have plugged in */
|
||
const notEditorPort = (p) => /wavetable|iac driver|midi through|loopmidi|loopbe|virtual|rtpmidi|network|bluetooth/i.test(p.name || "");
|
||
let seenPorts = "";
|
||
async function openEditorMidi(access, hooks = {}, selected = {}) {
|
||
const live = (ports) => [...ports.values()].filter(p => p.state !== "disconnected");
|
||
const select = (ports, id) => live(ports).filter(p => id ? p.id === id : editorPort(p));
|
||
let inputs = select(access.inputs, selected.input), outputs = select(access.outputs, selected.output);
|
||
seenPorts = [...new Set([...live(access.inputs), ...live(access.outputs)].map(p => p.name || p.id))].join(", ");
|
||
/* none under a name we know: every other port is asked (INFO, then the reply's "JIANT" / "FELUCCA" decides): a host
|
||
that shows the FM-1 under a name of its own still finds it */
|
||
if ((!inputs.length || !outputs.length) && !selected.input && !selected.output) {
|
||
inputs = live(access.inputs).filter(p => !notEditorPort(p));
|
||
outputs = live(access.outputs).filter(p => !notEditorPort(p));
|
||
}
|
||
if (!inputs.length || !outputs.length) throw new Error("no MIDI ports");
|
||
const pairs = inputs.flatMap(input => outputs.map(output => ({ input, output,
|
||
score: (input.name === output.name ? 2 : 0) + (input.manufacturer && input.manufacturer === output.manufacturer ? 1 : 0) })));
|
||
pairs.sort((a,b) => b.score-a.score);
|
||
let last;
|
||
for (const {input, output} of pairs) {
|
||
const link = new Link(d => output.send(d), { ...hooks, timeout: 600 });
|
||
try {
|
||
if (input.open) await input.open();
|
||
if (output.open) await output.open();
|
||
input.onmidimessage = e => link.receive(e.data);
|
||
const info = parse[CMD.INFO](await link.request(req.info(), { timeout: 800, retries: 2, quiet: true }));
|
||
if (!/^(?:JIANT|FELUCCA)\b/i.test(info.version || "")) throw new Error("Not a JIANT editor device");
|
||
return {input, output, link, info};
|
||
} catch (e) {
|
||
last = e; link.close(); input.onmidimessage = null;
|
||
await Promise.allSettled([input.close?.(), output.close?.()]);
|
||
}
|
||
}
|
||
throw last;
|
||
}
|
||
|
||
/* ------------------------------------------------------------- formatting --- */
|
||
const NOTE_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
|
||
const noteName = (n) => NOTE_NAMES[n % 12] + (Math.floor(n / 12) - 1); /* 60 = C4 */
|
||
/* a note token: a number or a note name (C4, F#3, Bb2) */
|
||
function parseNote(tok) {
|
||
if (/^\d+$/.test(tok)) { const n = +tok; return n <= 127 ? n : null; }
|
||
const m = /^([A-Ga-g])([#b]?)(-?\d)$/.exec(tok);
|
||
if (!m) return null;
|
||
const base = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 }[m[1].toUpperCase()];
|
||
const n = base + (m[2] === "#" ? 1 : m[2] === "b" ? -1 : 0) + (parseInt(m[3], 10) + 1) * 12;
|
||
return n >= 0 && n <= 127 ? n : null;
|
||
}
|
||
/* "C4 E4 G4" -> [60, 64, 67]; null on a bad token or more than 4 notes */
|
||
function parseNotes(s) {
|
||
const t = s.trim().split(/[\s,]+/).filter(Boolean);
|
||
if (t.length > 4) return null;
|
||
const out = t.map(parseNote);
|
||
return out.includes(null) ? null : out;
|
||
}
|
||
|
||
/* close to the device's param_format (params.c), tables from tools/gen_tables.py */
|
||
function fmtValue(d, v) {
|
||
const sign = (x) => (x > 0 ? "+" + x : String(x));
|
||
switch (d.fmt) {
|
||
case F.PCT: return [String(d.max === 100 || d.max === 120 ? v : Math.trunc((v * 100 + 63) / 127)), "%"]; /* 0..100 (SWG): the value */
|
||
case F.BIPCT: return [sign(Math.trunc(v * 100 / 64)), "%"];
|
||
case F.TIME: {
|
||
const ms10 = Math.round(10 * Math.pow(10000, (v & 127) / 127));
|
||
if (ms10 < 100) return [(ms10 / 10).toFixed(1), "ms"];
|
||
if (ms10 < 10000) return [String(Math.round(ms10 / 10)), "ms"];
|
||
return [(ms10 / 10000).toFixed(2), "s"];
|
||
}
|
||
case F.LFOHZ: {
|
||
if (v < 0) return [["4BAR", "2BAR", "1BAR", "1/2", "1/4", "1/8D", "1/4T", "1/8", "1/8T", "1/16", "1/16T", "1/32", "8BAR", "16BAR"][(-v - 1) % 14], ""]; /* (0.6.51) in time; V10.27: 8BAR 16BAR */
|
||
const h = 0.05 * Math.pow(800, (v & 127) / 127); return [h < 10 ? h.toFixed(2) : h.toFixed(1), "Hz"];
|
||
}
|
||
case F.CUTOFF: { const h = 30 * Math.pow(16000 / 30, (v & 127) / 127); return h < 1000 ? [String(Math.round(h)), "Hz"] : [(h / 1000).toFixed(1), "kHz"]; }
|
||
case F.DB: return v <= 0 ? ["OFF", ""] : [((v - 112) / 2).toFixed(1), "dB"];
|
||
case F.SEMI: return [sign(v), "st"];
|
||
case F.ENUM: return [d.names[v - d.min] ?? String(v), d.unit || ""];
|
||
case F.BPM: return [String(v), "BPM"];
|
||
case F.NOTE: return [NOTE_NAMES[((v % 12) + 12) % 12], ""];
|
||
case F.ONOFF: return [v ? "ON" : "OFF", ""];
|
||
case F.STEPS: return [String(v), "STEP"];
|
||
default: return d.label === "PHASE" && v < 0 ? ["FREE", ""] : [String(v), d.unit || ""]; /* (0.6.51) the LFO's PHASE */
|
||
}
|
||
}
|
||
|
||
/* -------------------------------------------------------------- librarian --- */
|
||
/* A patch (library entry, user preset):
|
||
{name, engine (index), engineName, p: [P_COUNT values by parameter id, null = unknown],
|
||
pattern: 16 x [note 0..127 (0 rest), flags 1 accent | 2 slide | 4 tie] or null,
|
||
grid: 16 x [lane hits 0..255, their accents] or null (a DRUM sound's 16 steps; then no pattern),
|
||
tags: [], created, modified}
|
||
|
||
Library / bank / single-patch file (JSON):
|
||
{
|
||
"format": "felucca-library", "version": 1,
|
||
"kind": "library" | "bank" | "patch",
|
||
"firmware": "FELUCCA 0.5 ...", device version string when exported ("" if unknown)
|
||
"pCount": 57, "pE0": 49, P_COUNT and the first engine parameter id
|
||
"paramLabels": ["LVL", "ATK", ...], one key per parameter id: the DESC label, "#2", "#3" appended to
|
||
a repeated label (PIT, PIT#2), and "E0".."E7" for the engine
|
||
parameters (their labels depend on the engine)
|
||
"engines": ["ANALOG", ...], engine names by index
|
||
"exported": "2026-10-03T12:00:00.000Z",
|
||
"patches": [{ "name", "engine", "engineName", "params": [pCount numbers or null],
|
||
"pattern": [[note, flags] x 16] or null, "grid": [[hits, accents] x 16] (when there is one),
|
||
"tags": [...], "created", "modified",
|
||
"slot": n (bank files only, 0-based) }]
|
||
}
|
||
Reading maps every parameter by its key, so a firmware with other ids (or more parameters) still gets
|
||
the right values; parameters the file does not have are null (left at the engine default). Engines are
|
||
matched by name. The old single-sound file ("felucca-patch" version 1, "Save to file") is read too. */
|
||
const LIB = { FORMAT: "felucca-library", VERSION: 1 };
|
||
|
||
/* parameter keys by id from the instrument DESCs */
|
||
function paramKeys(pdesc, pe0, pcount) {
|
||
const seen = {}, out = [];
|
||
for (let i = 0; i < pcount; i++) {
|
||
if (i >= pe0) { out.push("E" + (i - pe0)); continue; }
|
||
const l = (pdesc[i] && pdesc[i].label) || "P" + i;
|
||
seen[l] = (seen[l] || 0) + 1;
|
||
out.push(seen[l] > 1 ? `${l}#${seen[l]}` : l);
|
||
}
|
||
return out;
|
||
}
|
||
const sameKeys = (a, b) => !!a && !!b && a.length === b.length && a.every((k, i) => k === b[i]);
|
||
/* values by fromKeys -> values by toKeys (null where the source has no such key) */
|
||
/* (JIANT 0.6.24) the labels made readable (LVL -> LEVEL, SWG -> SWING, ...): a file's keys from before, renamed and
|
||
numbered again in their order, as paramKeys numbers today's */
|
||
const LEGACY_LABEL = { LVL: "LEVEL", FLT: "FILTER", PIT: "PITCH", SHP: "SHAPE", PHS: "PHASE", SWG: "SWING", ORD: "ORDER",
|
||
SCL: "SCALE", QNT: "QUANT", TRN: "TRANS", DST: "DIST", CHO: "CHORUS", VCE: "VOICE", GLD: "GLIDE", GLMOD: "MODE",
|
||
DPTH: "DEPTH", OFS: "OFFSET", DTUNE: "DETUNE", DST1: "DEST1", DST2: "DEST2", DST3: "DEST3", DST4: "DEST4" };
|
||
function legacyKeys(keys) {
|
||
if (!keys) return keys;
|
||
const seen = {};
|
||
return keys.map((k) => {
|
||
if (/^E[0-7]$/.test(k)) return k;
|
||
let b = String(k).split("#")[0];
|
||
b = LEGACY_LABEL[b] || b;
|
||
seen[b] = (seen[b] || 0) + 1;
|
||
return seen[b] > 1 ? `${b}#${seen[b]}` : b;
|
||
});
|
||
}
|
||
function remapParams(p, fromKeys, toKeys, pe0) {
|
||
if (!fromKeys && toKeys && pe0 && p.length !== toKeys.length) return tailParams(p, toKeys.length, pe0);
|
||
fromKeys = legacyKeys(fromKeys);
|
||
if (!fromKeys || !toKeys || sameKeys(fromKeys, toKeys)) return p.slice();
|
||
const at = new Map(fromKeys.map((k, i) => [k, i]));
|
||
return toKeys.map((k) => (at.has(k) ? p[at.get(k)] ?? null : null));
|
||
}
|
||
|
||
/* values without keys from another firmware: ids below its P_E0 kept their places, its last 8 are E0..E7
|
||
(common ids are only ever appended before P_E0); the rest stay null */
|
||
function tailParams(p, n, pe0) {
|
||
const out = Array(n).fill(null), common = Math.max(0, p.length - 8);
|
||
for (let i = 0; i < Math.min(common, pe0); i++) out[i] = p[i] ?? null;
|
||
for (let k = 0; k < 8 && common + k < p.length; k++) out[pe0 + k] = p[common + k] ?? null;
|
||
return out;
|
||
}
|
||
|
||
/* one pattern step as the firmware keeps it (up_pat_norm): a tie has no note, a rest no flags; flags 1 accent, 2 slide,
|
||
4 tie, 8 | 16 the ratchet - 1 (core.h SF_RATCH) */
|
||
const patNorm = (n, f) => (f & 4 ? [0, 4] : [n & 0x7F, n ? f & 27 : 0]);
|
||
/* sequencer steps (STEP_GET objects) -> 16-step pattern, as the firmware's UP_STORE does (up_pat_from):
|
||
the first note of a NOTE step, flag 4 for a TIE step */
|
||
function patternFromSteps(steps) {
|
||
return Array.from({ length: UP.PAT }, (_, i) => {
|
||
const s = steps[i];
|
||
if (!s) return [0, 0];
|
||
return patNorm(s.time === 0 && s.n ? s.notes[0] : 0, s.time === 1 ? 4 : (s.flags & 3) | ((s.ratchet || 1) - 1) << 3);
|
||
});
|
||
}
|
||
/* pattern -> 16 STEP_SET objects, as the firmware loads one (load_pat16; velocity 96); the ratchet is sent only with a
|
||
chance (req.stepSet) */
|
||
function stepsFromPattern(pat) {
|
||
return Array.from({ length: UP.PAT }, (_, i) => {
|
||
const [n, f] = (pat && pat[i]) || [0, 0];
|
||
return { n: n ? 1 : 0, notes: [n & 0x7F, 0, 0, 0], time: f & 4 ? 1 : n ? 0 : 2, flags: n ? f & 3 : 0, vel: n ? 96 : 0,
|
||
ratchet: n ? (f >> 3 & 3) + 1 : 1 };
|
||
});
|
||
}
|
||
const patternUsed = (pat) => !!pat && pat.some((x) => x && x[0]);
|
||
/* a DRUM track's first 16 steps -> a grid, as the firmware's UP_STORE stores one (its notes on their lanes) */
|
||
const gridFromSteps = (steps) => Array.from({ length: UP.PAT }, (_, i) => (steps[i] ? [stepLanes(steps[i]), stepAccents(steps[i])] : [0, 0]));
|
||
|
||
function cleanPatch(pt) {
|
||
const now = new Date().toISOString();
|
||
const pat = Array.isArray(pt.pattern) && pt.pattern.length
|
||
? Array.from({ length: UP.PAT }, (_, i) => { const x = pt.pattern[i]; return Array.isArray(x) ? patNorm(x[0] | 0, x[1] | 0) : [0, 0]; })
|
||
: null;
|
||
const grid = Array.isArray(pt.grid) && pt.grid.length
|
||
? Array.from({ length: UP.PAT }, (_, i) => { const x = pt.grid[i]; const h = Array.isArray(x) ? x[0] & 255 : 0; return [h, Array.isArray(x) ? x[1] & h : 0]; })
|
||
: null;
|
||
const o = {
|
||
name: String(pt.name ?? "PATCH").slice(0, 32) || "PATCH",
|
||
engine: pt.engine | 0, engineName: String(pt.engineName ?? ""),
|
||
p: Array.from(pt.p || pt.params || [], (v) => (Number.isFinite(v) ? Math.round(v) : null)),
|
||
pattern: patternUsed(grid) ? null : patternUsed(pat) ? pat : null,
|
||
grid: patternUsed(grid) ? grid : null,
|
||
tags: Array.isArray(pt.tags) ? [...new Set(pt.tags.map((x) => String(x).trim()).filter(Boolean))] : [],
|
||
created: pt.created || now, modified: pt.modified || pt.created || now,
|
||
};
|
||
if (Number.isInteger(pt.slot)) o.slot = pt.slot;
|
||
if (Array.isArray(pt.fm6) && pt.fm6.length === FM6.PACKED) o.fm6 = pt.fm6.map((x) => (x | 0) & 127); /* (a converted */
|
||
if (Array.isArray(pt.fm4)) o.fm4 = pt.fm4.map((v) => (Number.isFinite(v) ? Math.round(v) : null)); /* DIGITAL sound) */
|
||
return o;
|
||
}
|
||
|
||
/* ctx: {keys, engines, firmware, pe0} of the library (the device's when connected) */
|
||
function libraryFile(kind, patches, ctx) {
|
||
return {
|
||
format: LIB.FORMAT, version: LIB.VERSION, kind, firmware: ctx.firmware || "",
|
||
pCount: ctx.keys ? ctx.keys.length : 0, pE0: ctx.pe0 ?? null, paramLabels: ctx.keys || [], engines: ctx.engines || [],
|
||
exported: new Date().toISOString(),
|
||
patches: patches.map((x) => {
|
||
const c = cleanPatch(x);
|
||
const o = { name: c.name, engine: c.engine, engineName: c.engineName || (ctx.engines || [])[c.engine] || "",
|
||
params: c.p, pattern: c.pattern, tags: c.tags, created: c.created, modified: c.modified };
|
||
if (c.grid) o.grid = c.grid;
|
||
if (c.fm6) { o.fm6 = c.fm6; if (c.fm4) o.fm4 = c.fm4; } /* an FM6 sound's own patch (a DIGITAL sound converted: and
|
||
the DIGITAL values) */
|
||
if (Number.isInteger(x.slot)) o.slot = x.slot;
|
||
return o;
|
||
}),
|
||
};
|
||
}
|
||
/* -> {patches, skipped, keys (the file's, for a library that has none yet)}; throws on a file it cannot read.
|
||
A DIGITAL patch (the engine retired in 1.0) where ctx has no DIGITAL imports as FM6 (fromDigital); a SAMPLE PERC
|
||
one (the set retired after 1.0.2) as DRUM's kit (fromPerc) */
|
||
function readLibraryFile(obj, ctx) {
|
||
if (!obj || typeof obj !== "object") throw new Error("not JSON");
|
||
const noFm4 = !(ctx.engines || []).includes("DIGITAL");
|
||
const perc = (pt, pe0) => (pt && fromPerc(pt, ctx.engines, pe0)) || pt;
|
||
const fm4 = (pt, nm, pe0) => (nm === "DIGITAL" && noFm4 ? fromDigital(pt, ctx.engines, pe0) : perc(pt, pe0));
|
||
const engIndex = (name, idx, fileEngines) => {
|
||
const nm = name || (fileEngines || [])[idx];
|
||
if (ctx.engines && ctx.engines.length) {
|
||
if (nm === "SAMPLE" && ctx.engines.indexOf(nm) < 0) return 4; /* (JIANT: retired; its PERC sounds still become DRUM) */
|
||
if (nm) return ctx.engines.indexOf(nm);
|
||
return idx < ctx.engines.length ? idx : -1;
|
||
}
|
||
return idx;
|
||
};
|
||
if (obj.format === "felucca-patch") { /* "Save to file": the whole current sound */
|
||
if (!Array.isArray(obj.p) || !Number.isInteger(obj.engine)) throw new Error("felucca-patch without engine / p");
|
||
const digital = obj.engineName === "DIGITAL" && noFm4;
|
||
const e = digital ? 1 : engIndex(obj.engineName, obj.engine);
|
||
if (e < 0) return { patches: [], skipped: 1, keys: null };
|
||
const p = ctx.keys && ctx.pe0 && obj.p.length !== ctx.keys.length ? tailParams(obj.p, ctx.keys.length, ctx.pe0)
|
||
: obj.p.slice(0, ctx.keys ? ctx.keys.length : obj.p.length);
|
||
const pt = fm4({ name: obj.presetName || obj.engineName || "PATCH", engine: e, engineName: obj.engineName, p,
|
||
pattern: Array.isArray(obj.steps) ? patternFromSteps(obj.steps) : null, tags: ["file"] }, obj.engineName,
|
||
ctx.keys && ctx.pe0 ? ctx.pe0 : p.length - 8);
|
||
return pt ? { patches: [cleanPatch(pt)], skipped: 0, keys: null } : { patches: [], skipped: 1, keys: null };
|
||
}
|
||
if (obj.format !== LIB.FORMAT) throw new Error("unknown format");
|
||
if (!(obj.version >= 1)) throw new Error("version");
|
||
if (!Array.isArray(obj.patches)) throw new Error("no patches");
|
||
const fileKeys = Array.isArray(obj.paramLabels) && obj.paramLabels.length ? obj.paramLabels.map(String) : null;
|
||
const out = [];
|
||
let skipped = 0;
|
||
for (const x of obj.patches) {
|
||
if (!x || !Array.isArray(x.params)) { skipped++; continue; }
|
||
const nm = x.engineName || (obj.engines || [])[x.engine | 0];
|
||
const digital = nm === "DIGITAL" && noFm4;
|
||
const e = digital ? 1 : engIndex(x.engineName, x.engine | 0, obj.engines);
|
||
if (e < 0) { skipped++; continue; }
|
||
const p = remapParams(x.params, fileKeys, ctx.keys, ctx.pe0);
|
||
const pe0 = ctx.keys && ctx.pe0 ? ctx.pe0 : obj.pE0 ?? p.length - 8;
|
||
const pt = digital ? fromDigital({ ...x, engine: e, p }, ctx.engines, pe0)
|
||
: perc(cleanPatch({ ...x, engine: e, engineName: (ctx.engines || [])[e] || x.engineName || (obj.engines || [])[x.engine], p }), pe0);
|
||
if (!pt) { skipped++; continue; }
|
||
out.push(cleanPatch(pt));
|
||
}
|
||
return { patches: out, skipped, keys: fileKeys };
|
||
}
|
||
|
||
/* device side; rq(r, opt) -> reply args (Link.request), info from INFO */
|
||
const FLASH_OPT = { timeout: 2500, retries: 0 };
|
||
const presetPatches = (info) => !!(info && info.fm6 && info.fm6.caps & 2); /* user presets carry FM6 patches (1.0.3) */
|
||
/* zlib's CRC-32 (the voice bank's END: of the records written, in index order) */
|
||
function crc32(bytes, c = 0xFFFFFFFF) {
|
||
for (const x of bytes) { c ^= x; for (let k = 0; k < 8; k++) c = (c >>> 1) ^ (0xEDB88320 & -(c & 1)); }
|
||
return (c ^ 0xFFFFFFFF) >>> 0;
|
||
}
|
||
/* (JIANT 0.6.11, Felucca 1.4.1) FM6's voice bank on the device: 32 voices in flash, SLOT B1..B32 picks them. A 32-voice
|
||
.syx is sent whole (fm6_vbank.c: the old bank stays until END answers 0, a power cut leaves one or the other) */
|
||
const fm6Bank = {
|
||
N: 32,
|
||
/* the voices of an import ({name, v} or 155-byte voices; null: an empty slot) -> 128-byte records */
|
||
fromVoices: (voices) => Array.from({ length: Math.min(32, voices.length) }, (_, k) => {
|
||
const x = voices[k]; return x ? FM6.pack(x.v || x) : null;
|
||
}),
|
||
/* the bank's name from a file name: its base, capitals, printable ASCII, 10 at most */
|
||
nameOf: (file) => String(file ?? "").replace(/\.[^.]*$/, "").toUpperCase().replace(/[^\x20-\x7E]/g, " ").trim().slice(0, 10).trim(),
|
||
async list(rq) { return parse[CMD.FM6B_LIST](await rq(req.fm6bList())); },
|
||
/* packed: up to 32 records (null: not written, empty in the new bank) -> END's rc (0: the new bank is on the device) */
|
||
async send(rq, packed, name) {
|
||
let rc = parse[CMD.FM6B_BEGIN](await rq(req.fm6bBegin(), { timeout: 3000, retries: 0 })).rc; /* (no retries: a WRITE twice is rc 1) */
|
||
if (rc) return rc;
|
||
const done = [];
|
||
for (let k = 0; k < Math.min(32, packed.length); k++) {
|
||
if (!packed[k]) continue;
|
||
rc = parse[CMD.FM6B_WRITE](await rq(req.fm6bWrite(k, packed[k]), { timeout: 2000, retries: 0 })).rc;
|
||
if (rc) return rc;
|
||
done.push(...packed[k].map((x) => x & 0x7F));
|
||
}
|
||
return parse[CMD.FM6B_END](await rq(req.fm6bEnd(name, crc32(done)), { timeout: 5000, retries: 0 })).rc;
|
||
},
|
||
};
|
||
const bank = {
|
||
async list(rq) {
|
||
const first = parse[CMD.UP_LIST](await rq(req.upList(0, UP.LIST_MAX)));
|
||
const slots = first.slots.slice();
|
||
while (slots.length < first.total) {
|
||
const r = parse[CMD.UP_LIST](await rq(req.upList(slots.length, Math.min(UP.LIST_MAX, first.total - slots.length))));
|
||
if (!r.count) break;
|
||
slots.push(...r.slots);
|
||
}
|
||
return { total: first.total, slots };
|
||
},
|
||
/* an FM6 sound's own patch comes with it (fm6: packed) where the firmware keeps one (INFO fm6.caps bit 1) */
|
||
async get(rq, info, slot) {
|
||
const u = parse[CMD.UP_GET](await rq(req.upGet(slot)), info);
|
||
if (u.used && presetPatches(info) && info.engines[u.engine] === "FM6") {
|
||
const g = parse[CMD.FM6_GET](await rq(req.fm6Get(FM6.TARGET.USER, slot)));
|
||
if (!g.rc) u.fm6 = g.packed;
|
||
}
|
||
return u;
|
||
},
|
||
/* -> rc (0 ok); with info, an FM6 sound's patch (pt.fm6) goes with it */
|
||
async put(rq, slot, pt, info) {
|
||
const rc = parse[CMD.UP_PUT](await rq(req.upPut(slot, pt), FLASH_OPT)).rc;
|
||
if (rc || !pt.fm6 || !presetPatches(info) || info.engines[pt.engine] !== "FM6") return rc;
|
||
return parse[CMD.FM6_PUT](await rq(req.fm6Put(FM6.TARGET.USER, slot, pt.fm6), FLASH_OPT)).rc;
|
||
},
|
||
async store(rq, slot, name) { return parse[CMD.UP_STORE](await rq(req.upStore(slot, name), FLASH_OPT)).rc; },
|
||
async load(rq, slot) { return parse[CMD.UP_LOAD](await rq(req.upLoad(slot), { timeout: 1000 })).rc; },
|
||
async erase(rq, slot) { return parse[CMD.UP_ERASE](await rq(req.upErase(slot), FLASH_OPT)).rc; },
|
||
};
|
||
|
||
/* the current sound: DUMP + the first 16 steps */
|
||
async function capturePatch(rq, info, name) {
|
||
const dump = parse[CMD.DUMP](await rq(req.dump()), info);
|
||
const steps = [];
|
||
for (let i = 0; i < UP.PAT && i < info.nstep; i++) steps.push(parse[CMD.STEP_GET](await rq(req.stepGet(i))));
|
||
const drum = info.engines[dump.engine] === "DRUM"; /* (a DRUM track that strikes a lane: its grid) */
|
||
let fm6 = null; /* an FM6 track: its own patch (the selected track's) */
|
||
if (info.fm6 && info.engines[dump.engine] === "FM6") {
|
||
const sel = info.ntrk ? parse[CMD.TRACK](await rq(req.track())).sel : 0;
|
||
const g = parse[CMD.FM6_GET](await rq(req.fm6Get(FM6.TARGET.TRACK, sel)));
|
||
if (!g.rc) fm6 = g.packed;
|
||
}
|
||
return { patch: cleanPatch({ name, engine: dump.engine, engineName: info.engines[dump.engine], p: dump.p, pattern: patternFromSteps(steps),
|
||
grid: drum ? gridFromSteps(steps) : null, fm6 }), dump, steps };
|
||
}
|
||
|
||
/* the track's own parameters, which no sound load changes (ui.c param_kept): LEVEL, the ARP and ARP 2 pages,
|
||
SCL, LEN DIV SWING GATE (17..32), PAN, MUTE, the SLICER (45..48); with P_E0 83 the SHIFT offsets OFS PIT (81, 82,
|
||
once the chord keys CHRD VOIC; E0 E1 of the 89-parameter firmware) */
|
||
const TRACK_OWN = new Set([0, 39, 40, ...Array.from({ length: 16 }, (_, i) => 17 + i), 45, 46, 47, 48]);
|
||
const P_SHIFT = [81, 82]; /* core.h P_SOFS, P_POFS (since P_COUNT 91, P_E0 83; the chord keys before JIANT) */
|
||
const P_LANES = [83, 84, 85, 86, 87, 88, 89, 90]; /* core.h P_LN0..P_LN7: the DRUM lane levels (since P_COUNT 99, P_E0 91) */
|
||
const trackOwn = (i, pe0) => TRACK_OWN.has(i) || (pe0 >= 83 && P_SHIFT.includes(i));
|
||
/* play a patch without writing flash, as UP_LOAD would load it: the sound only. SET the engine (G_ENGSEL:
|
||
engine defaults and its first preset), then every instrument parameter that differs, except the track's
|
||
own (TRACK_OWN). The steps are never touched. The device keeps a copy of the sound from before (SAVE held
|
||
there = undo) and treats the SETs right after G_ENGSEL as part of this load (EDITOR_PROTOCOL.md "undo").
|
||
opt: {gEng: G_ENGSEL id, progress(i, n)} */
|
||
async function auditionPatch(rq, info, pt, opt = {}) {
|
||
await rq(req.set(1, opt.gEng ?? 20, pt.engine));
|
||
const dump = parse[CMD.DUMP](await rq(req.dump()), info);
|
||
const n = Math.min(info.pcount, pt.p.length);
|
||
for (let i = 0; i < n; i++) {
|
||
const v = pt.p[i];
|
||
if (opt.progress) opt.progress(i, n);
|
||
if (v == null || v === dump.p[i] || trackOwn(i, info.pe0)) continue;
|
||
await rq(req.set(0, i, v));
|
||
}
|
||
if (pt.fm6 && info.fm6) /* a converted DIGITAL sound: its own FM6 patch on the track */
|
||
await rq(req.fm6Put(FM6.TARGET.TRACK, opt.track ?? 0, pt.fm6));
|
||
return {};
|
||
}
|
||
|
||
/* WATCH on (asking for TRACK_CHANGED too): false when the firmware does not know it (older than protocol v2),
|
||
else 1, or 3 when it also has TRACK_PARAM / TRACK_CHANGED (protocol v4) */
|
||
async function startWatch(rq) {
|
||
try { const on = parse[CMD.WATCH](await rq(req.watch(3), { timeout: 300, retries: 1, quiet: true })).on; return on & 1 ? on & 3 : false; }
|
||
catch (e) { if (e.message === "closed") throw e; return false; }
|
||
}
|
||
|
||
/* ------------------------------------------------------------ mixer (v3) --- */
|
||
/* The TRACKS page in the editor: TRACK (engine, preset, level, mute, armed of all four) and TRACK_DUMP
|
||
of each track for its P_PAN. Level and mute go through TRACK_MIX (any track). Pan: TRACK_PARAM (v4, any track); with v3 firmware a plain SET, which reaches only the
|
||
selected track: another track is selected for it and the selection is put back (TRACK pushes no
|
||
RELOAD). ids: {pan: P_PAN id} */
|
||
const mixer = {
|
||
async read(rq, info, ids) {
|
||
const tr = parse[CMD.TRACK](await rq(req.track()));
|
||
for (let i = 0; i < tr.ntrk; i++) {
|
||
const d = parse[CMD.TRACK_DUMP](await rq(req.trackDump(i)), info);
|
||
tr.tracks[i].pan = ids.pan == null ? null : d.p[ids.pan];
|
||
}
|
||
return tr;
|
||
},
|
||
/* -> {track, level, mute} as the device has them now */
|
||
async setMix(rq, track, level, mute, opt) { return parse[CMD.TRACK_MIX](await rq(req.trackMix(track, level, mute), opt)); },
|
||
/* -> the pan value after clamping. v4: TRACK_PARAM, the selection stays */
|
||
async setPan(rq, track, sel, panId, v, v4) {
|
||
if (v4) return parse[CMD.TRACK_PARAM](await rq(req.trackParam(track, panId, v), { key: "pan:" + track })).value;
|
||
if (track === sel) return parse[CMD.SET](await rq(req.set(0, panId, v))).value;
|
||
await rq(req.track(track));
|
||
try { return parse[CMD.SET](await rq(req.set(0, panId, v))).value; }
|
||
finally { await rq(req.track(sel)).catch(() => {}); }
|
||
},
|
||
};
|
||
|
||
/* ------------------------------------------------------------ mock device --- */
|
||
/* Implements the protocol like firmware/src/editor.c, with tables copied from params.c
|
||
and the engine sources (test_web.mjs checks them against the firmware's, tests/descdump.c). Used with ?mock=1 (add &legacy=1 for a firmware without cmds 16..26).
|
||
opt: {legacy: no user bank / WATCH, v3: no TRACK_PARAM / TRACK_CHANGED (firmware 0.8),
|
||
auto: false = no simulated knobs (tests drive sim.*),
|
||
watchMs: how long WATCH lasts after the last request (3000), slots: user bank size (32)} */
|
||
/* ------------------------------------------------------------------- FM6 --- */
|
||
/* The FM6 engine's patches (eng_fm6.c, EDITOR_PROTOCOL.md "FM6 patches"): the generic 6-operator voice.
|
||
voice: 155 bytes, 6 x 21 operator bytes (the sixth operator first, as the format has them), then 19 voice bytes
|
||
and a 10-character name. packed: the 128-byte record of a 32-voice bank (every byte 7-bit). SysEx files: a
|
||
single voice (F0 43 0n 00 01 1B, 155 bytes, checksum, F7: 163 bytes) or 32 packed voices (F0 43 0n 09 20 00,
|
||
4096 bytes, checksum, F7: 4104 bytes); parseSysex also reads the variants real files have (see there). */
|
||
const FM6 = (() => {
|
||
/* per operator byte: name, highest value; then the voice bytes */
|
||
const OP = [["R1", 99], ["R2", 99], ["R3", 99], ["R4", 99], ["L1", 99], ["L2", 99], ["L3", 99], ["L4", 99],
|
||
["BP", 99], ["LD", 99], ["RD", 99], ["LC", 3], ["RC", 3], ["RS", 7], ["AMS", 3], ["KVS", 7], ["OL", 99],
|
||
["MODE", 1], ["FC", 31], ["FF", 99], ["DET", 14]];
|
||
const VOICE = [["PR1", 99], ["PR2", 99], ["PR3", 99], ["PR4", 99], ["PL1", 99], ["PL2", 99], ["PL3", 99], ["PL4", 99],
|
||
["ALG", 31], ["FB", 7], ["OKS", 1], ["LFS", 99], ["LFD", 99], ["LPMD", 99], ["LAMD", 99], ["LKS", 1], ["LFW", 5],
|
||
["LPMS", 7], ["TRNSP", 48]];
|
||
const OPI = Object.fromEntries(OP.map(([n], i) => [n, i])), VI = Object.fromEntries(VOICE.map(([n], i) => [n, 126 + i]));
|
||
const NAME = 145, SIZE = 155, PACKED = 128;
|
||
const max = (i) => (i < 126 ? OP[i % 21][1] : i < NAME ? VOICE[i - 126][1] : 126);
|
||
/* byte i of operator n (1..6) */
|
||
const at = (n, field) => (6 - n) * 21 + OPI[field];
|
||
function sanitize(v) {
|
||
const o = Uint8Array.from(v.slice(0, SIZE));
|
||
for (let i = 0; i < SIZE; i++) o[i] = i >= NAME ? (o[i] < 32 || o[i] > 126 ? 32 : o[i]) : Math.min(o[i], max(i));
|
||
return o;
|
||
}
|
||
function unpack(b) { /* eng_fm6.c fm6_unpack */
|
||
const v = new Uint8Array(SIZE);
|
||
for (let k = 0; k < 6; k++) {
|
||
const o = k * 17, d = k * 21;
|
||
for (let i = 0; i < 11; i++) v[d + i] = b[o + i] & 127;
|
||
v[d + 11] = b[o + 11] & 3; v[d + 12] = b[o + 11] >> 2 & 3; v[d + 13] = b[o + 12] & 7; v[d + 20] = b[o + 12] >> 3 & 15;
|
||
v[d + 14] = b[o + 13] & 3; v[d + 15] = b[o + 13] >> 2 & 7; v[d + 16] = b[o + 14] & 127; v[d + 17] = b[o + 15] & 1;
|
||
v[d + 18] = b[o + 15] >> 1 & 31; v[d + 19] = b[o + 16] & 127;
|
||
}
|
||
for (let i = 0; i < 9; i++) v[126 + i] = b[102 + i] & 127;
|
||
v[134] &= 31; v[135] = b[111] & 7; v[136] = b[111] >> 3 & 1;
|
||
for (let i = 0; i < 4; i++) v[137 + i] = b[112 + i] & 127;
|
||
v[141] = b[116] & 1; v[142] = b[116] >> 1 & 7; v[143] = b[116] >> 4 & 7; v[144] = b[117] & 127;
|
||
for (let i = 0; i < 10; i++) v[NAME + i] = b[118 + i] & 127;
|
||
return sanitize(v);
|
||
}
|
||
function pack(v) { /* eng_fm6.c fm6_pack */
|
||
const b = new Array(PACKED).fill(0);
|
||
for (let k = 0; k < 6; k++) {
|
||
const o = k * 17, d = k * 21;
|
||
for (let i = 0; i < 11; i++) b[o + i] = v[d + i] & 127;
|
||
b[o + 11] = (v[d + 11] & 3) | (v[d + 12] & 3) << 2; b[o + 12] = (v[d + 13] & 7) | (v[d + 20] & 15) << 3;
|
||
b[o + 13] = (v[d + 14] & 3) | (v[d + 15] & 7) << 2; b[o + 14] = v[d + 16] & 127;
|
||
b[o + 15] = (v[d + 17] & 1) | (v[d + 18] & 31) << 1; b[o + 16] = v[d + 19] & 127;
|
||
}
|
||
for (let i = 0; i < 9; i++) b[102 + i] = v[126 + i] & 127;
|
||
b[110] &= 31; b[111] = (v[135] & 7) | (v[136] & 1) << 3;
|
||
for (let i = 0; i < 4; i++) b[112 + i] = v[137 + i] & 127;
|
||
b[116] = (v[141] & 1) | (v[142] & 7) << 1 | (v[143] & 7) << 4; b[117] = v[144] & 127;
|
||
for (let i = 0; i < 10; i++) b[118 + i] = v[NAME + i] & 127;
|
||
return b;
|
||
}
|
||
const name = (v) => String.fromCharCode(...v.slice(NAME, NAME + 10)).replace(/\s+$/, "");
|
||
function setName(v, s) {
|
||
const t = String(s).toUpperCase().replace(/[^\x20-\x7E]/g, " ").slice(0, 10).padEnd(10, " ");
|
||
for (let i = 0; i < 10; i++) v[NAME + i] = t.charCodeAt(i);
|
||
return v;
|
||
}
|
||
const checksum = (a) => (128 - (a.reduce((s, x) => s + x, 0) & 127)) & 127;
|
||
/* every voice in a file's bytes, tolerant of what real files have:
|
||
- SysEx F0 43 0n 00 xx xx (one voice, 155 bytes) and F0 43 0n 09 xx xx (32 packed voices, 4096 bytes): the byte
|
||
count is not checked (some tools write 09 10 00, i.e. 0x1000 as two plain bytes); the payload is taken right
|
||
after the 6-byte header whatever follows it: a checksum or not, F7 or not, a stray byte, the next F0;
|
||
a message cut short (EOF, or a byte >= 0x80 inside it) keeps its whole voices (the name may be cut: blanks);
|
||
- several messages in one file, junk before / between / after them;
|
||
- the format's other blocks (manufacturer 43h: supplements, performances, 4-operator voices, universal "LM ..." blocks) and other
|
||
makers' messages are skipped and counted;
|
||
- raw data without SysEx: 4096 x n bytes (banks), 155 (one voice) or 128 bytes (one packed voice).
|
||
-> {voices: [{name, v}], badSum: messages with a wrong checksum (still read), short: messages cut short,
|
||
skipped: other messages, kinds: what the skipped ones were ("fm4" 4-operator voices, "other43" the format's other
|
||
blocks, "universal", "maker:XX" another manufacturer id), sysex: F0 seen} */
|
||
function parseSysex(bytes) {
|
||
const d = Uint8Array.from(bytes), voices = [], kinds = [];
|
||
let badSum = 0, short = 0, skipped = 0;
|
||
const add = (v) => voices.push({ v, name: name(v) });
|
||
const kind = (k) => { skipped++; if (!kinds.includes(k)) kinds.push(k); };
|
||
const sysex = d.includes(0xF0);
|
||
if (d[0] !== 0xF0 && !sysex) {
|
||
if (d.length && d.length % 4096 === 0) {
|
||
for (let o = 0; o < d.length; o += 128) add(unpack(d.subarray(o, o + 128)));
|
||
} else if (d.length === SIZE) add(sanitize(d));
|
||
else if (d.length === PACKED) add(unpack(d));
|
||
return { voices, badSum, short, skipped, kinds, sysex };
|
||
}
|
||
for (let i = 0; i < d.length; i++) {
|
||
if (d[i] !== 0xF0) continue;
|
||
const id = d[i + 1], st = d[i + 2], f = d[i + 3];
|
||
if (id === 0x43 && st !== undefined && (st & 0xF0) === 0 && (f === 0 || f === 9) && i + 6 <= d.length) {
|
||
const want = f === 0 ? SIZE : 4096, s = i + 6;
|
||
let e = s;
|
||
while (e < d.length && e < s + want && d[e] < 0x80) e++;
|
||
const data = d.subarray(s, e);
|
||
if (data.length < want) short++;
|
||
else if (e < d.length && d[e] < 0x80 && checksum(data) !== d[e]) badSum++;
|
||
if (f === 0) {
|
||
if (data.length >= NAME) { const v = new Uint8Array(SIZE); v.set(data); add(sanitize(v)); }
|
||
} else {
|
||
for (let o = 0; o + 118 <= data.length; o += 128) { /* whole voices, and one cut in its name (at 118) */
|
||
const pk = new Uint8Array(128); pk.set(data.subarray(o, o + 128)); add(unpack(pk));
|
||
}
|
||
}
|
||
i = e - 1; /* on to the next F0 (the checksum, F7, junk are passed over) */
|
||
continue;
|
||
}
|
||
if (id === 0x43) kind(f === 3 || f === 4 ? "fm4" : "other43");
|
||
else if (id === 0x7E || id === 0x7F) kind("universal");
|
||
else if (id !== undefined && id < 0x80) kind("maker:" + (id === 0 ? [0, d[i + 2], d[i + 3]] : [id])
|
||
.map((x) => (x ?? 0).toString(16).toUpperCase().padStart(2, "0")).join(" "));
|
||
}
|
||
return { voices, badSum, short, skipped, kinds, sysex };
|
||
}
|
||
function singleSysex(v, ch = 0) {
|
||
const data = Array.from(sanitize(v));
|
||
return Uint8Array.from([0xF0, 0x43, ch & 15, 0, 0x01, 0x1B, ...data, checksum(data), 0xF7]);
|
||
}
|
||
function bankSysex(voices, ch = 0) { /* up to 32 voices (155 bytes each), the rest the init voice */
|
||
const data = [];
|
||
for (let k = 0; k < 32; k++) data.push(...(voices[k] ? pack(voices[k]) : INIT_PK));
|
||
return Uint8Array.from([0xF0, 0x43, ch & 15, 9, 0x20, 0, ...data, checksum(data), 0xF7]);
|
||
}
|
||
/* the 32 algorithms (msfa's tables; fm6_core.c FM6_ALG): per operator, the sixth first */
|
||
const ALG = [[0xc1, 0x11, 0x11, 0x14, 0x01, 0x14], [0x01, 0x11, 0x11, 0x14, 0xc1, 0x14], [0xc1, 0x11, 0x14, 0x01, 0x11, 0x14],
|
||
[0xc1, 0x11, 0x94, 0x01, 0x11, 0x14], [0xc1, 0x14, 0x01, 0x14, 0x01, 0x14], [0xc1, 0x94, 0x01, 0x14, 0x01, 0x14],
|
||
[0xc1, 0x11, 0x05, 0x14, 0x01, 0x14], [0x01, 0x11, 0xc5, 0x14, 0x01, 0x14], [0x01, 0x11, 0x05, 0x14, 0xc1, 0x14],
|
||
[0x01, 0x05, 0x14, 0xc1, 0x11, 0x14], [0xc1, 0x05, 0x14, 0x01, 0x11, 0x14], [0x01, 0x05, 0x05, 0x14, 0xc1, 0x14],
|
||
[0xc1, 0x05, 0x05, 0x14, 0x01, 0x14], [0xc1, 0x05, 0x11, 0x14, 0x01, 0x14], [0x01, 0x05, 0x11, 0x14, 0xc1, 0x14],
|
||
[0xc1, 0x11, 0x02, 0x25, 0x05, 0x14], [0x01, 0x11, 0x02, 0x25, 0xc5, 0x14], [0x01, 0x11, 0x11, 0xc5, 0x05, 0x14],
|
||
[0xc1, 0x14, 0x14, 0x01, 0x11, 0x14], [0x01, 0x05, 0x14, 0xc1, 0x14, 0x14], [0x01, 0x14, 0x14, 0xc1, 0x14, 0x14],
|
||
[0xc1, 0x14, 0x14, 0x14, 0x01, 0x14], [0xc1, 0x14, 0x14, 0x01, 0x14, 0x04], [0xc1, 0x14, 0x14, 0x14, 0x04, 0x04],
|
||
[0xc1, 0x14, 0x14, 0x04, 0x04, 0x04], [0xc1, 0x05, 0x14, 0x01, 0x14, 0x04], [0x01, 0x05, 0x14, 0xc1, 0x14, 0x04],
|
||
[0x04, 0xc1, 0x11, 0x14, 0x01, 0x14], [0xc1, 0x14, 0x01, 0x14, 0x04, 0x04], [0x04, 0xc1, 0x11, 0x14, 0x04, 0x04],
|
||
[0xc1, 0x14, 0x04, 0x04, 0x04, 0x04], [0xc4, 0x04, 0x04, 0x04, 0x04, 0x04]];
|
||
/* operators 1..6 that are carriers (on the output bus), and the one with the feedback, of algorithm a (0..31) */
|
||
const carriers = (a) => [1, 2, 3, 4, 5, 6].filter((n) => !(ALG[a & 31][6 - n] & 3));
|
||
const feedbackOp = (a) => [1, 2, 3, 4, 5, 6].find((n) => (ALG[a & 31][6 - n] & 0xc0) === 0xc0);
|
||
/* an operator's frequency as text: x ratio, or Hz for a fixed one (msfa note osc_freq) */
|
||
function freqText(v, n) {
|
||
const fc = v[at(n, "FC")], ff = v[at(n, "FF")];
|
||
if (v[at(n, "MODE")]) return (10 ** ((fc & 3) + ff / 100)).toPrecision(4) + " Hz";
|
||
return "x" + ((fc ? fc : 0.5) * (1 + ff / 100)).toFixed(2);
|
||
}
|
||
const INIT_PK = [99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,99,99,99,99,99,99,0,39,0,0,0,56,0,99,2,0,99,99,99,99,50,50,50,50,0,8,35,0,0,0,49,24,73,78,73,84,32,86,79,73,67,69];
|
||
const FACTORY_PK = [
|
||
[95,40,30,60,99,80,0,0,39,0,0,0,56,12,52,2,0,95,30,20,60,99,90,0,0,39,0,0,0,48,4,78,2,0,97,62,40,60,99,60,0,0,39,0,0,0,59,24,68,28,0,95,20,20,50,99,95,0,0,39,0,0,0,66,8,90,2,0,95,50,35,78,99,75,0,0,39,0,0,0,59,28,58,2,0,96,25,25,67,99,75,0,0,39,0,0,0,59,8,98,2,0,99,99,99,99,50,50,50,50,4,11,34,33,0,0,41,24,84,73,78,69,32,69,80,32,32,32], /* TINE EP */
|
||
[99,60,40,45,99,50,0,0,39,0,0,0,56,0,60,2,0,99,60,40,45,99,50,0,0,39,0,0,0,40,0,78,10,40,99,50,30,40,99,60,0,0,39,0,0,0,56,12,70,10,0,99,45,30,40,99,70,0,0,39,0,0,0,72,4,84,4,38,99,35,25,35,99,70,0,0,39,0,0,0,56,12,78,6,50,99,40,25,35,99,80,0,0,39,0,0,0,56,4,96,2,0,99,99,99,99,50,50,50,50,4,8,35,0,0,0,1,24,71,76,65,83,83,32,66,69,76,76], /* BELL */
|
||
[99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,72,50,75,99,65,40,0,39,0,0,0,56,24,78,4,0,99,55,40,75,99,70,50,0,39,0,0,0,64,4,80,2,0,99,60,40,75,99,72,55,0,39,0,0,0,56,20,80,2,0,99,40,30,75,99,85,70,0,39,0,0,0,56,8,99,2,0,99,99,99,99,50,50,50,50,4,8,35,0,0,0,1,24,82,79,85,78,68,32,66,65,83,83], /* FM BASS */
|
||
[52,50,40,60,99,85,82,0,39,0,0,0,56,8,72,2,0,62,50,40,60,99,92,90,0,39,0,0,0,40,4,88,2,0,50,50,40,60,99,88,85,0,39,0,0,0,56,12,78,2,0,62,50,40,60,99,92,90,0,39,0,0,0,72,4,92,2,0,55,50,40,60,99,88,85,0,39,0,0,0,56,12,80,2,0,65,50,40,60,99,92,90,0,39,0,0,0,56,4,98,2,0,80,60,99,60,46,50,50,50,4,13,33,50,6,0,57,24,66,82,65,83,83,32,83,69,67,84], /* BRASS */
|
||
[35,30,40,40,85,90,85,0,39,0,0,0,56,0,50,2,0,38,30,40,40,99,95,90,0,39,0,0,0,56,0,80,4,0,30,25,40,40,80,90,85,0,39,0,0,0,56,4,55,4,0,40,30,40,40,99,95,90,0,39,0,0,0,80,0,92,2,0,35,30,40,40,85,90,80,0,39,0,0,0,56,4,60,2,0,40,30,40,40,99,95,90,0,39,0,0,0,40,0,92,2,0,99,99,99,99,50,50,50,50,4,10,30,60,4,0,41,24,83,79,70,84,32,80,65,68,32,32], /* PAD */
|
||
[99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,80,50,60,99,0,0,0,39,0,0,0,59,12,45,2,0,99,70,50,60,99,0,0,0,39,0,0,0,59,12,72,8,0,99,75,50,60,99,0,0,0,39,0,0,0,59,20,70,8,0,99,52,40,55,99,0,0,0,39,0,0,0,58,8,99,2,0,99,99,99,99,50,50,50,50,4,8,35,0,0,0,1,24,87,79,79,68,32,66,65,82,83,32], /* MARIMBA */
|
||
[99,99,99,85,99,99,99,0,39,0,0,0,56,0,72,2,50,99,99,99,85,99,99,99,0,39,0,0,0,56,0,78,8,0,99,99,99,85,99,99,99,0,39,0,0,0,56,0,76,6,0,99,99,99,85,99,99,99,0,39,0,0,0,56,0,86,4,0,99,99,99,85,99,99,99,0,39,0,0,0,56,0,84,0,0,99,99,99,85,99,99,99,0,39,0,0,0,56,0,90,2,0,99,99,99,99,50,50,50,50,31,8,60,0,3,0,57,24,68,82,65,87,66,65,82,83,32,32], /* ORGAN */
|
||
[99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,99,99,99,99,99,99,0,39,0,0,0,56,0,0,2,0,99,75,40,60,99,30,0,0,39,0,0,0,58,12,68,2,0,99,60,40,60,99,30,0,0,39,0,0,0,66,8,74,4,0,99,70,40,60,99,40,0,0,39,0,0,0,58,16,76,6,0,99,45,30,60,99,60,0,0,39,0,0,0,58,8,98,2,0,99,99,99,99,50,50,50,50,4,8,35,0,0,0,1,24,78,89,76,79,78,32,80,73,67,75], /* PLUCK */
|
||
];
|
||
const init = () => unpack(INIT_PK);
|
||
const factory = (k) => unpack(FACTORY_PK[k]);
|
||
return { OP, VOICE, OPI, VI, NAME, SIZE, PACKED, max, at, sanitize, unpack, pack, name, setName, checksum, parseSysex,
|
||
singleSysex, bankSysex, ALG, carriers, feedbackOp, freqText, INIT_PK, FACTORY_PK, init, factory,
|
||
TARGET: { TRACK: 0, BANK: 1, FACTORY: 2, USER: 3 } };
|
||
})();
|
||
|
||
/* ----------------------------------------------------------------- DIGITAL --- */
|
||
/* DIGITAL (engine 1, four-operator FM) was replaced by FM6 (1.0): the firmware keeps engine 1 reserved (its name
|
||
"-"; a FELUCCA_FM4=1 build has DIGITAL back) and turns every DIGITAL sound into an FM6 one with a patch of its own
|
||
(src/fm4_convert.c). This is the same conversion (test_web.mjs: == the firmware's, build/host/desc.json "FM4"), for
|
||
library files and device slots of DIGITAL sounds. convert(p, pe0): p the values as DIGITAL has them (null: its
|
||
defaults), P_E0 at pe0 (the OP ENV values at 61..80 when pe0 >= 81) -> {p: FM6's (the macros neutral, PTCH the
|
||
nearest factory patch, the OP ENV values their defaults), voice: the 155-byte patch, preset: FM6's that covers it} */
|
||
const FM4 = (() => {
|
||
const P = (name, e, env, fenv, mono, fx, pat) => ({ name, e, env, fenv, mono, fx, pat });
|
||
const PRESETS = [ /* src/fm4_convert.c DIGITAL_PRESETS (fx: the sends) */
|
||
P("E.PIANO", [4, 1, 1, 14, 70, 55, 0, 0], [0, 80, 40, 60], 0, 0, [0, 50, 25, 35], 6),
|
||
P("BELL", [4, 8, 1, 4, 90, 70, 0, 0], [0, 95, 0, 85], 0, 0, [0, 0, 30, 70], 7),
|
||
P("BASS", [0, 1, 1, 1, 48, 40, 8, 0], [0, 60, 70, 25], 0, 1, [0, 0, 10, 10], 2),
|
||
P("BRASS", [0, 1, 1, 1, 70, 40, 20, 0], [40, 70, 100, 40], 20, 0, [0, 20, 20, 40], 6),
|
||
P("ORGAN", [7, 2, 3, 4, 0, 0, 0, 0], [2, 60, 127, 20], 0, 0, [10, 40, 0, 30], 6),
|
||
P("PAD", [5, 2, 1, 3, 40, 90, 10, 0], [80, 90, 110, 95], 0, 0, [0, 60, 30, 70], 5),
|
||
P("MARIMBA", [4, 4, 1, 1, 60, 30, 0, 0], [0, 80, 0, 60], 0, 0, [0, 0, 25, 40], 3),
|
||
P("FUNK KEY", [3, 1, 3, 5, 90, 25, 20, 0], [0, 45, 30, 30], 0, 0, [0, 20, 30, 20], 6)];
|
||
const TO_FM6 = [0, 1, 2, 3, 6, 4, 5, 7]; /* DIGITAL preset k -> the FM6 preset (its PTCH) covering it */
|
||
const ALG = [[0, [3, 4, 5, 6], [1, 1, 1, 1]], [13, [3, 4, 5, 6], [1, 1, 2, 2]], [7, [3, 5, 6, 4], [1, 2, 1, 2]],
|
||
[6, [3, 4, 5, 6], [1, 2, 2, 1]], [4, [1, 2, 5, 6], [2, 1, 2, 1]], [21, [3, 4, 5, 6], [3, 3, 3, 1]],
|
||
[28, [1, 2, 5, 6], [3, 3, 3, 1]], [31, [1, 2, 3, 6], [4, 4, 4, 4]]];
|
||
const MUTE = -100000, FB_NOISE = 20, FB_LIFT = 768, ATK = 1, DEC = 2, SUS = 3, REL = 4, ED_FLT = 5, OPENV = 61;
|
||
const EDEF = [0, 1, 1, 1, 60, 60, 0, 0], TDEF = { 1: 10, 2: 70, 3: 90, 4: 60, 5: 0 };
|
||
const MS10 = Array.from({ length: 128 }, (_, v) => Math.round(10 * 10000 ** (v / 127))); /* TIME_MS_X10 */
|
||
const LUT = [0, 5, 9, 13, 17, 20, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 42, 43, 45, 46];
|
||
const scaleout = (l) => (l >= 20 ? 28 + l : LUT[l < 0 ? 0 : l]);
|
||
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
|
||
const div = (a, b) => Math.trunc(a / b);
|
||
function lg(x) { /* 256 log2(x) (fm4_lg) */
|
||
if (!x) return MUTE;
|
||
let n = 0;
|
||
while (n < 31 && Math.floor(x / 2 ** (n + 1))) n++;
|
||
const f = (n >= 8 ? Math.floor(x / 2 ** (n - 8)) : x * 2 ** (8 - n)) & 255;
|
||
return n * 256 + f + Math.floor(f * (256 - f) * 89 / 65536);
|
||
}
|
||
const ms = (q) => (q ? lg(q) - 3840 : MUTE);
|
||
const samples = (v) => Math.floor(MS10[v & 127] * 441 / 100);
|
||
function rate(per) {
|
||
const lt = lg(per < 1 ? 1 : per);
|
||
let best = 0, bd = Infinity;
|
||
for (let r = 0; r < 100; r++) {
|
||
const q = (r * 41) >> 6, d = Math.abs(lg(Math.floor((1 << (22 - (q >> 2))) / (4 + (q & 3)))) - lt);
|
||
if (d < bd) { bd = d; best = r; }
|
||
}
|
||
return best;
|
||
}
|
||
const fall = (t, drop) => (drop <= 0 ? (drop === MUTE ? rate(div(t * 100, 664)) : 99) : rate(div(t * 111, drop)));
|
||
function nearestLevel(m, f) {
|
||
if (m <= MUTE) return 0;
|
||
let best = 0, bd = Infinity;
|
||
for (let l = 0; l < 100; l++) { const d = Math.abs(f(l) - m); if (d < bd) { bd = d; best = l; } }
|
||
return best;
|
||
}
|
||
const level = (m) => nearestLevel(m, (l) => ((scaleout(l) >> 1) << 6) - 4032);
|
||
const outlevel = (m) => nearestLevel(m, (l) => (scaleout(l) << 5) - 4064);
|
||
function nearest(e) {
|
||
let best = 0, bd = Infinity;
|
||
PRESETS.forEach((pr, k) => {
|
||
let d = ((e[0] & 7) !== pr.e[0]) * 1000;
|
||
for (let i = 1; i < 7; i++) d += Math.abs(e[i] - pr.e[i]) * (i < 4 ? 8 : 1);
|
||
if (d < bd) { bd = d; best = k; }
|
||
});
|
||
return best;
|
||
}
|
||
function convert(pin, pe0 = pin.length - 8) {
|
||
const p = pin.slice(), v = new Array(156).fill(0), op = pe0 >= 81;
|
||
const g = (i, d) => (p[i] == null ? d : p[i]);
|
||
const ev = Array.from({ length: 8 }, (_, i) => g(pe0 + i, EDEF[i]));
|
||
const tv = (i) => g(i, TDEF[i]);
|
||
const alg = ev[0] & 7, near = nearest(ev);
|
||
const idx = clamp(ev[4], 0, 127), fenv = clamp(tv(ED_FLT), -64, 63), sus = clamp(tv(SUS), 0, 127);
|
||
const ipk = clamp(idx + fenv, 0, 127), isus = clamp(div(idx, 4) + div(fenv * sus, 127), 0, 127);
|
||
const tAtt = samples(tv(ATK)), tMod = samples(ev[5]), car = FM6.carriers(ALG[alg][0]);
|
||
let fb = MUTE;
|
||
for (let k = 0; k < 6; k++) { const o = k * 21; v[o] = v[o + 1] = v[o + 2] = v[o + 3] = 99; v[o + 8] = 39; v[o + 18] = 1; v[o + 20] = 7; }
|
||
v[134] = ALG[alg][0];
|
||
for (let k = 0; k < 4; k++) {
|
||
const e = op ? [0, 1, 2, 3, 4].map((i) => g(OPENV + k * 5 + i, i === 2 || i === 4 ? 127 : 0)) : [0, 0, 127, 0, 127];
|
||
const opn = ALG[alg][1][k], share = ALG[alg][2][k], o = (6 - opn) * 21;
|
||
const flat = !e[0] && !e[1] && e[2] === 127 && !e[3];
|
||
const lvl = clamp(e[4], 0, 127) * 258, osus = flat ? 32767 : clamp(e[2], 0, 127) * 258;
|
||
const tOdec = flat || e[2] === 127 ? 0 : e[1] ? samples(e[1]) : 1;
|
||
const tOrel = flat ? 0x7FFFFFFF : e[3] ? samples(e[3]) : 0;
|
||
const r = k ? (ev[k] >>> 0) % 15 : 1;
|
||
let ta, td, tr, msS;
|
||
v[o + 18] = k ? (r === 0 ? 0 : r <= 12 ? r : r === 13 ? 14 : 16) : 1;
|
||
if (car.includes(opn)) { /* a carrier: the master envelope x the op's */
|
||
v[o + 16] = outlevel(ms(Math.floor(lvl / share)) + 256 - 96);
|
||
v[o + 15] = 3;
|
||
ta = tAtt;
|
||
if (!flat && e[0] && samples(e[0]) > ta) ta = samples(e[0]);
|
||
const s = Math.floor(sus * 258 * osus / 32768);
|
||
td = Math.max(sus < 127 ? samples(tv(DEC)) : 0, tOdec);
|
||
tr = samples(tv(REL));
|
||
if (!flat) tr = tOrel ? Math.floor((tr >> 5) * (tOrel >> 5) / ((tr >> 5) + (tOrel >> 5) + 1)) << 5 : 0;
|
||
msS = ms(s);
|
||
v[o] = rate(div(ta * 100, 146)); v[o + 4] = 99; v[o + 5] = v[o + 6] = level(msS);
|
||
v[o + 1] = fall(td, msS === MUTE ? MUTE : -msS); v[o + 2] = 99; v[o + 3] = rate(div(tr * 100, 664)); v[o + 7] = 0;
|
||
if (k === 3 && ev[6] && v[o + 16]) {
|
||
const need = ms(Math.floor(ev[6] * 258 * lvl / 32768)) + 256;
|
||
let out = (scaleout(v[o + 16]) << 5) - 4064 + (msS === MUTE ? -2048 : msS);
|
||
if (ev[6] >= FB_NOISE && msS !== MUTE && out < need) {
|
||
out += Math.min(need - out, FB_LIFT);
|
||
v[o + 16] = outlevel(out - msS);
|
||
out = (scaleout(v[o + 16]) << 5) - 4064 + msS;
|
||
}
|
||
fb = need - 256 - out;
|
||
}
|
||
} else { /* a modulator: INDEX through MODDEC x the op's envelope */
|
||
const a = Math.floor(Math.floor(ipk * lvl / 127) / share);
|
||
const m = ipk ? Math.floor(Math.floor(isus * 32767 / ipk) * osus / 32768) : 0;
|
||
let msA = ms(a);
|
||
msS = ms(m);
|
||
if (k === 3 && ev[6] && a) {
|
||
const need = ms(Math.floor(ev[6] * 258 * lvl / 32768)) + 256;
|
||
if (ev[6] >= FB_NOISE && msS !== MUTE && msA + msS < need) {
|
||
const t = msA + msS + Math.min(need - (msA + msS), FB_LIFT);
|
||
if (t <= msA) msS = t - msA;
|
||
else { msS = 0; msA = t > 0 ? 0 : t; }
|
||
}
|
||
fb = need - 256 - (msA + (msS === MUTE ? -2048 : msS));
|
||
}
|
||
v[o + 16] = outlevel(msA); v[o + 15] = a ? 1 : 0;
|
||
ta = fenv > 0 ? div(tAtt * fenv, idx + fenv) : 0;
|
||
if (!flat && e[0] && samples(e[0]) > ta) ta = samples(e[0]);
|
||
td = Math.max(msS < 0 ? (isus < ipk ? tMod : 0) : 0, tOdec);
|
||
v[o] = rate(div(ta * 100, 146)); v[o + 4] = 99; v[o + 5] = v[o + 6] = level(msS);
|
||
v[o + 1] = fall(td, msS === MUTE ? MUTE : -msS); v[o + 2] = 99;
|
||
if (flat) { v[o + 3] = v[o + 1]; v[o + 7] = v[o + 6]; }
|
||
else { v[o + 3] = tOrel ? rate(div(tOrel * 100, 664)) : 99; v[o + 7] = 0; }
|
||
}
|
||
}
|
||
fb += 8 * 256 + 128; /* FM6 feedback: deviation = output x 2^(FB - 8) */
|
||
if (ev[6] && fb > 0) v[135] = Math.min(div(fb, 256), 7);
|
||
for (let k = 0; k < 4; k++) { v[126 + k] = 99; v[130 + k] = 50; }
|
||
v[136] = 1; v[137] = 35; v[144] = 24;
|
||
const same = PRESETS.find((pr) => pr.env.every((x, i) => x === tv(ATK + i)) && pr.e.slice(0, 7).every((x, i) => x === ev[i]));
|
||
FM6.setName(v, same ? same.name : `4OP ALG ${alg + 1}`);
|
||
for (let k = 0; k < 7; k++) p[pe0 + k] = 0;
|
||
p[pe0 + 7] = TO_FM6[near];
|
||
if (op) for (let i = 0; i < 20; i++) p[OPENV + i] = i % 5 === 2 || i % 5 === 4 ? 127 : 0;
|
||
p[ATK] = p[ATK + 1] = p[ATK + 3] = 0; p[ATK + 2] = 127; /* (0.6.81) the ADSR in the operators': FM6's neutral */
|
||
return { p, voice: FM6.sanitize(v), preset: TO_FM6[near] };
|
||
}
|
||
/* preset k's values into p (src/fm4_convert.c fm4_preset_values: EDIT, ENV, ENV -> FLT, VOICE, sends, OP ENV) */
|
||
function presetValues(p, k, pe0 = p.length - 8) {
|
||
const pr = PRESETS[k % PRESETS.length];
|
||
pr.e.forEach((x, i) => { p[pe0 + i] = x; });
|
||
pr.env.forEach((x, i) => { p[ATK + i] = x; });
|
||
p[ED_FLT] = pr.fenv; p[37] = pr.mono ? 2 : 0;
|
||
pr.fx.forEach((x, i) => { p[33 + i] = x; });
|
||
if (pe0 >= 81) for (let i = 0; i < 20; i++) p[OPENV + i] = i % 5 === 2 || i % 5 === 4 ? 127 : 0;
|
||
return p;
|
||
}
|
||
return { PRESETS, TO_FM6, ALG, convert, presetValues };
|
||
})();
|
||
/* a DIGITAL sound for a device / library without DIGITAL (engines: its names; "-" at 1 = reserved) -> the FM6 patch
|
||
that replaces it: {..., engine: FM6's index, engineName "FM6", p, fm6: packed, fm4: the DIGITAL values}; null when
|
||
the engines have no FM6. A device's slot of engine 1 holds such a sound (its record kept: the device converts it) */
|
||
function fromDigital(pt, engines, pe0) {
|
||
const fm6 = engines && engines.length ? engines.indexOf("FM6") : 12;
|
||
if (fm6 < 0) return null;
|
||
const src = Array.from(pt.p || pt.params || []);
|
||
const r = FM4.convert(src, pe0 ?? src.length - 8);
|
||
return { ...pt, engine: fm6, engineName: "FM6", p: r.p, params: undefined, fm6: FM6.pack(r.voice), fm4: src };
|
||
}
|
||
const reservedFm4 = (engines, e) => e === 1 && (engines || [])[1] === "-"; /* a device's slot of a DIGITAL sound */
|
||
/* SAMPLE SET 4 was PERC, the GM drum kit (retired after 1.0.2; src/core.h drum_from_perc): a sound of it is the DRUM
|
||
engine with its default kit (eng_drum.c DRUM_PRESETS[0], the same GM key map); the rest of its values stay. engines:
|
||
the names ("SAMPLE", "DRUM"; none: the firmware's indices 4, 10), pe0: P_E0 in its p. -> the DRUM patch, or null when
|
||
pt is no such sound or there is no DRUM. The device converts its own (projects, user presets) the same way */
|
||
const PERC_SET = 4, DRUM_KIT_E = [64, 64, 70, 64, 64, 0, 0, 0];
|
||
function fromPerc(pt, engines, pe0) {
|
||
const names = engines && engines.length ? engines : null;
|
||
const name = pt.engineName || (names || [])[pt.engine];
|
||
const p = pt.p || pt.params, drum = names ? names.indexOf("DRUM") : 10;
|
||
if (!(name === "SAMPLE" || (pt.engine === 4 && (!name || name === "-"))) || !Array.isArray(p) || drum < 0) return null; /* (4: "-" once retired) */
|
||
const e0 = pe0 ?? p.length - 8;
|
||
if (p[e0] !== PERC_SET) return null;
|
||
if (names && names[4] === "SAMPLE") return null; /* ((ports/) a big CPU plays SAMPLE: its sounds stay, core.h drum_from_perc) */
|
||
const q = p.slice();
|
||
DRUM_KIT_E.forEach((v, i) => { q[e0 + i] = v; });
|
||
return { ...pt, engine: drum, engineName: "DRUM", p: q, params: undefined };
|
||
}
|
||
/* an engine's name to show: the reserved engine 1 holds DIGITAL sounds that play as FM6 */
|
||
const engineLabel = (engines, e) => (e === 1 && (engines || [])[1] === "-" ? "FM6" : (engines || [])[e] ?? String(e));
|
||
|
||
function makeMockDevice(opt = {}) {
|
||
const NDTIME = ["1/4", "1/8", "1/16", "1/32", "8T", "16T", "1/2", "1/1", "2BAR", "4BAR", "5ms", "6ms", "7ms", "8ms", "9ms", "10ms", "11ms", "12ms", "13ms", "15ms", "17ms", "19ms", "21ms", "24ms", "27ms", "31ms", "35ms", "39ms", "44ms", "50ms", "56ms", "64ms", "72ms", "81ms", "91ms", "103ms", "116ms", "131ms", "148ms", "167ms", "189ms", "213ms", "241ms", "272ms", "307ms", "346ms", "391ms", "441ms", "498ms", "562ms", "634ms", "716ms", "808ms", "912ms", "1.03s", "1.16s", "1.31s", "1.48s", "1.67s", "1.89s", "2.13s", "2.40s", "2.71s", "2.95s", "1/8D", "1/16D", "1/4D"]; /* (JIANT 0.4) the delay's TIME: the divisions, then free times (0.8.4: to 2.95 s); V10.8: the dotted ones appended */
|
||
const NONOFF = ["OFF", "ON"], NDIV = ["1/4", "1/8", "1/16", "1/32", "8T", "16T", "1/2", "1/1", "2BAR", "4BAR"], NGO = ["--", "GO"], NDASH = ["--"];
|
||
const D = (label, fmt, min, max, def, names = null, unit = "") => ({ label, fmt, min, max, def, names, unit });
|
||
const E = (label, names, def) => D(label, F.ENUM, 0, names.length - 1, def, names);
|
||
const MSRC = ["OFF", "LFO", "ENV", "VEL", "KEY", "RAND", "MODW", "AT", "EXPR", "M1", "M2", "M3", "M4", "STEP", "NOISE", "PROX", "ENV2", "FOLLOW"]; /* (V10.14 PROX, V10.22 ENV2, FOLLOW) */
|
||
const MDST = ["OFF", "PITCH", "CUT", "SHP", "AMP", "PAN", "DIST", "CHO", "DLY", "REV", "RATE", "VIB", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "CLIP", "PNCH", "D.TIM", "D.FB", "D.TON", "D.MIX", "R.SIZ", "R.DMP", "C.RAT", "C.DEP"];
|
||
const TP = [
|
||
D("LEVEL", F.DB, 0, 127, 104),
|
||
D("ATK", F.TIME, 0, 127, 10), D("DEC", F.TIME, 0, 127, 70), D("SUS", F.PCT, 0, 127, 90), D("REL", F.TIME, 0, 127, 60),
|
||
D("FILTER", F.BIPCT, -64, 63, 0), D("PITCH", F.BIPCT, -64, 63, 0), D("SHAPE", F.BIPCT, -64, 63, 0), E("LOOP", ["OFF", "ON"], 0), /* (JIANT 0.4: P_ED_FX is the ENV LOOP) */
|
||
D("RATE", F.LFOHZ, -14, 127, 60), E("WAVE", ["SIN", "TRI", "SAW", "SQR", "S&H", "DRIFT"], 0), D("PHASE", F.INT, -1, 127, 0), D("FADE", F.TIME, 0, 127, 0), /* (0.6.51) RATE < 0 in time, PHASE -1 FREE (0.9.18: shown as MODE TRIG / FREE, lfoModeRows) */
|
||
D("PITCH", F.BIPCT, -64, 63, 0), D("FILTER", F.BIPCT, -64, 63, 0), D("SHAPE", F.BIPCT, -64, 63, 0), D("AMP", F.PCT, 0, 127, 0),
|
||
E("MODE", ["OFF", "UP", "DN", "UPDN", "RND", "ORD", "REPEAT", "DNUP", "UP+8", "CONV", "DIVG", "PINKY", "THUMB", "WALK", "CHORD", "TRNS"], 0), E("RATE", NDIV, 2), D("OCT", F.INT, 1, 4, 1), D("GATE", F.PCT, 1, 127, 64),
|
||
D("SWING", F.PCT, 0, 100, 0), D("PROB", F.PCT, 0, 127, 127), E("HOLD", NONOFF, 0), E("ORDER", ["NOTE", "PLAY"], 0),
|
||
D("ROOT", F.NOTE, 0, 11, 0), E("SCALE", ["CHR", "MAJ", "MIN", "DOR", "MIX", "PEN", "MPEN", "HARM", "PHRY", "LYD", "LOC", "MEL", "BLUES", "WHOLE", "DIMHW", "DIMWH"], 0), E("QUANT", ["OFF", "SNAP", "WHITE", "SEQ"], 0), D("TRANS", F.SEMI, -24, 24, 0),
|
||
D("LEN", F.STEPS, 1, 64, 16), E("DIV", NDIV, 2), D("SWING", F.PCT, 0, 100, 0), D("GATE", F.PCT, 1, 127, 64),
|
||
D("DIST", F.PCT, 0, 127, 0), D("CHORUS", F.PCT, 0, 127, 0), D("DLY", F.PCT, 0, 127, 0), D("REV", F.PCT, 0, 127, 0),
|
||
E("VOICE", ["POLY", "MONO", "LEG", "UNI"], 0), D("GLIDE", F.TIME, 0, 127, 0), D("PAN", F.BIPCT, -64, 63, 0), E("MUTE", NONOFF, 0),
|
||
E("MODE", ["RATE", "TIME"], 0), E("PRIO", ["LAST", "LOW", "HIGH"], 0), E("ALLOC", ["ROT", "REUSE"], 0), D("DETUNE", F.INT, 0, 127, 40),
|
||
D("DEPTH", F.PCT, 0, 127, 0), D("RATE", F.LFOHZ, 0, 127, 2), E("WAVE", ["SIN", "TRI", "SAW", "SQR", "S&H"], 1), E("SYNC", ["FREE", "BEAT"], 1), /* (JIANT 0.6.9) AUTO PAN, in the old per-track SLICER's slots (BEAT: RATE 0..7, 4BAR .. 1/32) */
|
||
...[1, 2, 3, 4].flatMap((k) => [E("SRC" + k, MSRC, 0), E("DEST" + k, MDST, 0), D("AMT" + k, F.BIPCT, -64, 63, 0)]), /* the matrix */
|
||
];
|
||
const GP = [
|
||
D("BPM", F.BPM, 40, 240, 120), D("SWING", F.PCT, 0, 100, 0), E("CLOCK", ["INT", "USB+BT", "TRS"], 0), D("TUNE", F.INT, -50, 50, 0),
|
||
E("TIME", NDTIME, 1), D("FEEDBK", F.PCT, 0, 120, 60), D("TONE", F.PCT, 0, 127, 64), D("MIX", F.PCT, 0, 127, 90), /* (JIANT 0.4: free
|
||
times past the divisions; TONE: COLR + HPF in one) */
|
||
D("SIZE", F.PCT, 0, 127, 90), D("DAMP", F.PCT, 0, 127, 60), D("RATE", F.LFOHZ, 0, 127, 40), D("DEPTH", F.PCT, 0, 127, 60),
|
||
E("MIDI", ["USB", "TRS"], 0), D("REL", F.PCT, 0, 100, 30), /* G_DREL (was SYNC): DUCK's release */ E("ROUTE", ["CH1-6", "SEL"], 0), D("CPU", F.INT, 0, 0, 0),
|
||
D("SLOT", F.INT, 1, 4, 1), D("DJ FILT", F.BIPCT, -64, 63, 0), E("LOAD", NGO, 0), E("SAVE", NGO, 0), /* (0.9.1) G_DJF 17 (was NAME, "--"): the master DJ FILTER */
|
||
E("ENG", ["ANALOG", "-", "PHASE", "LOFI", "-", "VOICE", "-", "WHEEL",
|
||
"STRING", "-", "DRUM", "NOISE", "FM6", "ADD", "ANIMAL", "INPUT"], 0), D("CLIP", F.PCT, 0, 100, 0), /* G_CLIP (was SET); 0.8.3 ANIMAL; snd5 STRING 8 ADD 13; V10.54 INPUT 15 */
|
||
E("CLRSQ", NGO, 0), E("INIT", NGO, 0),
|
||
E("TYPE", ["ROOM", "SPRING", "SHIMR", "RESO", "CLOUD"], 0), /* G_RTYPE (id 24, was G_DRCH): the reverb's model */
|
||
D("PUNCH", F.PCT, 0, 100, 0), D("DUCK", F.PCT, 0, 100, 0), /* G_PUNCH, G_DUCK (JIANT; were G_DRLVL, G_DRREV) */
|
||
D("STEREO", F.BIPCT, -64, 63, 0), D("WIDE", F.PCT, 0, 127, 0), /* (JIANT, FUNB) G_DHPF (0.6.9: G_CSTER, the CHORUS's stereo), G_WIDTH: width */
|
||
D("MOD", F.PCT, 0, 127, 0), D("RATE", F.LFOHZ, 0, 127, 30), D("PRE", F.INT, -24, 100, 0), /* the reverb's modulation, pre-delay (0.6.12: SHIMMER / CLOUD AIR below 0) */
|
||
D("FILT", F.BIPCT, -64, 63, 0), D("WIDE", F.PCT, 0, 127, 0), /* (JIANT 0.3) G_RFILT, G_RWIDE: the reverb's tone, width */
|
||
D("PITCH", F.SEMI, -12, 12, 0), D("SPRAY", F.PCT, 0, 127, 0), /* .. G_DPIT, G_DSPRY: the GRAIN delay */
|
||
D("ALL TR", F.INT, -14, 14, 0), /* (JIANT 0.4) G_STRN: every sequence this many steps along the scale */
|
||
/* (JIANT 0.6.3) G_SLMODE 37 ..: the SLICER, one on a bus: mode, pattern, rate, depth; T1..T6 and FX in; the repeats'
|
||
pitch sequence: LEN, QNT, 16 steps */
|
||
E("MODE", ["OFF", "GATE", "STUT"], 0), D("PAT", F.INT, 1, 16, 1), E("RATE", ["1/8", "1/16", "1/32", "8T", "16T", "32T"], 1), D("DEPTH", F.PCT, 0, 127, 127),
|
||
...["T1", "T2", "T3", "T4", "T5", "T6", "FX"].map((l) => E(l, ["OFF", "ON"], 1)),
|
||
D("LEN", F.INT, 1, 16, 16), E("QUANT", ["CHR", "SCL"], 1),
|
||
...Array.from({ length: 16 }, () => D("PITCH", F.SEMI, -24, 24, 0)),
|
||
D("MOD", F.PCT, 0, 127, 0), /* (0.6.86) G_DMOD 66: the delay's tape drift (WOW, FLUTTER) */
|
||
E("TYPE", ["ANALOG", "DIGITAL"], 0), E("PING", ["OFF", "ON"], 0), /* (0.6.90) G_DTYPE 67, G_DPING 68 */
|
||
D("LEN", F.INT, 1, 64, 64), E("RES", ["1/8", "1/16", "1/32"], 1), /* (0.6.99) G_PFXLEN 69, G_PFXRES 70: the punch-in lane */
|
||
D("DRIVE", F.PCT, 0, 100, 0), /* (0.9.9-snd2) G_DDRV 71: the delay's loop driven */
|
||
E("R TIME", ["=L", "x1/2", "x2/3", "x3/4", "x4/3", "x3/2", "x2"], 0), /* (V10.49) G_DRTIM 72: the right echo's time, a ratio of TIME */
|
||
];
|
||
const NONE = D("-", F.INT, 0, 0, 0);
|
||
const RATIO = [".5", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "14", "16"];
|
||
const P = (name, e, env = [10, 70, 90, 60], mono = 0, pat = 0, xp = 0) => ({ name, e, env, mono, pat, xp }); /* xp (0.8.5):
|
||
VOICE's LANG | LYRIC << 2 */
|
||
const ENG = [
|
||
{ name: "ANALOG", titles: ["OSC", "FLT"], edit: [E("WAVE", ["SAW", "SQR", "TRI", "SIN", "PWM", "SYNC", "RING", "SAW3", "PLS3"], 0), D("DETUNE", F.INT, 0, 127, 10, null, "ct"), D("MIX", F.PCT, 0, 127, 64),
|
||
D("NOISE", F.PCT, 0, 127, 0), D("CUT", F.CUTOFF, 0, 127, 90), D("RES", F.PCT, 0, 127, 30), D("DRIVE", F.PCT, 0, 127, 0), D("INT", F.SEMI, -24, 24, 0)], /* (JIANT 0.4: INT, osc 2's interval, was KTR) */
|
||
presets: [P("SAW LEAD", [0, 12, 64, 0, 90, 30, 10, 12], [4, 70, 100, 50], 1, 4), P("SOFT PAD", [0, 20, 64, 4, 60, 10, 0, 0], [80, 90, 110, 95], 0, 5, 14),
|
||
P("SQR BASS", [1, 0, 0, 0, 50, 70, 40, 0], [0, 60, 40, 30], 1, 2), P("PWM STR", [4, 8, 40, 0, 75, 20, 0, 0], [60, 80, 110, 85], 0, 5),
|
||
P("ACID", [0, 0, 0, 0, 50, 100, 25, 0], [0, 55, 20, 30], 1, 1), P("SINE KEY", [3, 6, 50, 0, 127, 0, 0, 0], [2, 80, 30, 70], 0, 6),
|
||
P("RAVE", [4, 30, 64, 0, 85, 20, 30, 7], [20, 80, 110, 60], 1, 13), P("SUB BASS", [3, 0, 0, 0, 40, 0, 20, 0], [0, 60, 100, 20], 1, 8),
|
||
P("PLUCK", [0, 8, 50, 0, 30, 40, 0, 0], [0, 88, 0, 60], 0, 3), P("BRASS", [0, 10, 64, 0, 45, 20, 10, 0], [35, 70, 90, 45], 0, 6),
|
||
P("WIND", [0, 0, 0, 90, 30, 90, 0, 0], [60, 90, 60, 80], 0, 5), P("STRINGS", [0, 25, 64, 0, 70, 10, 0, 0], [70, 90, 115, 90], 0, 5, 74),
|
||
P("SYNC LEAD", [5, 11, 90, 0, 82, 30, 10, 0], [2, 70, 100, 40], 1, 4), P("RING BELL", [6, 18, 100, 0, 110, 20, 0, 0], [0, 92, 0, 80], 0, 7),
|
||
P("FAT BASS", [7, 9, 64, 0, 62, 45, 20, -12], [0, 62, 60, 25], 1, 2), P("JUNO PAD", [4, 14, 64, 2, 58, 12, 0, 0], [45, 90, 115, 90], 0, 5, 80),
|
||
P("REESE", [7, 22, 64, 0, 44, 20, 25, 0], [2, 80, 110, 40], 1, 2), P("HOOVER", [7, 40, 64, 0, 92, 15, 35, 12], [10, 80, 110, 55], 1, 13),
|
||
P("DUB STAB", [1, 6, 64, 0, 52, 55, 10, 7], [0, 50, 20, 45], 0, 6), P("CELLO", [0, 4, 40, 2, 48, 18, 15, -12], [30, 85, 110, 70], 0, 5),
|
||
P("ARP PLUCK", [1, 10, 50, 0, 44, 50, 0, 12], [0, 62, 0, 40], 0, 3), P("MOOG LEAD", [2, 6, 40, 0, 72, 40, 40, -12], [6, 75, 100, 45], 1, 4),
|
||
P("DARK PAD", [0, 18, 64, 6, 38, 30, 10, -12], [70, 95, 120, 100], 0, 5, 214), P("GLASS KEYS", [3, 8, 60, 0, 120, 0, 0, 19], [0, 82, 20, 65], 0, 6),
|
||
P("ORGAN SQR", [1, 4, 64, 0, 100, 0, 5, 12], [0, 64, 127, 30], 0, 6)] },
|
||
/* 1: reserved (DIGITAL, retired: src/fm4_convert.c ENG_FM4_GONE; its sounds load as FM6, FM4 above) */
|
||
{ name: "-", titles: ["-", "-"], edit: [D("-", F.INT, 0, 7, 0), D("-", F.INT, 0, 14, 1), D("-", F.INT, 0, 14, 1),
|
||
D("-", F.INT, 0, 14, 1), D("-", F.PCT, 0, 127, 60), D("-", F.INT, 0, 127, 60), D("-", F.PCT, 0, 127, 0), NONE],
|
||
presets: [] },
|
||
{ name: "PHASE", titles: ["PHS", "LINE"], edit: [E("WAVE", ["SAW", "SQR", "PLS", "DSIN", "SPLS", "RSAW", "RTRI", "RTRP"], 0),
|
||
E("WAVE2", ["-", "SAW", "SQR", "PLS", "DSIN", "SPLS", "RSAW", "RTRI", "RTRP"], 0), D("DCW", F.PCT, 0, 127, 60), D("ENV", F.PCT, 0, 127, 64),
|
||
D("DETUNE", F.INT, 0, 127, 0, null, "ct"), E("LINE", ["MIX", "RING"], 0), D("SUB", F.PCT, 0, 127, 0), D("FB", F.PCT, 0, 127, 0)],
|
||
presets: [P("BRASS", [0, 0, 30, 90, 0, 0, 0, 0], [8, 70, 90, 40], 0, 6), P("ORGAN", [3, 0, 40, 0, 0, 0, 0, 0], [0, 127, 127, 30], 0, 6),
|
||
P("STRING", [0, 4, 50, 40, 12, 0, 0, 0], [40, 90, 100, 70], 0, 5), P("RESO", [5, 0, 60, 60, 0, 0, 0, 0], [0, 70, 30, 60], 0, 1),
|
||
P("BELL", [6, 0, 80, 50, 0, 0, 0, 0], [0, 95, 0, 90], 0, 7), P("WIRE", [4, 7, 70, 40, 7, 0, 0, 0], [10, 80, 80, 60], 0, 4),
|
||
P("GROWL", [0, 0, 70, 80, 0, 0, 40, 55], [2, 70, 90, 40], 1, 4), P("FB BASS", [1, 0, 45, 60, 0, 0, 70, 35], [0, 60, 60, 25], 1, 2),
|
||
P("CZ PIANO", [3, 0, 55, 85, 0, 0, 15, 0], [0, 78, 30, 55], 0, 6), P("GLASS PAD", [6, 5, 45, 35, 14, 0, 0, 0], [60, 90, 115, 95], 0, 5, 210),
|
||
P("DIGI STAB", [4, 2, 75, 70, 0, 1, 0, 0], [0, 55, 20, 40], 0, 6), P("SYN BASS", [1, 0, 50, 70, 0, 0, 60, 0], [0, 58, 50, 25], 1, 2),
|
||
P("VOX PAD", [5, 4, 35, 30, 10, 0, 0, 0], [70, 95, 115, 100], 0, 5, 14), P("HARP", [3, 0, 70, 90, 0, 0, 0, 0], [0, 85, 0, 70], 0, 3),
|
||
P("PD LEAD", [0, 2, 65, 55, 9, 0, 20, 10], [4, 70, 95, 45], 1, 4), P("RING KEYS", [2, 4, 60, 60, 0, 1, 0, 0], [0, 75, 25, 60], 0, 6)] },
|
||
{ name: "LOFI", titles: ["CHIP", "TONE"], edit: [E("CHIP", ["4BIT", "4B/2", "8BIT", "1BIT", "STEP"], 0), E("WAVE", ["PLS", "TRI", "SAW", "NOIS", "WRAM", "BYTE", "FLOAT"], 0), D("DUTY", F.INT, 0, 127, 64),
|
||
D("CRUSH", F.PCT, 0, 127, 0), D("CUT", F.CUTOFF, 0, 127, 110), D("VIB", F.PCT, 0, 127, 0), D("BEND", F.PCT, 0, 127, 0), D("MASK", F.PCT, 0, 127, 0)], /* (JIANT 0.4: CUT BEND MASK) */
|
||
presets: [P("BYTEBEAT", [2, 5, 4, 0, 64, 0, 0, 0], [0, 80, 110, 40], 1, 4), P("BYTE VAR", [2, 5, 64, 40, 64, 0, 0, 0], [0, 80, 110, 50], 1, 3),
|
||
P("BYTE BENT", [2, 5, 16, 0, 64, 24, 70, 0], [0, 80, 110, 45], 1, 4), P("PULSE LD", [0, 0, 32, 0, 127, 20, 0, 0], [0, 60, 90, 30], 1, 4),
|
||
P("WAVE BASS", [1, 1, 0, 0, 90, 0, 0, 0], [0, 50, 70, 20], 1, 2), P("8BIT KEYS", [2, 0, 96, 0, 110, 0, 30, 0], [0, 60, 80, 40], 0, 13),
|
||
P("WAVE LEAD", [0, 4, 92, 0, 110, 18, 0, 0], [0, 70, 90, 30], 1, 3), P("STEP LEAD", [4, 0, 40, 34, 127, 16, 0, 0], [0, 64, 127, 55], 1, 4),
|
||
P("BYTE TONE", [2, 5, 40, 0, 64, 0, 0, 80], [0, 70, 100, 40], 1, 4), P("FLOAT FM", [2, 6, 4, 0, 64, 0, 0, 0], [0, 60, 90, 40], 1, 4),
|
||
P("FLOAT ARP", [2, 6, 8, 0, 64, 0, 0, 0], [0, 50, 80, 50], 1, 3), P("FLOAT PAD", [2, 6, 112, 0, 40, 0, 0, 0], [60, 90, 110, 90], 1, 3),
|
||
P("CHIP PAD", [0, 1, 64, 0, 90, 12, 0, 0], [40, 90, 115, 80], 0, 5, 78), P("GB ARP", [2, 0, 16, 0, 120, 0, 0, 0], [0, 55, 0, 35], 0, 3),
|
||
P("TRI BASS", [0, 1, 64, 0, 80, 0, 0, 0], [0, 60, 90, 20], 1, 2), P("SOFT CHIP", [1, 0, 64, 0, 85, 8, 0, 0], [5, 70, 80, 50], 0, 6),
|
||
P("SAW CHIP", [2, 2, 64, 0, 100, 10, 0, 0], [0, 65, 90, 35], 1, 4), P("PULSE BASS", [0, 0, 40, 0, 70, 0, 0, 0], [0, 55, 80, 15], 1, 2)] },
|
||
/* 4: reserved (SAMPLE, retired in JIANT; its sounds load as ANALOG, its PERC set as DRUM) */
|
||
{ name: "-", titles: ["-", "-"], edit: [D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0),
|
||
D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0)],
|
||
presets: [] },
|
||
{ name: "VOICE", titles: ["VOWL", "TONE"], edit: [D("VOWEL", F.INT, 0, 127, 0), D("VOWEL2", F.INT, 0, 127, 64), D("TALK", F.TIME, 0, 127, 0),
|
||
D("SHIFT", F.SEMI, -12, 12, 0), D("BUZZ", F.PCT, 0, 127, 64), D("BREATH", F.PCT, 0, 127, 10), D("Q", F.PCT, 0, 127, 64), D("RAND", F.PCT, 0, 127, 0)],
|
||
presets: [P("CHOIR AAH", [0, 0, 0, 0, 40, 22, 60, 0], [85, 90, 115, 95], 0, 5), P("VOX LEAD", [32, 0, 0, 2, 90, 8, 72, 0], [6, 70, 105, 55], 1, 4),
|
||
P("WOW BASS", [95, 0, 68, 0, 100, 0, 80, 0], [0, 70, 70, 30], 1, 8), P("WHISPER", [0, 95, 88, 3, 50, 120, 50, 0], [50, 90, 110, 90], 0, 5),
|
||
P("OOH PAD", [80, 100, 50, 0, 55, 25, 55, 0], [70, 90, 115, 95], 0, 5), P("CHANT", [20, 60, 100, -12, 70, 15, 65, 10], [30, 90, 110, 80], 0, 5),
|
||
P("TALK BOX", [10, 110, 40, 0, 110, 4, 85, 0], [2, 65, 95, 40], 1, 4),
|
||
/* (0.8.5) WORDS (src/sing.c): LANG 1 ES 2 EN 3 JA, LYRIC 0 TEXT 1..16 W1..W16 17..24 S1..S8 (xp = LANG | LYRIC << 2) */
|
||
P("CANTOR ES", [0, 64, 0, 0, 80, 6, 72, 0], [24, 70, 112, 72], 1, 4, 1 | 1 << 2),
|
||
P("CANTORA ES", [0, 0, 0, 4, 70, 10, 74, 0], [26, 70, 112, 72], 1, 4, 1 | 2 << 2),
|
||
P("SINGER EN", [0, 64, 0, 0, 84, 6, 72, 0], [24, 70, 112, 72], 1, 4, 2 | 3 << 2),
|
||
P("UTA JA", [0, 48, 0, 5, 76, 8, 74, 0], [24, 70, 112, 70], 1, 4, 3 | 4 << 2),
|
||
P("WORD CHOIR", [0, 64, 16, 0, 45, 20, 62, 0], [60, 90, 115, 85], 0, 5, 1 | 5 << 2),
|
||
P("SCAT EN", [0, 64, 0, 0, 96, 4, 76, 0], [16, 60, 100, 60], 1, 4, 2 | 17 << 2),
|
||
P("ROBOT EN", [0, 64, 0, -3, 127, 0, 90, 0], [2, 65, 120, 56], 1, 4, 2 | 6 << 2),
|
||
P("WHISPER JA", [0, 64, 0, 3, 50, 120, 52, 0], [40, 90, 110, 80], 0, 5, 3 | 7 << 2)] },
|
||
/* 6: reserved (TRIO, folded into ANALOG in JIANT 0.4: its sounds load as ANALOG's SYNC / RING / SAW3, core.h analog_from_trio) */
|
||
{ name: "-", titles: ["-", "-"], edit: [D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0),
|
||
D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0)],
|
||
presets: [] },
|
||
{ name: "WHEEL", titles: ["BARS", "TONE"], edit: [E("REG", ["FLUTE", "MELLO", "HOLLW", "SMOOT", "3BAR", "BLUES", "GOSPL", "ROCK",
|
||
"TOPS", "CLARI", "REED", "STRNG", "CHAPL", "BRITE", "BASS", "FULL"], 4), D("SUB", F.INT, -8, 8, 0), D("BODY", F.INT, -8, 8, 0), D("TOP", F.INT, -8, 8, 0),
|
||
E("PERC", ["OFF", "2ND", "3RD", "2SOFT", "3SOFT", "2SLOW", "3SLOW"], 0), D("CLICK", F.PCT, 0, 127, 40), D("DRIVE", F.PCT, 0, 127, 0), E("ROTOR", ["OFF", "SLOW", "FAST"], 1)],
|
||
presets: [P("FULL ORGAN", [15, 0, 0, 0, 0, 30, 20, 1], [0, 64, 127, 45], 0, 5), P("JAZZ PERC", [4, 0, 0, 0, 2, 50, 8, 1], [0, 64, 127, 40], 0, 3),
|
||
P("GOSPEL", [6, 0, 0, 0, 1, 60, 40, 2], [0, 64, 127, 45], 0, 6), P("SOFT FLUTE", [1, 0, -2, 0, 0, 10, 0, 1], [0, 64, 127, 55], 0, 5),
|
||
P("ROCK DRIVE", [7, 0, 0, 0, 0, 70, 100, 2], [0, 64, 127, 40], 0, 4), P("PEDAL BASS", [0, 6, 0, -8, 0, 30, 15, 0], [0, 64, 127, 25], 1, 2),
|
||
P("DRIVE LEAD", [13, 0, 0, 3, 2, 60, 80, 1], [0, 64, 127, 35], 1, 4), P("CHURCH", [12, 0, 0, 0, 0, 0, 0, 0], [15, 64, 127, 70], 0, 5),
|
||
P("WAVE ORGAN", [8, 0, 0, 2, 3, 35, 15, 2], [0, 64, 127, 35], 0, 3), P("REED BASS", [14, 2, 0, -4, 0, 20, 10, 0], [0, 64, 127, 30], 1, 2)] },
|
||
/* 8: STRING (JIANT 0.9.9-snd5, src/eng_string.c; generated from it): Karplus-Strong in the COMB's lines (GRAIN's number, retired in JIANT) */
|
||
{ name: "STRING", titles: ["STRING", "BODY"], edit: [E("EXCITE", ["NOISE", "PLUCK", "PICK", "HAMMR", "STICK", "FDBK"], 1),
|
||
D("DECAY", F.PCT, 0, 127, 72), D("BRIGHT", F.PCT, 0, 127, 60), D("POS", F.PCT, 0, 127, 28), D("STRETCH", F.PCT, 0, 127, 0),
|
||
D("BODY", F.PCT, 0, 127, 40), D("SIZE", F.PCT, 0, 127, 40), D("BOW", F.PCT, 0, 127, 0)],
|
||
presets: [P("NYLON", [1, 72, 52, 28, 0, 60, 40, 0], [0, 64, 127, 104], 0, 3), P("STEEL GTR", [2, 86, 88, 24, 6, 40, 52, 0], [0, 64, 127, 104], 0, 3),
|
||
P("HARP", [1, 96, 62, 64, 0, 30, 30, 0], [0, 64, 127, 112], 0, 6), P("KOTO", [2, 78, 98, 14, 16, 30, 62, 0], [0, 64, 127, 104], 0, 5),
|
||
P("BANJO", [2, 52, 112, 10, 4, 90, 92, 0], [0, 64, 127, 96], 0, 4), P("PIANO", [3, 104, 76, 18, 42, 20, 22, 0], [0, 64, 127, 100], 0, 6),
|
||
P("DULCIMER", [3, 92, 100, 20, 26, 36, 60, 0], [0, 64, 127, 108], 0, 5), P("MARIMBA", [4, 56, 40, 64, 72, 80, 70, 0], [0, 64, 127, 96], 0, 5),
|
||
P("PLUCK BASS", [1, 62, 36, 20, 0, 50, 10, 0], [0, 64, 127, 80], 1, 2), P("BOWED", [0, 118, 46, 30, 0, 50, 40, 70], [30, 64, 127, 96], 0, 5),
|
||
P("KS NOISE", [0, 80, 127, 0, 0, 0, 0, 0], [0, 64, 127, 90], 0, 4), P("METAL STR", [0, 100, 120, 10, 112, 0, 0, 0], [0, 64, 127, 104], 0, 3),
|
||
P("FEEDBACK", [5, 90, 70, 24, 60, 70, 40, 60], [0, 64, 127, 90], 0, 5), P("SHOEGAZE", [5, 110, 50, 30, 55, 100, 90, 70], [0, 64, 127, 112], 0, 5),
|
||
P("SQUEAL", [5, 80, 96, 16, 70, 110, 12, 30], [0, 64, 127, 80], 0, 4), P("EBOW", [5, 127, 44, 40, 50, 20, 64, 90], [20, 64, 127, 100], 0, 5)] },
|
||
/* 9: reserved (PHYS, retired in TONIC: src/engines.c ENG_PHYS_GONE; its sounds load as ANALOG) */
|
||
{ name: "-", titles: ["-", "-"], edit: [D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0),
|
||
D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0), D("-", F.INT, 0, 127, 0)],
|
||
presets: [] },
|
||
{ name: "DRUM", titles: ["KIT", "KIT 2"], edit: [D("MORPH", F.PCT, 0, 127, 64), D("TUNE", F.PCT, 0, 127, 64),
|
||
D("TONE", F.PCT, 0, 127, 64), D("DECAY", F.PCT, 0, 127, 64), D("NOISE", F.PCT, 0, 127, 64), D("FM ENV", F.PCT, 0, 127, 0),
|
||
D("FOLD", F.PCT, 0, 127, 0), D("DRIVE", F.PCT, 0, 127, 0)],
|
||
presets: [P("DRUM-X", [64, 64, 70, 64, 64, 0, 0, 0], [0, 100, 127, 100], 0, 12), P("909 CLUB", [60, 64, 76, 64, 64, 0, 0, 10], [0, 100, 127, 100], 0, 12),
|
||
P("808 BOOM", [58, 60, 56, 76, 60, 0, 0, 0], [0, 100, 127, 100], 0, 12), P("LOFI DUST", [70, 64, 50, 54, 76, 0, 0, 20], [0, 100, 127, 100], 0, 12),
|
||
P("INDUSTRIAL", [72, 66, 88, 70, 74, 20, 0, 40], [0, 100, 127, 100], 0, 12), P("ACOUSTIC", [56, 64, 58, 62, 64, 0, 0, 0], [0, 100, 127, 100], 0, 12),
|
||
P("DUB ROOTS", [60, 60, 52, 70, 60, 0, 0, 0], [0, 100, 127, 100], 0, 12), P("TECHNO RAW", [66, 64, 80, 62, 66, 10, 0, 30], [0, 100, 127, 100], 0, 12),
|
||
P("BREAKS", [62, 66, 72, 62, 70, 0, 0, 10], [0, 100, 127, 100], 0, 12),
|
||
P("HIP HOP", [58, 62, 56, 64, 66, 0, 0, 18], [0, 100, 127, 100], 0, 14)] },
|
||
{ name: "NOISE", titles: ["SRC", "MOVE"], edit: [E("MODE", ["ANLG", "DUST", "LFSR", "META"], 0), D("COLOR", F.PCT, 0, 127, 64),
|
||
D("FREQ", F.CUTOFF, 0, 127, 80), D("PEAK", F.PCT, 0, 127, 30), D("TRK", F.PCT, 0, 127, 64), D("DENSE", F.PCT, 0, 127, 0),
|
||
D("DRIFT", F.PCT, 0, 127, 0), D("CRUSH", F.PCT, 0, 127, 0)],
|
||
presets: [P("WIND", [0, 64, 70, 100, 127, 0, 70, 0], [90, 90, 110, 90], 0, 5), P("RAIN", [1, 30, 88, 80, 64, 105, 40, 0], [10, 90, 127, 70], 0, 5),
|
||
P("ARCADE", [2, 0, 127, 0, 127, 112, 0, 84], [0, 80, 0, 50], 0, 3), P("METAL", [3, 0, 100, 40, 100, 32, 0, 0], [0, 75, 40, 60], 0, 7),
|
||
P("SEA", [0, 40, 50, 60, 40, 0, 90, 0], [100, 90, 120, 110], 0, 5), P("HISS PAD", [0, 90, 95, 110, 127, 0, 20, 0], [80, 90, 115, 100], 0, 5, 152),
|
||
P("CRACKLE", [1, 60, 100, 40, 64, 60, 20, 0], [5, 90, 127, 60], 0, 5), P("TAPE AIR", [0, 75, 60, 20, 64, 0, 50, 10], [90, 90, 120, 110], 0, 5)] },
|
||
{ name: "FM6", titles: ["OPS", "PATCH"], edit: [D("ALG", F.INT, 0, 32, 0), D("FB", F.INT, -7, 7, 0), D("MOD", F.BIPCT, -64, 63, 0),
|
||
D("RATIO", F.INT, -16, 16, 0), D("MEG", F.BIPCT, -64, 63, 0), D("VMOD", F.INT, -7, 7, 0), D("DETUNE", F.PCT, 0, 127, 0),
|
||
D("SLOT", F.INT, 0, FM6.FACTORY_PK.length + 32, 0)], /* F1..F8, then OWN (eng_fm6.c, 1.0.3) */
|
||
presets: [P("TINE EP", [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 127, 0], 0, 6), P("BELL", [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 127, 0], 0, 7),
|
||
P("FM BASS", [0, 0, 0, 0, 0, 0, 0, 2], [0, 0, 127, 0], 1, 2), P("BRASS", [0, 0, 0, 0, 0, 0, 0, 3], [0, 0, 127, 0], 0, 4),
|
||
P("PAD", [0, 0, 0, 0, 0, 0, 30, 4], [0, 0, 127, 0], 0, 5, 204), P("MARIMBA", [0, 0, 0, 0, 0, 0, 0, 5], [0, 0, 127, 0], 0, 3),
|
||
P("ORGAN", [0, 0, 0, 0, 0, 0, 0, 6], [0, 0, 127, 0], 0, 6), P("PLUCK", [0, 0, 0, 0, 0, 0, 0, 7], [0, 0, 127, 0], 0, 13),
|
||
P("FM LEAD", [16, 2, -30, 0, 0, 0, 8, 3], [0, 0, 127, 20], 1, 4), P("SQR LEAD", [0, 0, 10, 1, 20, 0, 6, 7], [0, 30, 110, 25], 1, 4),
|
||
P("SLAP BASS", [0, 1, 25, 0, -30, 3, 0, 2], [0, 0, 127, 0], 1, 2), P("SUB BASS", [0, 0, -64, 0, 0, 0, 0, 2], [0, 0, 127, 10], 1, 2),
|
||
P("BELL PAD", [0, 0, -10, 0, 0, 0, 40, 1], [55, 0, 105, 75], 0, 5, 74), P("HARD BASS", [0, 2, 25, 0, 0, 0, 0, 2], [0, 0, 127, 0], 1, 2),
|
||
P("SAW LEAD", [1, 3, -20, 0, 10, 0, 12, 3], [0, 0, 127, 20], 1, 4)] },
|
||
/* 13: ADD (JIANT 0.9.9-snd5, src/eng_add.c; generated from it): additive, nine partials (SLICE's number, retired in JIANT) */
|
||
{ name: "ADD", titles: ["SPECTRUM", "MOTION"], edit: [E("MODE", ["HARM", "ODD", "WIDE", "BELL", "BAR", "DRUM", "PRIME", "FIFTH", "SUB", "PLATE"], 0),
|
||
D("MORPH", F.PCT, 0, 127, 0), D("BRIGHT", F.PCT, 0, 127, 70), D("PARTIAL", F.PCT, 0, 127, 127), D("SHIFT", F.INT, -64, 63, 0),
|
||
D("COMB", F.PCT, 0, 127, 0), D("DECAY", F.PCT, 0, 127, 127), D("MOTION", F.INT, -64, 63, 0)],
|
||
presets: [P("ADD ORGAN", [0, 0, 70, 127, 0, 0, 127, 0], [0, 64, 127, 40], 0, 5), P("ADD SAW", [0, 0, 92, 127, 0, 0, 127, 0], [0, 64, 127, 35], 0, 4),
|
||
P("HOLLOW", [1, 0, 84, 127, 0, 0, 127, 0], [4, 64, 127, 40], 0, 5), P("PHASER", [0, 0, 96, 127, 0, 40, 127, 0], [10, 64, 127, 45], 0, 5),
|
||
P("BELL", [3, 0, 100, 127, 0, 0, 74, 0], [0, 64, 127, 70], 0, 6), P("RADIO", [0, 0, 96, 127, 40, 0, 127, 20], [0, 64, 127, 80], 0, 6),
|
||
P("VIBES", [4, 0, 72, 127, 0, 0, 76, 0], [0, 64, 127, 55], 0, 6), P("GLASS", [2, 0, 118, 127, -20, 0, 80, 30], [0, 64, 127, 70], 0, 5),
|
||
P("SKIN TOM", [5, 0, 92, 127, 0, 0, 46, 0], [0, 64, 127, 30], 0, 4), P("AIR PAD", [2, 64, 100, 127, -10, 20, 127, 50], [64, 64, 127, 80], 0, 5),
|
||
P("SWELL", [0, 40, 104, 127, 0, 0, 127, -50], [20, 64, 127, 60], 0, 5), P("SUB ADD", [1, 0, 20, 40, 0, 0, 127, 0], [0, 64, 127, 25], 1, 2),
|
||
P("PRIME ORG", [6, 0, 84, 127, 0, 0, 127, 0], [2, 64, 127, 45], 0, 5), P("QUINT", [7, 0, 80, 127, 0, 24, 127, 20], [6, 64, 127, 50], 0, 5),
|
||
P("DRONE", [8, 50, 70, 127, 0, 30, 127, 40], [40, 64, 127, 90], 0, 5), P("GONG", [9, 30, 104, 127, -12, 0, 88, 30], [0, 64, 127, 90], 0, 6)] },
|
||
/* 14: ANIMAL (JIANT 0.8.3, src/eng_animal.c; generated from it): animal calls, five sources (MODE); the labels as the
|
||
device shows them per MODE (animal_desc) are the device's; here the engine's own */
|
||
{ name: "ANIMAL", titles: ["SRC", "CALL"], edit: [E("MODE", ["CMOS", "PULSE", "WHSTL", "WING", "GLOTT"], 0),
|
||
D("PRESS", F.PCT, 0, 127, 100), D("CHAOS", F.PCT, 0, 127, 0), D("SIZE", F.INT, 0, 127, 64), D("SWEEP", F.BIPCT, -64, 63, 0),
|
||
D("RATE", F.LFOHZ, 0, 127, 80), E("GROUP", ["HOLD", "TRILL", "1+1", "1+3", "2+2", "2+6", "3+3", "3+9", "4+4", "4+12", "6+6", "8+8", "8+24", "12+12", "16+16", "32+32"], 0),
|
||
D("TEMP", F.INT, 0, 40, 22, null, "C")],
|
||
presets: [P("CMOS BIRD", [0, 90, 0, 37, 16, 74, 0, 20], [0, 64, 127, 40], 0, 7), P("CMOS TRILL", [0, 70, 0, 50, 6, 94, 0, 6], [0, 64, 127, 40], 0, 7),
|
||
P("CMOS MONKEY", [0, 110, 20, 80, -40, 70, 5, 28], [0, 64, 127, 50], 0, 3), P("CMOS BUG", [0, 60, 90, 20, 12, 104, 0, 16], [0, 64, 127, 30], 0, 7),
|
||
P("CRICKET", [1, 127, 100, 26, 0, 119, 7, 22], [0, 64, 127, 30], 0, 5), P("TREE CRICKT", [1, 127, 110, 32, 4, 102, 1, 22], [0, 64, 127, 40], 0, 5),
|
||
P("KATYDID", [1, 10, 20, 24, 50, 80, 7, 22], [0, 64, 127, 30], 0, 5), P("CICADA", [1, 38, 85, 28, 14, 60, 0, 24], [20, 64, 127, 60], 0, 5),
|
||
P("TREEFROG", [1, 106, 49, 41, 6, 127, 15, 26], [0, 64, 127, 40], 0, 5), P("TOAD", [1, 127, 80, 44, 8, 116, 1, 22], [4, 64, 127, 50], 0, 5),
|
||
P("BULLFROG", [1, 70, 30, 53, 10, 52, 7, 22], [2, 64, 127, 50], 0, 8), P("CANARY", [2, 100, 20, 38, -30, 112, 14, 22], [0, 64, 127, 30], 0, 3),
|
||
P("CARDINAL", [2, 110, 6, 46, -40, 77, 10, 22], [0, 64, 127, 30], 0, 3), P("DOVE", [2, 70, 10, 66, 15, 60, 9, 22], [6, 64, 127, 50], 0, 5),
|
||
P("OWL", [2, 80, 8, 68, -8, 68, 9, 22], [4, 64, 127, 50], 0, 8), P("PEEPER", [2, 100, 4, 34, 30, 80, 3, 22], [0, 64, 127, 30], 0, 5),
|
||
P("BAT", [2, 120, 0, 40, -64, 127, 3, 22], [0, 64, 127, 20], 0, 7), P("MOSQUITO", [3, 30, 50, 64, 20, 40, 2, 22], [10, 64, 127, 40], 0, 5),
|
||
P("BEE", [3, 90, 30, 75, 10, 40, 2, 22], [10, 64, 127, 40], 0, 5), P("FLY", [3, 70, 90, 78, 25, 50, 1, 22], [10, 64, 127, 40], 0, 5),
|
||
P("WOLF", [4, 0, 8, 64, 40, 50, 0, 5], [20, 64, 127, 60], 1, 5), P("DOG BARK", [4, 100, 70, 64, -15, 85, 5, 6], [0, 64, 127, 30], 0, 3),
|
||
P("ROAR", [4, 110, 100, 100, -20, 50, 3, 9], [6, 64, 127, 50], 1, 8), P("PURR", [4, 10, 60, 50, 0, 60, 1, 19], [10, 64, 127, 40], 1, 8)] },
|
||
/* 15: INPUT (V10.54, src/eng_input.c): the audio input as a track's sound, THRU (always) or KEYS (gated by the notes) */
|
||
{ name: "INPUT", titles: ["INPUT", "SHAPE"], edit: [E("SOURCE", ["IN 1", "IN 2", "1+2", "STEREO"], 0),
|
||
D("GAIN", F.INT, 0, 127, 64), D("GATE", F.PCT, 0, 127, 0), E("PLAY", ["THRU", "KEYS"], 0),
|
||
D("WIDTH", F.PCT, 0, 127, 127), D("RING", F.PCT, 0, 127, 0), D("BITS", F.PCT, 0, 127, 0), D("RATE", F.PCT, 0, 127, 0)],
|
||
presets: [P("IN 1", [0, 64, 0, 0, 127, 0, 0, 0], [0, 64, 127, 20], 1, 0), P("IN 2", [1, 64, 0, 0, 127, 0, 0, 0], [0, 64, 127, 20], 1, 0),
|
||
P("IN 1+2", [2, 64, 0, 0, 127, 0, 0, 0], [0, 64, 127, 20], 1, 0), P("STEREO IN", [3, 64, 0, 0, 127, 0, 0, 0], [0, 64, 127, 20], 1, 0),
|
||
P("MIC GATE", [0, 80, 24, 0, 127, 0, 0, 0], [0, 64, 127, 20], 1, 0), P("SPACE IN", [3, 64, 0, 0, 127, 0, 0, 0], [0, 64, 127, 20], 1, 0),
|
||
P("TRANCE GATE", [3, 64, 0, 1, 127, 0, 0, 0], [0, 40, 0, 10], 1, 0), P("RING IN", [0, 64, 0, 1, 127, 90, 0, 0], [0, 64, 127, 30], 1, 0),
|
||
P("CRUSH IN", [2, 72, 0, 0, 127, 0, 90, 60], [0, 64, 127, 20], 1, 0)] },
|
||
];
|
||
/* (ports/) a big CPU's device (opt.hostPower: the MPC Sample, the plugins, the app; INFO 'D' and 'H'): SAMPLE in 4 and
|
||
GRAIN in 8 (engines.c with FELUCCA_HOST_POWER), and the values their pages and DRUM-X's sample layer keep in other
|
||
engines' slots, named by the track's engine (engines.c hp_xdesc) */
|
||
const HP_ENG = {
|
||
/* (ports/, generated from tests/descdump.c built with FELUCCA_HOST_POWER=1: test_web.mjs compares) */
|
||
4: { name: "SAMPLE", titles: ["SAMPLE", "WARP"], edit: [E("SLOT", ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"], 0), D("START", F.PCT, 0, 127, 0), D("LENGTH", F.PCT, 0, 127, 127), E("MODE", ["ONE", "GATE", "LOOP", "PING", "REV", "SLICE", "SCRUB", "TAPE"], 0), D("TUNE", F.SEMI, -24, 24, 0), D("FEEDBK", F.PCT, 0, 127, 0), D("TONE", F.PCT, 0, 127, 64), D("DSTROY", F.PCT, 0, 127, 0)],
|
||
presets: [P("ONE SHOT", [0, 0, 127, 0, 0, 0, 64, 0], [0, 100, 127, 40], 0, 0), P("GATE", [0, 0, 127, 1, 0, 0, 64, 0], [0, 100, 127, 30], 0, 0), P("LOOP", [0, 0, 127, 2, 0, 0, 64, 0], [4, 100, 127, 60], 0, 0), P("PING PONG", [0, 20, 60, 3, 0, 0, 64, 0], [10, 100, 127, 70], 0, 0), P("REVERSE", [0, 0, 127, 4, 0, 0, 64, 0], [0, 100, 127, 40], 0, 0), P("SLICE 16", [0, 0, 127, 5, 0, 0, 64, 0], [0, 100, 127, 20], 0, 11), P("SLICE 8", [0, 0, 127, 5, 0, 0, 64, 0], [0, 100, 127, 20], 0, 10), P("RANDOM SLC", [0, 0, 127, 5, 0, 0, 64, 0], [0, 100, 127, 20], 0, 11), P("VEL SLICE", [0, 0, 127, 5, 0, 0, 64, 0], [0, 100, 127, 20], 0, 9), P("SCRUB", [0, 0, 127, 6, 0, 0, 64, 0], [10, 100, 127, 50], 0, 0), P("TAPE STOP", [0, 0, 127, 7, 0, 0, 64, 0], [0, 100, 127, 100], 0, 0), P("RATCHET", [0, 0, 127, 0, 0, 0, 64, 0], [0, 100, 127, 30], 0, 12), P("CHOKE", [0, 0, 127, 0, 0, 0, 64, 0], [0, 100, 127, 20], 0, 12), P("ROUND ROBIN", [0, 0, 127, 0, 0, 0, 64, 0], [0, 100, 127, 30], 0, 12), P("LEGATO", [0, 0, 127, 1, 0, 0, 64, 0], [4, 100, 127, 40], 0, 4), P("CHANCE", [0, 0, 127, 0, 0, 0, 64, 0], [0, 100, 127, 30], 0, 12), P("FEEDBACK", [0, 0, 127, 0, 0, 90, 60, 0], [0, 100, 127, 50], 0, 3), P("METAL COMB", [0, 0, 127, 1, 0, 118, 110, 0], [0, 100, 127, 60], 0, 7), P("DESTROY", [0, 0, 127, 0, 0, 40, 50, 70], [0, 100, 127, 40], 0, 0), P("RESAMPLE", [0, 0, 127, 2, 0, 0, 64, 0], [0, 100, 127, 40], 0, 0)] },
|
||
8: { name: "GRAIN", titles: ["GRAIN", "CLOUD"], edit: [E("SLOT", ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"], 0), D("POS", F.PCT, 0, 127, 0), D("SCAN", F.BIPCT, -64, 63, 0), D("SIZE", F.PCT, 0, 127, 64), D("DENSE", F.PCT, 0, 127, 70), D("SPRAY", F.PCT, 0, 127, 10), D("SPREAD", F.PCT, 0, 127, 0), D("REVRS", F.PCT, 0, 127, 0)],
|
||
presets: [P("CLOUD", [0, 0, 8, 70, 70, 20, 0, 0], [40, 100, 127, 70], 0, 5), P("FROZEN CLOUD", [0, 40, 0, 80, 85, 10, 2, 0], [60, 100, 127, 90], 0, 5), P("SCAN", [0, 0, 20, 60, 70, 5, 0, 0], [20, 100, 127, 60], 0, 5), P("STRETCH 0.5X", [0, 0, -36, 75, 80, 4, 0, 0], [10, 100, 127, 60], 0, 5), P("STRETCH 2X", [0, 0, 21, 65, 80, 4, 0, 0], [10, 100, 127, 60], 0, 5), P("SHIMMER", [0, 30, 4, 90, 80, 30, 0, 0], [80, 100, 127, 110], 0, 5), P("SPRAY", [0, 20, 0, 40, 100, 90, 30, 30], [20, 100, 127, 60], 0, 5), P("OCTAVES", [0, 30, 4, 70, 80, 20, 60, 0], [30, 100, 127, 80], 0, 5), P("REVERSE", [0, 0, 10, 80, 60, 10, 0, 127], [20, 100, 127, 60], 0, 5), P("GLITCH", [0, 0, 40, 20, 90, 40, 20, 40], [0, 100, 127, 30], 0, 3), P("KEY POSITION", [0, 0, 0, 55, 70, 4, 0, 0], [10, 100, 127, 50], 0, 6), P("LIVE DELAY", [0, 30, 0, 60, 60, 20, 0, 0], [10, 100, 127, 80], 0, 0), P("LIVE FREEZE", [0, 10, 0, 85, 90, 15, 0, 0], [40, 100, 127, 100], 0, 0), P("FEEDBACK", [0, 10, 6, 70, 75, 20, 4, 10], [30, 100, 127, 90], 0, 5)] },
|
||
};
|
||
const HP_PAGES = [
|
||
{ engine: "SAMPLE", name: "TRIG", ids: [83, 84, 85, 86], descs: [E("TRIG", ["NORM", "CHOKE", "RATCH", "RAND", "ROUND", "VEL", "LEGAT", "CHNCE"], 0), D("-", F.PCT, 0, 127, 64), E("RATE", ["1/4", "1/8", "1/8T", "1/16", "16T", "1/32"], 3), D("SLICES", F.INT, 2, 64, 16)] },
|
||
{ engine: "SAMPLE", name: "REC", ids: [87, 88, 89, 90], descs: [E("REC", ["OFF", "IN 1", "IN 2", "IN 4", "IN 8", "IN H", "MST 1", "MST 2", "MST 4", "MST 8", "MST H", "T1 1", "T1 2", "T1 4", "T1 8", "T1 H", "T2 1", "T2 2", "T2 4", "T2 8", "T2 H", "T3 1", "T3 2", "T3 4", "T3 8", "T3 H", "T4 1", "T4 2", "T4 4", "T4 8", "T4 H", "T5 1", "T5 2", "T5 4", "T5 8", "T5 H", "T6 1", "T6 2", "T6 4", "T6 8", "T6 H"], 0), D("WOW", F.PCT, 0, 127, 40), D("STOP", F.PCT, 0, 127, 64), D("DECAY", F.PCT, 0, 127, 64)] },
|
||
{ engine: "GRAIN", name: "TRAVEL", ids: [83, 84, 85, 86], descs: [E("TRAVEL", ["FWD", "REV", "PING", "RAND", "STRCH", "FREEZ", "KEY"], 0), D("REGION", F.PCT, 0, 127, 127), D("FEEDBK", F.PCT, 0, 127, 0), E("SHIMMR", ["OFF", "+OCT", "+5TH", "-OCT", "+2OCT"], 0)] },
|
||
{ engine: "GRAIN", name: "SOURCE", ids: [87, 88, 89, 90], descs: [E("WINDOW", ["HANN", "TRI", "FLAT", "PERC", "SWELL"], 0), D("WIDTH", F.PCT, 0, 127, 64), E("SOURCE", ["SLOT", "IN", "MST"], 0), E("REC", ["OFF", "IN 1", "IN 2", "IN 4", "IN 8", "IN H", "MST 1", "MST 2", "MST 4", "MST 8", "MST H", "T1 1", "T1 2", "T1 4", "T1 8", "T1 H", "T2 1", "T2 2", "T2 4", "T2 8", "T2 H", "T3 1", "T3 2", "T3 4", "T3 8", "T3 H", "T4 1", "T4 2", "T4 4", "T4 8", "T4 H", "T5 1", "T5 2", "T5 4", "T5 8", "T5 H", "T6 1", "T6 2", "T6 4", "T6 8", "T6 H"], 0)] },
|
||
{ engine: "GRAIN", name: "PITCH", ids: [72, 78], descs: [E("QUANT", ["FREE", "OCT", "5TH"], 0), D("DAMP", F.PCT, 0, 127, 127)] },
|
||
{ engine: "DRUM", name: "SAMPLES", ids: [61, 72, 80, 78], descs: [D("SMORPH", F.PCT, 0, 127, 0), E("BLEND", ["XFADE", "S>B", "B>S", "FOLW", "RING"], 0), D("SLOT", F.ENUM, 112, 127, 112, ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"]), D("MAP", F.ENUM, 125, 127, 125, ["SLOTS", "LANES", "KEYS"])] },
|
||
{ engine: "DRUM", name: "SAMPLES 2", ids: [75], descs: [D("SLEVEL", F.PCT, 0, 127, 127)] },
|
||
];
|
||
const HP_AMT = ["-", "-", "COUNT", "RANGE", "SLOTS", "RANGE", "-", "CHANCE"]; /* SAMPLE's AMOUNT by TRIG (eng_sample.c SMP_AMT) */
|
||
if (opt.hostPower) { ENG[4] = HP_ENG[4]; ENG[8] = HP_ENG[8]; }
|
||
const FM6_E = ENG.findIndex((e) => e.name === "FM6"), FM6_OWN = FM6.FACTORY_PK.length, DRUM_E = ENG.findIndex((e) => e.name === "DRUM");
|
||
/* factory PATTERNS[] (engines.c; the device loads them from SEQ > PATTERNS, presets only suggest one): absolute
|
||
notes, 0 rest; flags 1 accent, 2 slide, 4 tie (holds the previous note) */
|
||
const T_ = 4;
|
||
const PATTERNS = [
|
||
[[45, 45, 57, 45, 0, 48, 45, 55, 45, 0, 57, 52, 45, 48, 0, 50], [1, 0, 2, 0, 0, 0, 1, 2, 0, 0, 1, 0, 0, 2, 0, 1]],
|
||
[[0, 36, 0, 36, 0, 36, 0, 48, 0, 36, 0, 36, 0, 39, 0, 43], [0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]],
|
||
[[60, 0, 67, 0, 72, 67, 0, 64, 62, 0, 69, 0, 74, 69, 0, 67], [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]],
|
||
[[72, 0, 0, 74, 0, 0, 76, 0, 79, 0, 76, 0, 74, 0, 0, 0], [1, T_, 0, 2, T_, 0, 0, 0, 1, 0, 2, 0, 0, T_, T_, 0]],
|
||
[[60, 0, 0, 0, 0, 0, 0, 0, 57, 0, 0, 0, 55, 0, 0, 0], [0, T_, T_, T_, T_, T_, T_, 0, 0, T_, T_, 0, 0, T_, T_, 0]],
|
||
[[0, 0, 60, 0, 0, 63, 0, 0, 0, 0, 60, 0, 0, 65, 0, 63], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]],
|
||
[[72, 0, 0, 79, 0, 0, 84, 0, 0, 0, 76, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
|
||
[[36, 0, 0, 0, 0, 0, 0, 36, 0, 0, 34, 0, 0, 0, 0, 0], [1, T_, T_, T_, 0, 0, 0, 0, 0, 0, 0, T_, T_, T_, 0, 0]],
|
||
[[60, 61, 62, 67, 64, 65, 60, 69, 68, 70, 62, 67, 72, 72, 74, 64], [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]],
|
||
[[60, 60, 61, 61, 62, 0, 63, 63, 64, 65, 65, 0, 66, 66, 66, 67], [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]],
|
||
[[60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75], [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]],
|
||
[[36, 42, 42, 42, 38, 42, 36, 42, 36, 42, 42, 36, 38, 42, 46, 42], [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]], /* 12 BEAT (DRUM) */
|
||
[[48, 51, 55, 60, 63, 67, 72, 75, 48, 51, 55, 60, 63, 67, 72, 75], [1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]], /* 13 ARP */
|
||
[[36, 0, 42, 0, 38, 0, 42, 36, 0, 36, 42, 0, 38, 0, 42, 46], [1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0]], /* 14 BOOM BAP (V10.34) */
|
||
];
|
||
for (let op = 0; op < 4; op++) TP.push(D("ATK", F.TIME, 0, 127, 0), D("DEC", F.TIME, 0, 127, 0), D("SUS", F.PCT, 0, 127, 127), D("REL", F.TIME, 0, 127, 0), D("LEVEL", F.PCT, 0, 127, 127));
|
||
TP.push(D("ROTATE", F.INT, -32, 32, 0), D("PITCH", F.SEMI, -24, 24, 0)); /* 81, 82: STRETCH's ROTATE, TRACK's PITCH (JIANT; SHIFT until 0.6.91; the chord keys before) */
|
||
for (const l of ["KICK", "SNARE", "CLAP", "HATCL", "HATOP", "TOM", "RIM", "BELL"]) TP.push(D(l, F.PCT, 0, 127, 127)); /* 83..90: DRUM lane levels */
|
||
TP.push(E("TYPE", ["SOFT", "HARD", "FOLD", "CRUSH", "RECT", "AMP"], 0), D("TONE", F.BIPCT, -64, 63, 0), /* 91, 92: DIST (JIANT, FUNB) */
|
||
D("LEN", F.STEPS, 1, 16, 16), E("DIV", NDIV, 2), D("SLEW", F.PCT, 0, 127, 0)); /* 93..95: the modulation sequence */
|
||
for (let k = 0; k < 16; k++) TP.push(D("LEVEL", F.PCT, 0, 127, 0)); /* 96..111: its levels */
|
||
TP.push(E("TYPE", ["LP", "HP", "BP", "COMB", "COMB-", "MS20", "LP24"], 0), /* 112: the FILTER's type (JIANT 0.5) */
|
||
D("CUT", F.CUTOFF, 0, 127, 127), D("RES", F.PCT, 0, 127, 0)); /* 113, 114: the other engines' */
|
||
const P_COUNT = 123, G_COUNT = 73, NSTEP = 64, P_E0 = 115, G_ENGSEL = 20, P_SLCR = 45;
|
||
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
|
||
const enumOrig = (d, v) => d.fmt === F.ENUM && d.names ? aliasOf(d.names, v - d.min) + d.min : v; /* params.c enum_orig */
|
||
/* tracks (firmware v3): four synth parts (1.0), six (JIANT 0.6); engine / preset / p / step below are the selected track's */
|
||
const NTRK = 6;
|
||
const newTrack = () => ({ engine: 0, preset: 0, fm6: FM6.INIT_PK.slice(),
|
||
p: TP.map((d) => d.def).concat(new Array(8).fill(0)),
|
||
motion: {on: true, events: []},
|
||
step: Array.from({ length: NSTEP }, () => ({ chance: 100, ratchet: 1, n: 0, notes: [0, 0, 0, 0], time: 2, flags: 0, vel: 0, hit: 0, acc: 0 })) });
|
||
const st = {
|
||
tracks: Array.from({ length: NTRK }, newTrack), sel: 0, rec: 0,
|
||
g: GP.map((d) => d.def),
|
||
slots: [null, null, null, null], songRows: [], chainPlaying: false, chainRow: 0, chainRemaining: 0,
|
||
bank: new Array(opt.slots || 32).fill(null), /* user presets: {engine, name, p, pattern, grid, fm6 (FM6: its patch)} */
|
||
uiCaps: opt.legacy || opt.v3 || opt.v5 ? 0 : opt.uiCaps ?? 9,
|
||
palette: 0, font: 0, monitor: 0, filter: 0, bankSig: 0,
|
||
vbank: { valid: false, name: "", voices: new Array(32).fill(null) }, vtx: null, /* (0.6.11) FM6's voice bank */
|
||
palettes: ["GREY", "GREEN", "AMBER", "ICE", "VIOLET", "ROSE", "PAPER", "HI-CON", "NIGHT", "MONO"],
|
||
favorites: Array.from({ length: ENG.length + 1 }, () => []),
|
||
watch: false, v4: false, lastReq: 0,
|
||
};
|
||
for (const k of ["engine", "preset", "p", "step"]) {
|
||
Object.defineProperty(st, k, { enumerable: false, get: () => st.tracks[st.sel][k], set: (v) => { st.tracks[st.sel][k] = v; } });
|
||
}
|
||
const watchMs = opt.watchMs || 3000;
|
||
const hpDesc = (id) => { /* (ports/) editor.c ed_tdesc: engines.c hp_xdesc */
|
||
if (!opt.hostPower) return null;
|
||
const pg = HP_PAGES.find((x) => x.engine === ENG[st.engine].name && x.ids.includes(id));
|
||
const d = pg && pg.descs[pg.ids.indexOf(id)];
|
||
return d && pg.engine === "SAMPLE" && id === pg.ids[1] && pg.name === "TRIG" ? { ...d, label: HP_AMT[st.p[pg.ids[0]]] || "-" } : d;
|
||
};
|
||
const desc = (scope, id) => (scope === 0 && id < P_COUNT ? hpDesc(id) || (id >= P_E0 ? ENG[st.engine].edit[id - P_E0] : TP[id])
|
||
: scope === 1 && id < G_COUNT ? GP[id] : null);
|
||
const EMPTY = { n: 0, notes: [0, 0, 0, 0], time: 2, flags: 0, vel: 0, hit: 0, acc: 0, chance: 100, ratchet: 1 };
|
||
const isDrum = () => ENG[st.engine].name === "DRUM";
|
||
const clearSteps = () => st.step.forEach((s) => Object.assign(s, EMPTY, { notes: [0, 0, 0, 0] }));
|
||
function toGrid(s) { /* eng_drum.c step_to_grid: a lane's own note becomes its hit */
|
||
if (s.time !== 0) return;
|
||
const keep = s.notes.slice(0, s.n).filter((n) => { const l = drumLane(n); if (n !== LANE_NOTE[l]) return true; s.hit |= 1 << l; return false; });
|
||
s.notes = [...keep, 0, 0, 0, 0].slice(0, 4); s.n = keep.length;
|
||
if (!s.n && s.flags & 1) { s.acc |= s.hit; s.flags &= ~1; }
|
||
}
|
||
function loadPat16(pat) { /* ui.c load_pat16 (into a DRUM track: its grid) */
|
||
const ps = stepsFromPattern(pat);
|
||
st.step.forEach((s, i) => { Object.assign(s, EMPTY, i < 16 ? ps[i] : { notes: [0, 0, 0, 0] }); if (isDrum()) toGrid(s); });
|
||
st.p[29] = 16;
|
||
}
|
||
const loadPattern = (k) => loadPat16(PATTERNS[k][0].map((n, i) => [n, PATTERNS[k][1][i]]));
|
||
function applyPreset(pi) {
|
||
const e = ENG[st.engine];
|
||
|
||
pi = aliasOf(e.presets.map((x) => x.name), pi % e.presets.length);
|
||
const pr = e.presets[pi];
|
||
st.preset = pi;
|
||
for (let i = 0; i < 8; i++) st.p[P_E0 + i] = pr.e[i];
|
||
[1, 2, 3, 4].forEach((id, k) => { st.p[id] = pr.env[k]; });
|
||
if (e.name === "VOICE") { st.p[61] = (pr.xp || 0) & 3; st.p[74] = (pr.xp || 0) >> 2; } /* (0.8.5) LANG, LYRIC (P_VLANG
|
||
= P_FM1_ATK 61, P_VLYR = P_FM3_REL 74; ui.c apply_preset_to) */
|
||
else { /* (V10.36) the other engines' xp: BREATHE, the LFO DRIFT on FILTER
|
||
(P_LD_FLT 14, xp & 63), PITCH (P_LD_PIT 13, bit 6), slow (bit 7:
|
||
RATE -14, else -1); none: the LFO's defaults (ui.c preset_load) */
|
||
for (const i of [9, 10, 13, 14]) st.p[i] = TP[i].def;
|
||
if (pr.xp) { st.p[10] = 5; st.p[9] = pr.xp & 0x80 ? -14 : -1; st.p[14] = pr.xp & 63; st.p[13] = pr.xp >> 6 & 1; }
|
||
}
|
||
st.p[37] = pr.mono ? 2 : 0;
|
||
st.p[33] = 0; st.p[34] = 24; st.p[35] = 28; st.p[36] = 36;
|
||
for (let i = P_SLCR + 4; i < P_E0; i++) if (!trackOwn(i, P_E0)) st.p[i] = TP[i].def; /* a factory preset turns the
|
||
matrix off; the SLICER, the chord keys, the steps and the other track
|
||
settings stay (ui.c apply_preset_to) */
|
||
if (opt.hostPower) /* (ports/) engines.c hp_preset_x: the extra values' defaults */
|
||
for (const pg of HP_PAGES) if (pg.engine === e.name) pg.ids.forEach((id, k) => { st.p[id] = pg.descs[k].def; });
|
||
if (st.engine === FM6_E) { /* eng_fm6.c fm6_track_loaded */
|
||
const t = st.tracks[st.sel];
|
||
t.own = null;
|
||
if (st.p[P_E0 + 7] < FM6_OWN) { t.fm6 = FM6.FACTORY_PK[st.p[P_E0 + 7]].slice(); t.slot = st.p[P_E0 + 7]; } else fm6Adopt(t);
|
||
}
|
||
}
|
||
/* SLOT s turned (eng_fm6.c fm6_poll): F1..F8 that factory patch (from OWN the own patch kept aside), OWN the own
|
||
patch back */
|
||
function fm6Slot(t, s) {
|
||
if (s === t.slot) return;
|
||
const bk = s > FM6_OWN && s <= FM6_OWN + 32 ? s - FM6_OWN - 1 : -1; /* (0.6.11) B1..B32: the voice bank's */
|
||
if (bk >= 0 && !st.vbank.voices[bk]) { t.p[P_E0 + 7] = t.slot ?? FM6_OWN; return; } /* (none there: refused) */
|
||
if (s >= FM6_OWN && bk < 0) { if (t.own) t.fm6 = t.own; t.own = null; t.slot = FM6_OWN; return; }
|
||
if (t.slot === FM6_OWN && !t.own) t.own = t.fm6.slice();
|
||
t.fm6 = (bk >= 0 ? st.vbank.voices[bk] : FM6.FACTORY_PK[s]).slice(); t.slot = s;
|
||
}
|
||
/* t's patch was put in as its own (eng_fm6.c fm6_adopt): SLOT = the factory patch it equals, else OWN */
|
||
function fm6Adopt(t) {
|
||
t.own = null;
|
||
if (t.engine !== FM6_E) return;
|
||
const k = FM6.FACTORY_PK.findIndex((pk) => pk.every((x, i) => x === t.fm6[i]));
|
||
t.p[P_E0 + 7] = t.slot = k < 0 ? FM6_OWN : k;
|
||
}
|
||
function setEngine(ei) {
|
||
if (ei % ENG.length === 1) { fm4Load(0); return; } /* DIGITAL (retired): its first preset, as FM6 (ui.c set_engine_of) */
|
||
if ([4, 6, 9].includes(ei % ENG.length) && !(opt.hostPower && ei % ENG.length === 4)) ei = 0; /* ((ports/) SAMPLE is there) */ /* SAMPLE TRIO PHYS (retired, core.h eng_gone): ANALOG; (snd5) 8 STRING 13 ADD */
|
||
st.engine = ei % ENG.length;
|
||
for (let i = 0; i < 8; i++) st.p[P_E0 + i] = ENG[st.engine].edit[i].def;
|
||
applyPreset(0);
|
||
}
|
||
/* the selected track's sound = p, DIGITAL's values, converted (ui.c fm4_apply) */
|
||
function fm4Apply(p) {
|
||
const r = FM4.convert(p, P_E0);
|
||
st.engine = FM6_E; st.preset = r.preset; st.p = r.p;
|
||
st.tracks[st.sel].fm6 = FM6.pack(r.voice);
|
||
fm6Adopt(st.tracks[st.sel]); /* (the converted patch is the track's own: SLOT OWN) */
|
||
}
|
||
function fm4Load(k) { /* a DIGITAL preset number (ui.c fm4_load_preset) */
|
||
const p = st.p.map((x, i) => (i < P_E0 && !trackOwn(i, P_E0) ? TP[i].def : x));
|
||
fm4Apply(FM4.presetValues(p, k, P_E0));
|
||
}
|
||
const snapshot = (name) => { /* (upreset.c up_store: a DRUM track that strikes a lane: its grid; an FM6
|
||
track: its patch, up_fm6.c) */
|
||
const grid = isDrum() ? gridFromSteps(st.step) : null;
|
||
const fm6 = st.engine === FM6_E ? st.tracks[st.sel].fm6.slice() : null;
|
||
return patternUsed(grid) ? { engine: st.engine, name, p: st.p.slice(), pattern: null, grid, fm6 }
|
||
: { engine: st.engine, name, p: st.p.slice(), pattern: patternFromSteps(st.step), grid: null, fm6 };
|
||
};
|
||
const ratchetOn = () => !!syncCaps() && !opt.noRatchet; /* (INFO 52 01 04, after the sync tag) */
|
||
const lanesOn = () => ratchetOn() && !opt.noLanes; /* (0.8.5, INFO 4F 01 07, after the voice bank) */
|
||
const stepOut = (x, b, lanes) => { b(x.n); x.notes.forEach(b); b(x.time); b(x.flags); b(x.vel); hitsEnc(x.hit, x.acc).forEach(b); if (!opt.legacy && !opt.v3 && !opt.v5) b(x.chance ?? 100); if (ratchetOn()) b(x.ratchet ?? 1);
|
||
if (lanes && lanesOn()) for (let l = 0; l < 8; l++) b(x.lanes ? x.lanes[l] : 0); }; /* (0.8.5: asked for, editor.c) */
|
||
function stepIn(x, a) { /* editor.c ed_step_put: n, 4 notes, time, flags, vel [, hits (3) [, chance [, ratchet]]] */
|
||
x.n = Math.min(4, a[0]); x.notes = a.slice(1, 5); x.time = Math.min(2, a[5]); x.flags = a[6] & 3; x.vel = a[7];
|
||
if (a.length >= 11) { x.hit = a[8] | (a[10] & 1) << 7; x.acc = (a[9] | (a[10] & 2) << 6) & x.hit; }
|
||
if (a.length >= 12) x.chance = Math.min(100, a[11]);
|
||
if (a.length >= 13 && ratchetOn()) x.ratchet = Math.max(1, Math.min(4, a[12]));
|
||
if (a.length >= 21 && lanesOn()) x.lanes = a.slice(13, 21).map((m) => (m > 6 ? 0 : m));
|
||
}
|
||
/* a few user presets to start with, each with its preset's suggested pattern stored (as UP_STORE would) */
|
||
[[0, 0, 0, "MY LEAD"], [1, FM6_E, 1, "GLASS BELL"], [2, 2, 3, "PHASE RESO"], [5, 3, 2, "8BIT ARP"]].forEach(([slot, e, p, name]) => {
|
||
setEngine(e); applyPreset(p);
|
||
if (ENG[e].presets[p].pat) loadPattern(ENG[e].presets[p].pat - 1);
|
||
st.bank[slot] = snapshot(name);
|
||
clearSteps(); st.p[29] = 16;
|
||
});
|
||
/* the power-on sounds (engines.c TRK_DEF, 0.9.9): DRUM-X, SINGER EN, CMOS BIRD, BYTEBEAT, FAT BASS, TINE EP */
|
||
[[1, 5, 9], [2, 14, 0], [3, 3, 0], [4, 0, 14], [5, FM6_E, 0], [0, 10, 0]].forEach(([i, e, p]) => { st.sel = i; setEngine(e); applyPreset(p); });
|
||
/* the device powers on with its sequencers empty; the mock starts as a little demo to look at: track 1 (DRUM-X)
|
||
with BEAT, track 5 (the bass) with OFFBEAT (as SEQ > PATTERNS would load them), the voice left, the bird right */
|
||
st.sel = 4; loadPattern(1);
|
||
st.sel = 0; loadPattern(11);
|
||
st.tracks[1].p[39] = -24; st.tracks[2].p[39] = 20; st.tracks[2].p[0] = 92;
|
||
const project = () => JSON.parse(JSON.stringify({ tracks: st.tracks, sel: st.sel, g: st.g, songRows: st.songRows }));
|
||
st.slots[0] = project();
|
||
|
||
function handle(cmd, a) {
|
||
const out = [];
|
||
const b = (x) => out.push(x & 0x7F), v = (x) => out.push(...v14enc(x)), s = (x) => out.push(...strEnc(x));
|
||
if (opt.legacy && cmd >= CMD.UP_LIST) return null;
|
||
if (opt.v3 && cmd >= CMD.TRACK_PARAM) return null;
|
||
if (opt.v5 && cmd >= CMD.SONG) return null;
|
||
if (!st.uiCaps && cmd >= CMD.UI_STATE) return null;
|
||
const uiState = () => {
|
||
const sig = JSON.stringify(st.favorites).split("").reduce((h, c) => Math.imul(h ^ c.charCodeAt(0), 16777619) >>> 0, st.filter);
|
||
[st.uiCaps, st.palette, st.uiCaps & 2 ? st.font : 127, st.uiCaps & 4 ? st.monitor : 127, st.uiCaps & 8 ? st.filter : 127].forEach(b);
|
||
for (const n of [sig, st.bankSig]) for (let i = 0; i < 4; i++) b(n >>> (i * 7));
|
||
};
|
||
const NB = st.bank.length;
|
||
switch (cmd) {
|
||
case CMD.UP_LIST: {
|
||
if (a.length < 2) return null;
|
||
const start = a[0], n = Math.max(0, Math.min(a[1], UP.LIST_MAX, NB - start));
|
||
b(start); b(n); b(NB);
|
||
for (let i = start; i < start + n; i++) { const u = st.bank[i]; b(u ? 1 : 0); b(u ? u.engine : 0); s(u ? u.name : ""); }
|
||
break;
|
||
}
|
||
case CMD.UP_GET: {
|
||
if (a.length < 1 || a[0] >= NB) return null;
|
||
const u = st.bank[a[0]];
|
||
b(a[0]); b(u ? 1 : 0); b(u ? u.engine : 0); s(u ? u.name : "");
|
||
for (let i = 0; i < P_COUNT; i++) v(u ? u.p[i] : 0);
|
||
if (u && u.grid) { /* kind 1: the grid's low 7 bits, then its bit 7s */
|
||
for (let i = 0; i < UP.PAT; i++) { const x = hitsEnc(...u.grid[i]); b(x[0]); b(x[1]); }
|
||
b(1);
|
||
for (let i = 0; i < UP.PAT; i++) b(hitsEnc(...u.grid[i])[2]);
|
||
} else {
|
||
for (let i = 0; i < UP.PAT; i++) { const x = u ? u.pattern[i] : [0, 0]; b(x[0]); b(x[1]); }
|
||
b(0);
|
||
}
|
||
break;
|
||
}
|
||
case CMD.UP_PUT: {
|
||
if (a.length < 3) return null;
|
||
const r = new Reader(a);
|
||
let rc = 0;
|
||
try {
|
||
const slot = r.b(), engine = r.b(), name = r.s(), p = [], raw = [];
|
||
let pattern = null, grid = null;
|
||
for (let i = 0; i < P_COUNT; i++) p.push(r.v());
|
||
for (let i = 0; i < UP.PAT; i++) raw.push([r.b(), r.b()]);
|
||
const tail = a.length - r.i;
|
||
if (tail !== 0 && (tail !== 1 + UP.PAT || a[r.i] > 1)) throw new Error("bad preset extension");
|
||
if (tail && a[r.i] === 1) { /* kind 1: a complete drum grid */
|
||
r.b();
|
||
grid = raw.map(([h, c]) => { const x = r.b(), hit = h | (x & 1) << 7; return [hit, (c | (x & 2) << 6) & hit]; });
|
||
} else pattern = raw.map(([n, f]) => patNorm(n, f));
|
||
if (slot >= NB || engine >= ENG.length || !name.length || name.length > UP.NAME_MAX || /[^\x20-\x7E]/.test(name)) rc = 1;
|
||
else {
|
||
const saved = st.engine; /* values clamped to the ranges of that engine */
|
||
const pc = fromPerc({ engine, p }, ENG.map((x) => x.name), P_E0); /* SAMPLE PERC: DRUM (upreset.c up_migrate) */
|
||
st.engine = pc ? pc.engine : engine;
|
||
st.bank[slot] = { engine: st.engine, name, p: (pc ? pc.p : p).map((x, i) => { const d = desc(0, i); return clamp(x, d.min, d.max); }), pattern, grid };
|
||
st.engine = saved;
|
||
}
|
||
} catch (e) { rc = 1; }
|
||
b(a[0]); b(rc);
|
||
break;
|
||
}
|
||
case CMD.UP_STORE: {
|
||
if (a.length < 2) return null;
|
||
const name = new Reader(a.slice(1)).s();
|
||
const rc = a[0] >= NB || name.length > UP.NAME_MAX ? 1 : 0;
|
||
if (!rc) st.bank[a[0]] = snapshot(name || `${ENG[st.engine].name} ${String(a[0] + 1).padStart(2, "0")}`); /* (FM6: its patch) */
|
||
b(a[0]); b(rc);
|
||
break;
|
||
}
|
||
case CMD.UP_LOAD: {
|
||
if (a.length < 1) return null;
|
||
const u = st.bank[a[0]];
|
||
if (u) { /* the sound only (upreset.c up_load): the steps and the track's own */
|
||
const own = st.p.slice(); /* parameters (TRACK_OWN: mix, ARP, SCL, LEN.., SLICER) stay */
|
||
const p = u.p.map((x, i) => (trackOwn(i, P_E0) ? own[i] : x));
|
||
if (u.engine === 1) fm4Apply(p); /* a DIGITAL record (kept as it is): FM6 */
|
||
else { st.engine = u.engine; st.preset = 0; st.p = p; }
|
||
if (u.engine === FM6_E) { /* its own patch (up_fm6.c upf_track_load); none: SLOT's factory / init */
|
||
const t = st.tracks[st.sel], s = p[P_E0 + 7];
|
||
t.fm6 = (u.fm6 || (s < FM6_OWN ? FM6.FACTORY_PK[s] : FM6.INIT_PK)).slice();
|
||
fm6Adopt(t);
|
||
}
|
||
}
|
||
b(a[0]); b(u ? 0 : 1);
|
||
break;
|
||
}
|
||
case CMD.UP_ERASE:
|
||
if (a.length < 1) return null;
|
||
if (a[0] < NB) { st.bank[a[0]] = null; st.favorites[ENG.length][a[0]] = false; }
|
||
b(a[0]); b(a[0] < NB ? 0 : 1);
|
||
break;
|
||
case CMD.WATCH:
|
||
if (a.length < 1) return null;
|
||
st.watch = !!(a[0] & 1);
|
||
st.v4 = st.watch && !opt.v3 && !!(a[0] & 2); /* v4: TRACK_CHANGED pushes too */
|
||
b((st.watch ? 1 : 0) | (st.v4 ? 2 : 0));
|
||
break;
|
||
case CMD.PING:
|
||
b(0);
|
||
break;
|
||
case CMD.UI_STATE: uiState(); break;
|
||
case CMD.UI_PALETTES: b(st.palettes.length); st.palettes.forEach(s); break;
|
||
case CMD.UI_SET: {
|
||
const id = a[0], val = a[1], key = ["palette", "font", "monitor", "filter"][id];
|
||
const rc = a.length !== 2 || !key ? 1 : !(st.uiCaps & 1 << id) ? 2 : val >= (id === 0 ? st.palettes.length : id === 2 ? 3 : 2) ? 1 : 0;
|
||
if (!rc) st[key] = val;
|
||
b(rc || (opt.noFlash ? 3 : opt.deferSettings ? 4 : 0)); b(id ?? 127); b(val ?? 127); uiState(); break;
|
||
}
|
||
case CMD.FAV_GET: case CMD.FAV_SET: {
|
||
if (!(st.uiCaps & 8)) { b(2); break; }
|
||
const engine = a[0], preset = v14dec(a[1], a[2]), count = a[3];
|
||
const limit = engine === ENG.length ? st.bank.length : engine < ENG.length ? ENG[engine].presets.length : 0;
|
||
if (a.length !== 4 || preset < 0 || preset >= limit ||
|
||
(cmd === CMD.FAV_GET ? !count || count > 32 || preset + count > limit : count > 1 || engine === ENG.length && count && !st.bank[preset])) { b(1); break; }
|
||
if (cmd === CMD.FAV_SET) st.favorites[engine][preset] = !!count;
|
||
b(cmd === CMD.FAV_SET ? (opt.noFlash ? 3 : opt.deferSettings ? 4 : 0) : 0); b(engine); v(preset); b(count);
|
||
if (cmd === CMD.FAV_GET) for (let i = 0; i < count; i++) b(!!st.favorites[engine][preset + i]);
|
||
break;
|
||
}
|
||
case CMD.MOTION: {
|
||
const track = st.tracks[a[0]], m = track && track.motion;
|
||
if (!m) return null;
|
||
let rc = 0;
|
||
if (a[1] >= 5 && opt.noLocks) return null;
|
||
if (a.length > 1 && a[1] !== 7 && st.chainPlaying) rc = 3;
|
||
else if (a[1] === 1) m.on = !!a[2];
|
||
else if (a[1] === 2) m.events = [];
|
||
else if (a[1] === 6) m.events = m.events.filter(e => !e.kind || (a[2] !== 127 && e.step !== a[2])); /* (1.1) a step's locks */
|
||
else if (a[1] === 3 || a[1] === 4 || a[1] === 5) { /* (1.1: 5, a lock; one record per step and id, of either kind) */
|
||
const at = m.events.findIndex(e => e.step === a[2] && e.param === a[3]);
|
||
if (a[1] === 4) { if (at >= 0) m.events.splice(at, 1); }
|
||
else if (at < 0 && st.tracks.reduce((n,t) => n + t.motion.events.length, 0) >= 64) rc = 2;
|
||
else { const e = {step:a[2],param:a[3],value:v14dec(a[4],a[5]),kind:a[1] === 5 ? 1 : 0}; if (at >= 0) m.events[at] = e; else m.events.push(e); }
|
||
if (!rc && a[1] !== 4) m.on = true;
|
||
}
|
||
[a[0],rc,+m.on,m.events.length,64].forEach(b);
|
||
m.events.forEach(e => {b(e.step);b(e.param);v(e.value);});
|
||
if (a[1] >= 5) m.events.forEach(e => b(e.kind ? 1 : 0)); /* (1.1) the kinds after ops 5..7 */
|
||
break;
|
||
}
|
||
case CMD.INFO:
|
||
s(opt.legacy ? "FELUCCA 0.4 BETA (MOCK)" : "FELUCCA v1.0 (MOCK)"); b(ENG.length); b(P_COUNT); b(G_COUNT); b(NSTEP); b(P_E0);
|
||
ENG.forEach((e) => s(e.name));
|
||
if (!opt.legacy) b(NTRK);
|
||
if (!opt.legacy && !opt.v3 && !opt.v5) {
|
||
b(16);
|
||
if (st.uiCaps) { b(0x55); b(1); b(st.uiCaps); b(0x4d); b(1); b(64); b(1); if (!opt.noFm6) { b(0x46); b(1); b(FM6.FACTORY_PK.length); b(0); }
|
||
if (syncCaps()) { b(0x53); b(1); b(syncCaps()); if (!opt.noFm6) { b(0x50); b(1); b(3); } if (ratchetOn()) { b(0x52); b(1); b(4); if (!opt.noLocks) { b(0x4C); b(1); b(1); } }
|
||
if (!opt.noFm6 && !opt.noVbank && ratchetOn()) { b(0x56); b(1); b(32); }
|
||
if (lanesOn()) { b(0x4F); b(1); b(7); } } } /* (FM6 v2: no bank, preset patches; 0.6.11: the voice bank; 0.8.5: the lanes' modes) */
|
||
if (st.uiCaps && !opt.noLyric && !opt.noFormula) { b(0x45); b(2); b(64); b(12); b(0x43); b(2); b(1); b(5); } /* (1.5) 'E': FORMULA, 'C' */
|
||
if (opt.board || opt.hostPower) { b(0x44); b(1); b(opt.board || 3); } /* (SMK-37, ports/) 'D': the device */
|
||
if (opt.hostPower) { b(0x48); b(2); b(15); b(16); } /* (ports/) 'H': SAMPLE GRAIN DRUM-X's samples, 16 slots */
|
||
if (st.uiCaps && !opt.noLyric) { b(0x59); b(1); b(63); } /* (0.8.5) LYRIC, the last tag */
|
||
}
|
||
break;
|
||
case CMD.FORMULA: { /* (1.5) editor.c ED_FORMULA (the mock: its length and header checked) */
|
||
if (opt.noFormula || a.length < 2 || a[0] >= NTRK || a[1] > 2) return null;
|
||
const tr = st.tracks[a[0]];
|
||
let rc = 0;
|
||
if (a[1] === 2) tr.formula = [];
|
||
else if (a[1] === 1) { const c = FVM.unpack7(Array.from(a.slice(2))); if (c.length < 2 || c.length > 64 || c[0] > 3) rc = 1; else tr.formula = c; }
|
||
const f = tr.formula || [];
|
||
b(a[0]); b(rc); b(f.length); FVM.pack7(f).forEach(b);
|
||
break;
|
||
}
|
||
case CMD.LYRIC: { /* (0.8.5) editor.c ED_LYRIC */
|
||
if (opt.noLyric || !a.length || a[0] >= NTRK) return null;
|
||
const tr = st.tracks[a[0]];
|
||
let rc = 0;
|
||
if (a.length > 1) {
|
||
let txt = "";
|
||
for (let i = 1; i < a.length && a[i]; i++) txt += String.fromCharCode(a[i] >= 32 && a[i] <= 126 ? a[i] : 32);
|
||
if (txt.length > 63) { txt = txt.slice(0, 63); rc = 1; }
|
||
tr.lyric = txt;
|
||
}
|
||
b(a[0]); b(rc); s(tr.lyric || "");
|
||
break;
|
||
}
|
||
case CMD.GET: case CMD.SET: {
|
||
if (a.length < 2) return null;
|
||
const d = desc(a[0], a[1]);
|
||
if (!d) return null;
|
||
const arr = a[0] ? st.g : st.p;
|
||
if (cmd === CMD.SET && a.length >= 4) {
|
||
if (a[0] === 1 && a[1] === G_ENGSEL) setEngine(clamp(v14dec(a[2], a[3]), 0, ENG.length - 1));
|
||
else if (d.max > d.min) arr[a[1]] = enumOrig(d, clamp(v14dec(a[2], a[3]), d.min, d.max));
|
||
if (!a[0] && a[1] === P_E0 + 7 && st.engine === FM6_E) fm6Slot(st.tracks[st.sel], arr[a[1]]); /* PTCH (fm6_poll) */
|
||
}
|
||
b(a[0]); b(a[1]); v(arr[a[1]]);
|
||
break;
|
||
}
|
||
case CMD.DUMP:
|
||
b(st.engine); b(st.preset); st.p.forEach(v); st.g.forEach(v);
|
||
break;
|
||
case CMD.TRACK:
|
||
if (a.length >= 1 && a[0] < NTRK) st.sel = a[0];
|
||
b(st.sel); b(NTRK);
|
||
st.tracks.forEach((t, i) => { b(t.engine); b(t.preset); v(t.p[0]); b(t.p[40] ? 1 : 0); b((st.rec >> i) & 1); });
|
||
break;
|
||
case CMD.TRACK_MIX: {
|
||
if (a.length < 1 || a[0] >= NTRK) return null;
|
||
const t = st.tracks[a[0]];
|
||
if (a.length >= 4) {
|
||
t.p[0] = clamp(v14dec(a[1], a[2]), 0, 127);
|
||
t.p[40] = a[3] ? 1 : 0;
|
||
}
|
||
b(a[0]); v(t.p[0]); b(t.p[40] ? 1 : 0);
|
||
break;
|
||
}
|
||
case CMD.TRACK_DUMP: {
|
||
if (a.length < 1 || a[0] >= NTRK) return null;
|
||
const t = st.tracks[a[0]];
|
||
b(a[0]); b(t.engine); b(t.preset); t.p.forEach(v);
|
||
break;
|
||
}
|
||
case CMD.TRACK_PARAM: {
|
||
if (a.length < 2 || a[0] >= NTRK || a[1] >= P_COUNT) return null;
|
||
const t = st.tracks[a[0]], d = a[1] >= P_E0 ? ENG[t.engine].edit[a[1] - P_E0] : TP[a[1]];
|
||
if (a.length >= 4 && d.max > d.min) t.p[a[1]] = enumOrig(d, clamp(v14dec(a[2], a[3]), d.min, d.max));
|
||
b(a[0]); b(a[1]); v(t.p[a[1]]);
|
||
break;
|
||
}
|
||
case CMD.TRACK_STEP: {
|
||
if (a.length < 2 || a[0] >= NTRK || a[1] >= NSTEP) return null;
|
||
const x = st.tracks[a[0]].step[a[1]];
|
||
if (a.length >= 10) stepIn(x, a.slice(2));
|
||
b(a[0]); b(a[1]); stepOut(x, b, a.length === 23 || (a.length === 3 && a[2] === 1));
|
||
break;
|
||
}
|
||
case CMD.DESC: {
|
||
if (a.length < 2) return null;
|
||
const d = desc(a[0], a[1]);
|
||
if (!d) return null;
|
||
b(a[0]); b(a[1]); b(d.fmt); v(d.min); v(d.max); v(d.def); s(d.label); s(d.unit || "");
|
||
if (d.fmt === F.ENUM && d.names) for (let i = 0; i <= d.max - d.min && i < 32; i++) s(d.names[i]);
|
||
break;
|
||
}
|
||
case CMD.STEP_GET: case CMD.STEP_SET: {
|
||
if (a.length < 1 || a[0] >= NSTEP) return null;
|
||
const x = st.step[a[0]];
|
||
if (cmd === CMD.STEP_SET && a.length >= 9) stepIn(x, a.slice(1));
|
||
b(a[0]); stepOut(x, b, a.length === 22 || (cmd === CMD.STEP_GET && a.length === 2 && a[1] === 1));
|
||
break;
|
||
}
|
||
case CMD.FM6B_BEGIN: case CMD.FM6B_WRITE: case CMD.FM6B_END: case CMD.FM6B_LIST: { /* (0.6.11) fm6_vbank.c */
|
||
if (opt.noFm6 || !st.uiCaps) return null;
|
||
const vb = st.vbank;
|
||
if (cmd === CMD.FM6B_BEGIN) {
|
||
if (a.length) { b(1); break; }
|
||
st.vtx = { voices: new Array(32).fill(null) }; b(0);
|
||
} else if (cmd === CMD.FM6B_WRITE) {
|
||
b(a.length ? a[0] : 127);
|
||
if (!st.vtx) b(5);
|
||
else if (a.length !== 1 + 128 || a[0] > 31 || st.vtx.voices[a[0]]) b(1);
|
||
else { st.vtx.voices[a[0]] = Array.from(a.slice(1)); b(0); }
|
||
} else if (cmd === CMD.FM6B_END) {
|
||
let rc = a.length !== 15 || a[14] > 15 ? 1 : !st.vtx ? 5 : 0;
|
||
if (!rc) {
|
||
const crc = (a[10] | a[11] << 7 | a[12] << 14 | a[13] << 21 | a[14] << 28) >>> 0;
|
||
const tx = st.vtx; st.vtx = null;
|
||
if (crc32(tx.voices.filter(Boolean).flat()) !== crc) rc = 2;
|
||
else {
|
||
st.vbank = { valid: true, name: String.fromCharCode(...a.slice(0, 10)).replace(/[\s\0]+$/, ""), voices: tx.voices };
|
||
for (const t of st.tracks) /* a track on a bank slot keeps its voice, as its own */
|
||
if (t.slot > FM6_OWN) { t.own = null; t.p[P_E0 + 7] = t.slot = FM6_OWN; }
|
||
}
|
||
}
|
||
b(rc); b(st.vbank.voices.filter(Boolean).length);
|
||
} else {
|
||
if (a.length) return null;
|
||
b(32); b(vb.valid ? 1 : 0); s(vb.name);
|
||
vb.voices.forEach((pk) => { b(pk ? 1 : 0); s(pk ? FM6.name(FM6.unpack(pk)) : ""); });
|
||
}
|
||
break;
|
||
}
|
||
case CMD.FM6_GET: case CMD.FM6_PUT: case CMD.FM6_LIST: case CMD.FM6_ERASE: { /* editor_fm6.c */
|
||
if (opt.noFm6 || !st.uiCaps) return null;
|
||
const nf = FM6.FACTORY_PK.length, fm6User = (k) => k < NB && st.bank[k] && st.bank[k].engine === FM6_E;
|
||
if (cmd === CMD.FM6_LIST) { /* the factory patches; no bank (1.0.3) */
|
||
if (a.length) return null;
|
||
b(nf); b(0);
|
||
for (let i = 0; i < nf; i++) { b(1); s(FM6.name(FM6.unpack(FM6.FACTORY_PK[i]))); }
|
||
} else if (cmd === CMD.FM6_ERASE) {
|
||
b(a[0] ?? 127); b(a.length !== 1 ? 1 : 3); /* (3: no bank) */
|
||
} else if (cmd === CMD.FM6_GET) {
|
||
let rc = a.length !== 2 || a[0] > 3 ? 1 : 0, pk = null;
|
||
if (!rc) {
|
||
if (a[0] === 0 && a[1] < NTRK) pk = st.tracks[a[1]].fm6;
|
||
else if (a[0] === 1) rc = 3;
|
||
else if (a[0] === 2 && a[1] < nf) pk = FM6.FACTORY_PK[a[1]];
|
||
else if (a[0] === 3 && a[1] < NB) { pk = fm6User(a[1]) ? st.bank[a[1]].fm6 : null; rc = pk ? 0 : 2; }
|
||
else rc = 1;
|
||
}
|
||
b(a[0] ?? 127); b(a[1] ?? 127); b(rc);
|
||
if (!rc) pk.forEach(b);
|
||
} else {
|
||
let rc = a.length !== 2 + 128 ? 1 : 0;
|
||
const pk = rc ? null : FM6.pack(FM6.unpack(a.slice(2))); /* (every value into its range) */
|
||
if (!rc && a[0] === 0 && a[1] < NTRK) { st.tracks[a[1]].fm6 = pk; fm6Adopt(st.tracks[a[1]]); }
|
||
else if (!rc && a[0] === 1) rc = 3;
|
||
else if (!rc && a[0] === 3 && fm6User(a[1])) st.bank[a[1]].fm6 = pk;
|
||
else rc = 1;
|
||
b(a[0] ?? 127); b(a[1] ?? 127); b(rc);
|
||
}
|
||
break;
|
||
}
|
||
case CMD.PRESET:
|
||
if (a.length < 2 || a[0] >= ENG.length) return null;
|
||
if (a[0] === 1) fm4Load(a[1]); /* a DIGITAL preset: its sound, as FM6 */
|
||
else if (a[0] === 4 && a[1] === PERC_SET && !opt.hostPower) setEngine(DRUM_E); /* SAMPLE preset 4, once PERC: DRUM's kit */
|
||
else {
|
||
if (a[0] !== st.engine) setEngine(a[0]);
|
||
applyPreset(a[1]);
|
||
}
|
||
b(st.engine); b(st.preset);
|
||
break;
|
||
case CMD.SONG: {
|
||
if (!a.length || a[0] > 3) return null;
|
||
let rc = 0;
|
||
if (a[0] === 1) {
|
||
const rows = Array.from({ length: a[1] || 0 }, (_, i) => ({ slot: a[2 + 2 * i], repeat: a[3 + 2 * i] }));
|
||
if (a.length < 2 || a[1] > 16 || a.length !== 2 + 2 * a[1] || rows.some((r) => r.slot > 3 || r.repeat < 1 || r.repeat > 64)) rc = 1;
|
||
else if (st.chainPlaying) rc = 2;
|
||
else st.songRows = rows;
|
||
} else if (a[0] === 2) {
|
||
if (st.chainPlaying) rc = 2;
|
||
else if (!st.songRows.length) rc = 1;
|
||
else {
|
||
const missing = st.songRows.find((r) => !st.slots[r.slot]);
|
||
if (missing) rc = 3 + missing.slot;
|
||
else { st.chainPlaying = true; st.chainRow = 0; st.chainRemaining = st.songRows[0].repeat; }
|
||
}
|
||
} else if (a[0] === 3) st.chainPlaying = false;
|
||
b(a[0]); b(rc); b(st.songRows.length); b(st.chainPlaying ? 1 : 0); b(st.chainRow); b(st.chainRemaining);
|
||
st.songRows.forEach((r) => { b(r.slot); b(r.repeat); });
|
||
break;
|
||
}
|
||
case CMD.PROJECT: {
|
||
if (a.length < 2) return null;
|
||
const k = a[1] & 3;
|
||
if (a[0] > 2) return null;
|
||
if (a[0] === 1) { st.chainPlaying = false; st.slots[k] = project(); }
|
||
else if (a[0] === 0 && st.slots[k]) {
|
||
st.chainPlaying = false; Object.assign(st, JSON.parse(JSON.stringify(st.slots[k])));
|
||
/* SAMPLE PERC tracks: DRUM's kit (project.c proj_perc). Removed factory presets keep their saved sound; only
|
||
the display index is normalized. */
|
||
st.tracks.forEach((t) => {
|
||
const pc = fromPerc({ engine: t.engine, p: t.p }, ENG.map((x) => x.name), P_E0);
|
||
if (pc) { t.engine = pc.engine; t.p = pc.p; t.preset = 0; }
|
||
if (t.preset >= ENG[t.engine].presets.length) t.preset = 0;
|
||
});
|
||
}
|
||
b(a[0]); b(k); b(st.slots[k] ? 1 : 0);
|
||
break;
|
||
}
|
||
case CMD.SCREEN: { /* the screen mirror: a picture of its own, a bar moving (scrMock) */
|
||
if (opt.legacy || opt.noScreen) return null; /* (firmware before it: no reply) */
|
||
const op = a.length ? a[0] : 0, bad = a.length > 1 || op > 4;
|
||
if (!bad && (op === 1 || (op === 3 && st.screen))) { st.screen = true; scrMock.full = true; scrMock.start(); }
|
||
else if (!bad && op === 4) st.screen = false;
|
||
b(op); b(bad ? 1 : 0); b(st.screen ? 1 : 0); b(240 & 127); b(240 >> 7); b(240 & 127); b(240 >> 7);
|
||
break;
|
||
}
|
||
case CMD.NAMES:
|
||
if (a.length < 1 || a[0] >= ENG.length) return null;
|
||
b(a[0]); b(ENG[a[0]].presets.length); ENG[a[0]].presets.forEach((p) => s(p.name));
|
||
ENG[a[0]].titles.forEach(s);
|
||
break;
|
||
default:
|
||
return null;
|
||
}
|
||
if ([CMD.UP_PUT, CMD.UP_STORE, CMD.UP_ERASE].includes(cmd) && out[1] === 0) st.bankSig++;
|
||
return frame(cmd, out);
|
||
}
|
||
|
||
/* a WebMIDI-like access object: one input and one output named "Felucca" */
|
||
const portName = opt.portName || "JIANT";
|
||
const input = { id: "mock-in", name: portName, type: "input", state: "connected", onmidimessage: null };
|
||
let busy = false;
|
||
const output = {
|
||
id: "mock-out", name: portName, type: "output", state: "connected",
|
||
send(data) {
|
||
const f = unframe(data);
|
||
if (!f) { console.error("mock: refused a frame that is not F0 7D 46 4C ... F7", data); return; }
|
||
if (busy) { console.warn("mock: frame dropped (device holds only one frame)", data); return; }
|
||
busy = true;
|
||
watching(); /* a lapsed WATCH ends before this request counts */
|
||
st.lastReq = Date.now();
|
||
const flash = [CMD.UP_PUT, CMD.UP_STORE, CMD.UP_ERASE].includes(f.cmd) && !opt.legacy;
|
||
setTimeout(() => {
|
||
busy = false;
|
||
const r = handle(f.cmd, f.a);
|
||
if (r && input.onmidimessage) input.onmidimessage({ data: Uint8Array.from(r) });
|
||
const ra = r ? r.slice(5, -1) : [];
|
||
if (r && ((!syncCaps() && ((f.cmd === CMD.SET && f.a[0] === 1 && f.a[1] === G_ENGSEL) || f.cmd === CMD.PRESET))
|
||
|| (f.cmd === CMD.PROJECT && f.a[0] === 0 && ra[2]) || (f.cmd === CMD.UP_LOAD && !ra[1]))) reloadPush();
|
||
}, flash ? 150 : 4 + Math.random() * 12);
|
||
},
|
||
};
|
||
/* the screen mirror's picture: a frame like the FM-1's (a header, two cards, a step row), the steps' playhead moving;
|
||
the whole screen when asked, then only the row that changed. Off by itself 4 s after the last request */
|
||
const scrMock = {
|
||
full: false, t: 0, timer: 0, fb: new Uint16Array(240 * 240),
|
||
rgb: (r, g, b) => (r >> 3) << 11 | (g >> 2) << 5 | b >> 3,
|
||
rect(x, y, w, h, c) { for (let j = y; j < y + h; j++) this.fb.fill(c, j * 240 + x, j * 240 + x + w); },
|
||
draw() {
|
||
const bg = this.rgb(20, 20, 24), surf = this.rgb(44, 44, 52), theme = this.rgb(236, 110, 80), text = this.rgb(230, 230, 230);
|
||
this.rect(0, 0, 240, 240, bg);
|
||
this.rect(0, 0, 240, 26, surf); this.rect(8, 9, 60, 8, text); this.rect(200, 9, 32, 8, theme);
|
||
this.rect(8, 40, 108, 70, surf); this.rect(124, 40, 108, 70, theme);
|
||
for (let i = 0; i < 16; i++) this.rect(8 + i * 14, 200, 12, 20, (i & 3) === 0 ? text : surf);
|
||
for (let i = 0; i < 100; i++) this.fb[(60 + (i >> 2)) * 240 + 16 + i] = this.rgb(120 + i, 120, 255 - i); /* a gradient */
|
||
},
|
||
start() {
|
||
if (this.timer) return;
|
||
this.timer = setInterval(() => {
|
||
if (!st.screen || Date.now() - st.lastReq > 4000) { st.screen = false; clearInterval(this.timer); this.timer = 0; return; }
|
||
const send = (args) => setTimeout(() => { if (input.onmidimessage) input.onmidimessage({ data: Uint8Array.from(frame(CMD.SCREEN_DATA, args)) }); }, 0);
|
||
if (this.full) {
|
||
this.full = false; this.draw();
|
||
for (const f of scrEncode(this.fb, 0, 0, 240, 240)) send(f);
|
||
return;
|
||
}
|
||
const step = this.t++ % 16, row = this.fb.subarray(224 * 240);
|
||
row.fill(this.rgb(20, 20, 24)); row.fill(this.rgb(236, 110, 80), 8 + step * 14, 20 + step * 14);
|
||
this.fb.copyWithin(225 * 240, 224 * 240, 225 * 240); this.fb.copyWithin(226 * 240, 224 * 240, 225 * 240);
|
||
for (const f of scrEncode(this.fb.subarray(224 * 240), 0, 224, 240, 3)) send(f);
|
||
}, 125);
|
||
},
|
||
};
|
||
/* WATCH ends by itself watchMs after the last request */
|
||
function watching() {
|
||
if (st.watch && Date.now() - st.lastReq > watchMs) st.watch = false;
|
||
return st.watch;
|
||
}
|
||
function push(cmd, args) {
|
||
if (!watching()) return false;
|
||
const fr = Uint8Array.from(frame(cmd, args));
|
||
setTimeout(() => { if (input.onmidimessage) input.onmidimessage({ data: fr }); }, 0);
|
||
return true;
|
||
}
|
||
/* INFO 53 01 caps (firmware after 1.0): no RELOAD echo of the editor's own PRESET / G_ENGSEL */
|
||
const syncCaps = () => (!opt.legacy && !opt.v3 && !opt.v5 && !opt.noFm6 && !opt.noSync && st.uiCaps ? 3 : 0);
|
||
const reloadPush = () => push(CMD.RELOAD, opt.legacy ? [st.engine, st.preset] : [st.engine, st.preset, st.sel]);
|
||
/* things done on the device itself */
|
||
const sim = {
|
||
knob(id = [9, 33, 35, P_E0 + 4][Math.floor(Math.random() * 4)], dv = Math.random() < 0.5 ? -4 : 4) {
|
||
const d = desc(0, id);
|
||
st.p[id] = clamp(st.p[id] + dv, d.min, d.max);
|
||
push(CMD.CHANGED, [0, id, ...v14enc(st.p[id])]);
|
||
return { id, value: st.p[id] };
|
||
},
|
||
reload(pi = st.preset + 1) {
|
||
applyPreset(pi);
|
||
reloadPush();
|
||
return { engine: st.engine, preset: st.preset };
|
||
},
|
||
track(i = (st.sel + 1) % NTRK) { /* TRACKS page KNOB 1 */
|
||
st.sel = i;
|
||
reloadPush();
|
||
return i;
|
||
},
|
||
/* TRACKS page KNOB 2: the selected track's level; pushes CHANGED */
|
||
level(v) {
|
||
st.p[0] = v = clamp(v, 0, 127);
|
||
push(CMD.CHANGED, [0, 0, ...v14enc(v)]);
|
||
return v;
|
||
},
|
||
mute(on = !st.p[40]) { st.p[40] = on ? 1 : 0; push(CMD.CHANGED, [0, 40, ...v14enc(st.p[40])]); return st.p[40]; },
|
||
/* a parameter of track i changed on the device: CHANGED for the selected track, else TRACK_CHANGED (v4 watch) */
|
||
param(i, id, val) {
|
||
const t = st.tracks[i], d = id >= P_E0 ? ENG[t.engine].edit[id - P_E0] : TP[id];
|
||
t.p[id] = clamp(val, d.min, d.max);
|
||
if (i === st.sel) push(CMD.CHANGED, [0, id, ...v14enc(t.p[id])]);
|
||
else if (st.v4) push(CMD.TRACK_CHANGED, [i, id, ...v14enc(t.p[id])]);
|
||
return t.p[id];
|
||
},
|
||
/* REC on TRACKS: arm / disarm live recording of a track (no push: the editor reads TRACK) */
|
||
arm(i = st.sel) { st.rec ^= 1 << i; return (st.rec >> i) & 1; },
|
||
step(i = Math.floor(Math.random() * 16)) {
|
||
const x = st.step[i];
|
||
if (x.n) x.flags ^= 1;
|
||
else Object.assign(x, { n: 1, notes: [60 + Math.floor(Math.random() * 12), 0, 0, 0], time: 0, flags: 0, vel: 96 });
|
||
push(CMD.STEP_CHANGED, opt.legacy ? [i] : [i, st.sel]);
|
||
return i;
|
||
},
|
||
};
|
||
if (opt.auto !== false) st.rec = 1 << 2; /* the browser mock: track 3 armed, to show it */
|
||
const timers = opt.auto === false ? [] : [
|
||
setInterval(() => sim.knob(), 3000),
|
||
setInterval(() => sim.step(), 11000),
|
||
setInterval(() => sim.reload(), 27000),
|
||
setInterval(() => sim.param((st.sel + 1) % NTRK, 39, Math.round(Math.random() * 80) - 40), 13000), /* pan of another track */
|
||
];
|
||
return {
|
||
state: st, sim,
|
||
tables: { HP_PAGES, HP_ENG, TP, GP, ENG, PATTERNS, P_COUNT, G_COUNT, NSTEP, P_E0, G_ENGSEL, P_SLCR, NTRK,
|
||
FM6: { bank: 0, own: FM6_OWN, init: FM6.INIT_PK, factory: FM6.FACTORY_PK } }, /* test_web.mjs: == the firmware */
|
||
stop: () => timers.forEach(clearInterval),
|
||
access: { sysexEnabled: true, inputs: new Map([[input.id, input]]), outputs: new Map([[output.id, output]]), onstatechange: null },
|
||
};
|
||
}
|
||
/* Optional preferences: old firmware is never probed with unknown commands. */
|
||
async function readDevicePreferences(rq, info, names, previous = null) {
|
||
if (!info.uiCaps) return null;
|
||
const state = parse[CMD.UI_STATE](await rq(req.uiState()));
|
||
const palettes = previous ? previous.palettes : parse[CMD.UI_PALETTES](await rq(req.uiPalettes()));
|
||
let favorites = previous ? previous.favorites : [], slots = previous ? previous.slots : null;
|
||
if (state.caps & 8) {
|
||
if (!previous || state.bankSig !== previous.state.bankSig) slots = await bank.list(rq);
|
||
if (!previous || state.favoriteSig !== previous.state.favoriteSig || state.bankSig !== previous.state.bankSig) {
|
||
favorites = [];
|
||
for (let engine = 0; engine <= info.nengines; engine++) {
|
||
const total = engine === info.nengines ? slots.total : (names[engine] || []).length;
|
||
const flags = favorites[engine] = [];
|
||
for (let start = 0; start < total; start += 32) {
|
||
const count = Math.min(32, total - start);
|
||
const r = parse[CMD.FAV_GET](await rq(req.favGet(engine, start, count)));
|
||
if (r.rc || r.engine !== engine || r.start !== start || r.count !== count) throw new Error("Invalid favorites reply");
|
||
flags.push(...r.values);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return { state, palettes, favorites, slots };
|
||
}
|
||
/* an enum value or a preset named like another is an alias kept for stored numbers: the device loads the original,
|
||
the lists hide the alias (shown when set). The original: the first entry when it has that name (SAMPLE / GRAIN 1
|
||
and 4, once TRANH and PERC: PIANO 0), else the last with it (EDITOR_PROTOCOL.md). "-" (a reserved engine number: DIGITAL 1, PHYS 9) is no alias. -> the original's index */
|
||
function aliasOf(names, i) {
|
||
if (!names || names[i] == null || names[i] === "-") return i;
|
||
const k = names[0] === names[i] ? 0 : names.lastIndexOf(names[i]);
|
||
return k >= 0 ? k : i;
|
||
}
|
||
|
||
/* #48: note divisions (1/4, 8T, 2BAR, ...) are listed by length, longest first, as the device's knobs step them
|
||
(src/params.c enum_order); the values stay. Any other list: in value order. -> d's values in the order shown */
|
||
function divLength(n) {
|
||
const d = /^(\d+)\/(\d+)D$/.exec(n); /* (V10.8) dotted: half as long again (params.c DTIME_ORDER) */
|
||
if (d) return 1.5 * +d[1] / +d[2];
|
||
const m = /^(\d+)\/(\d+)$/.exec(n) || /^(\d+)(T|BAR)$/.exec(n);
|
||
return !m ? null : m[2] === "BAR" ? +m[1] : m[2] === "T" ? 2 / 3 / +m[1] : +m[1] / +m[2];
|
||
}
|
||
function enumShown(d) {
|
||
const vals = [];
|
||
for (let v = d.min; v <= d.max; v++) vals.push(v);
|
||
const len = d.fmt === F.ENUM && d.names ? d.names.map(divLength) : [null];
|
||
if (d.names && d.names[5] === "BYTE" && d.names[0] === "PLS") return [vals[5], ...(vals.length > 6 ? [vals[6]] : []), ...vals.slice(0, 5)]; /* (JIANT 0.4: LOFI's WAVE, BYTE first; 0.5.1: FLOAT next) */
|
||
if (len.includes(null) && d.names && len.some((x) => x !== null) && d.names.every((n, i) => len[i] !== null || /^[\d.]+m?s$/.test(n)))
|
||
return [...vals.filter((v) => len[v - d.min] !== null).sort((a, b) => len[b - d.min] - len[a - d.min] || a - b),
|
||
...vals.filter((v) => len[v - d.min] === null)]; /* (JIANT 0.4, the delay's TIME: the divisions, then free times) */
|
||
return len.includes(null) ? vals : vals.sort((a, b) => len[b - d.min] - len[a - d.min] || a - b);
|
||
}
|
||
|
||
/* the order the device shows its engines in (src/engines.c ENGINE_ORDER): the lists here follow it, the protocol keeps
|
||
the engine numbers. engineOrder(names): the indices of names in that order, "-" (a reserved number) left out; a name
|
||
the list does not know (another firmware) follows in index order */
|
||
const ENGINE_ORDER = ["DRUM", "VOICE", "ANIMAL", "LOFI", "ANALOG", "FM6", "PHASE", "WHEEL", "NOISE", "STRING", "ADD", "INPUT", "SAMPLE", "GRAIN", "DIGITAL"]; /* (0.9.9: DRUM-X, VOICE,
|
||
ANIMAL first, as the parts at power-on; DIGITAL, FELUCCA_FM4 builds only, last; was ANALOG FM6 DIGITAL PHASE LOFI VOICE WHEEL NOISE
|
||
DRUM ANIMAL, the order PROGRAM CHANGE still numbers the sounds in: engines.c ENGINE_PC_ORDER) */
|
||
function engineOrder(names) {
|
||
const rank = (n) => { const k = ENGINE_ORDER.indexOf(n); return k < 0 ? ENGINE_ORDER.length : k; };
|
||
return (names || []).map((n, i) => i).filter((i) => names[i] !== "-")
|
||
.sort((a, b) => rank(names[a]) - rank(names[b]) || a - b);
|
||
}
|
||
|
||
function devicePresetRows(info, names, preferences) {
|
||
if (!preferences || !(preferences.state.caps & 8)) return [];
|
||
const rows = engineOrder(info.engines).filter((engine) => names[engine]).flatMap((engine) => names[engine]
|
||
.map((name, preset) => ({ engine, preset, name, user: false })).filter((row) => aliasOf(names[engine], row.preset) === row.preset));
|
||
for (const slot of preferences.slots.slots) if (slot.used)
|
||
rows.push({ engine: info.nengines, preset: slot.slot, name: slot.name, user: true });
|
||
return rows.map((row) => ({ ...row, favorite: !!(preferences.favorites[row.engine] || [])[row.preset] }))
|
||
.filter((row) => !preferences.state.filter || row.favorite);
|
||
}
|
||
|
||
/* (ports/) the big CPUs' pages beyond EDIT 1 / 2 (params.c PAGES from HP_PAGE0, ui.c page_visible): the ids of other
|
||
engines' slots their values live in (core.h P_LN0..7 83..90, P_LRTRG 61, P_FM3_DEC 72, P_FM3_LEVEL 75, P_FM4_SUS 78,
|
||
P_FM4_LEVEL 80), shown only for a device whose INFO says it has them ('H'), on a track of that engine; DESC names them */
|
||
const HP_PAGES = {
|
||
SAMPLE: [["TRIG", 0, [83, 84, 85, 86]], ["REC", 0, [87, 88, 89, 90]]],
|
||
GRAIN: [["TRAVEL", 0, [83, 84, 85, 86]], ["SOURCE", 0, [87, 88, 89, 90]], ["PITCH", 0, [72, 78]]],
|
||
DRUM: [["SAMPLES", 0, [61, 72, 80, 78]], ["SAMPLES 2", 0, [75]]],
|
||
};
|
||
const hpIds = (name) => (HP_PAGES[name] || []).flatMap((pg) => pg[2]);
|
||
/*PROTO-END*/
|
||
/*MATH-BEGIN*/
|
||
/* ------------------------------------------------------- MATH: the formula VM --- */
|
||
/* (the formula editor) MATH's formulas as the firmware has them (eng_lofi.c lofi_byte: BYTE, B01..B48; lofi_float:
|
||
FLOAT, F01..F48), a VM for a formula of its grammar, the BYTE voice as a model, a seeded generator. No DOM: the node
|
||
tests run it (web/math_test.mjs). The grammar: a C expression of t (the time) and a (VAR's variable, 1..16), unsigned
|
||
32-bit as the firmware computes it: numbers (decimal, 0x hex, an optional u), ( ), the unary - ~ !, then
|
||
* / %, + -, << >>, < <= > >=, == !=, &, ^, |, &&, || and ?: in C's precedence; a comparison or ! is 0 or 1; the
|
||
low 8 bits are the sample. A shift by 32 or more takes its count's low 5 bits (as the emulator's wasm), a / or % by 0
|
||
gives 0 (the firmware's formulas do neither) */
|
||
const MATH_BYTE = ["(~t >> 2) * ((127 & t * (7 & t >> 10)) < (245 & t * (2 + (5 & t >> 14))))",
|
||
"(t * ((3 + (1 ^ (t >> 10 & 5))) * (5 + (3 & t >> 14)))) >> (t >> 8 & 3)",
|
||
"((-t & 4095) * (255 & t * (t & t >> 13)) >> 12) + (127 & t * (234 & t >> 8 & t >> 3) >> (3 & t >> 14))",
|
||
"t * (((t >> 9) ^ ((t >> 9) - 1) ^ 1) % 13)",
|
||
"((t >> 13 | t % 24) & (t >> 7 | t % 19)) << 3",
|
||
"t * (t ^ (t + (t >> 15 | 1)) ^ (((t - 1280) ^ t) >> 10))",
|
||
"(t * (0xCA98 >> (t >> 9 & 14) & 15)) | t >> 8",
|
||
"(t * (t >> 8 | t >> 9) & 46 & t >> 8) ^ ((t & t >> 13) | t >> 6)",
|
||
"(t >> 4) * (13 & 0x8898A989 >> (t >> 11 & 30))",
|
||
"t * (t >> ((8 * ((t >> 15) | (t >> 8))) & 31) & (20 | (((t >> 19) * 5) >> (t & 31)) | t >> 3))",
|
||
"(t & t % 255) - (t * 3 & t >> 13 & t >> 6)",
|
||
"(t * (t >> 9 | t >> 13) & (t >> 6 | t >> 11) & 127) + ((t >> 4) * (3 + (t >> 12 & 3)) & 64)",
|
||
"t + (t & (t ^ t >> 6)) - t * ((t >> 9) & (t % 16 ? 2 : 6) & t >> 9)",
|
||
"t * (t >> 11 & t >> 8 & 123 & t >> 3)",
|
||
"(t * 9 & t >> 4) | (t * 5 & t >> 7) | (t * 3 & t >> 10)",
|
||
"(t * ((t & 4096 ? (t % 65536 < 59392 ? 7 : t & 7) : 16) + (1 & t >> 14)) >> (3 & -t >> (t & 2048 ? 2 : 10))) | t >> (t & 16384 ? (t & 4096 ? 10 : 3) : 2)",
|
||
"(t * ((3 + (1 ^ (t >> 10 & 5))) * (a + (3 & t >> 14)))) >> (t >> 8 & 3)",
|
||
"t * ((t >> (a & 15) | t >> 8) & 63 & t >> 4)",
|
||
"(t * a & t >> 7) | (t * 3 & t >> 10)",
|
||
"(t >> a | t) * (t >> 9 & 7)",
|
||
"t * (t >> 8 & a) ^ t >> 4",
|
||
"(t * a & t >> 8) * (t >> 12 & 3)",
|
||
"t * (0x9AD5 >> (t >> (8 + (a & 3)) & 14) & 15)",
|
||
"(t ^ t >> a) * (t >> 10 & 5)",
|
||
"t >> 2 & (t * a >> 6 | t >> 9)",
|
||
"(t | t >> a | t >> 7) * (t >> 13 & 7)",
|
||
"t * ((t >> 11 & 3) + a) & t >> 6",
|
||
"(t * (a | 1) % (257 - (t >> 10 & 127))) & 255",
|
||
"t * (t >> 10 & 7 & a) | t >> 5",
|
||
"(t >> 5 & t >> 7) * a + (t >> 9 & 32)",
|
||
"t * (t >> 12 & a ? 3 : 2) & t >> 6",
|
||
"(t * a >> 4 | t >> 3) ^ (t >> 7 & t >> 11)",
|
||
"(t * (t >> 5 | t >> 8)) >> (t >> 16 & 7)",
|
||
"t * ((t >> 12 | t >> 8) & 63 & t >> 4)",
|
||
"(t >> 6 | t | t >> (t >> 16 & 7)) * 10 + (t >> 11 & 7)",
|
||
"(t | (t >> 9 | t >> 7)) * t & (t >> 11 | t >> 9)",
|
||
"(t * 5 & t >> 7) | (t * 3 & t * 4 >> 10)",
|
||
"(t >> 7 | t | t >> 6) * 10 + 4 * ((t & t >> 13) | t >> 6)",
|
||
"t & 4096 ? (t * (t ^ t % 255) | t >> 4) >> 1 : (t >> 3) | (t & 8192 ? t << 2 : t)",
|
||
"(t * (t >> 9 | t >> 13) & 16) * 8 + (t >> 6 & t >> 8 & 31)",
|
||
"((t >> 4) * (t >> 5 & 0x2A)) | t >> 3",
|
||
"t * ((t >> 3 | t >> 9) & 82 & t >> 9)",
|
||
"(t * a & t >> 4) | (t >> 5 & t * (a + 1) >> 7)",
|
||
"t * (t >> ((t >> 11 & 3) + 4) & a * 3)",
|
||
"(t >> 2) * ((t >> (8 + (a & 3)) & 7) | (t >> 12 & 3))",
|
||
"(t * (0x5A3C >> (t >> 11 & 12) & 15)) >> (t >> 14 & 1)",
|
||
"(t * (t >> 13 & 1 ? 3 : 4) & t >> 5) | (t * (a + 2) >> 9 & t >> 7)",
|
||
"(t ^ t >> a) * ((t >> 9) % 5 + 1)"];
|
||
/* FLOAT's formulas (sines of t, the firmware's own fixed-point functions): shown, previewed through the emulator and
|
||
sent; not edited (the VM is BYTE's) */
|
||
const MATH_FLOAT = [["sin(t (t>>11 ^ t>>13 & 7))", "return S(x * (((t >> 11) ^ (t >> 13)) & 7) + x) * E >> 15;"],
|
||
["FM, its index walking", "return S(x + PM(S(x * 3), (int32_t)((t >> 10) & 15) * 3));"],
|
||
["a melody, a nibble table", "return S((x >> 4) * R[(0x36364689 >> ((st & 7) * 4)) & 7]) * E >> 15;"],
|
||
["a ring, rhythmic", "return S(x * (1 + ((t >> 12) & 3))) * S(x * (((t >> 9) & 7) + 1)) >> 15;"],
|
||
["a kick, a bass", "{\n uint32_t k = fr < 1024 ? (1024 - fr) * (1024 - fr) >> 6 : 0;\n *aux += (int32_t)k + 40;\n a = (st & 1) ? 0 : sine_i((uint32_t)*aux << 13) * (int32_t)(1024 - (fr < 1024 ? fr : 1024)) >> 10;\n return (a + (S(x >> 1) >> 1)) >> 1;"],
|
||
["Sierpinski partials", "return S(x * ((((t >> 9) & (t >> 11)) & 7) | 1)) * E >> 15;"],
|
||
["drive, rhythmic", "return softclip(S(x * (1 + (st & 1))) * (1 + (int32_t)((t >> 11) & 7) * 3) >> 1);"],
|
||
["fifths and octaves", "return S((x >> 4) * R[(st * 3 + (st >> 2)) & 7] * (1 + (st & 1)));"],
|
||
["two arpeggios", "{\n static const uint8_t H[8] = {2, 3, 4, 5, 6, 8, 5, 3};\n return (S(x * H[(t >> 9) & 7] >> 1) + S(x * H[(t >> 11) & 7] >> 2)) >> 1;"],
|
||
["a snare, a tone", "h = (t * 2654435761) >> 17;\n a = (st & 1) ? (int32_t)h - 16384 : 0;\n return (mulq15(a, E) + S(x)) >> 1;"],
|
||
["a pluck of FM", "return S(x + PM(S(x * (((t >> 12) & 7) + 1)), E >> 10));"],
|
||
["a vibrato, deep (4 Hz)", "return S(x + PM(S(t << 2), 6));"],
|
||
["folded, rhythmic", "return S((uint32_t)(S(x) * (2 + (int32_t)((t >> 11) & 7))) >> 2);"],
|
||
["rectified, leaping", "a = S(x * (1 + (st & 1))); b = S((x >> 4) * (24 + (st & 6) * 4));\n return (a < 0 ? -a : a) - (b < 0 ? -b : b);"],
|
||
["a staircase sine", "return S(x & ~((1 << (4 + (st & 7))) - 1));"],
|
||
["partials mod 7", "return S(x * (((t >> 8) % 7) + 1)) * E >> 15;"],
|
||
["three against four", "{\n int32_t e3 = 32767 - (int32_t)((t % 3072) * 10), e4 = E;\n return (mulq15(S(x * (1 + (st & 1))), e4) + mulq15(S((x >> 4) * (24 + (st & 2) * 8)), e3 > 0 ? e3 : 0)) >> 1;"],
|
||
["a riser each bar", "return S((x >> 6) * (64 + ((t >> 6) & 255))) * E >> 15;"],
|
||
["beating, gated", "return mulq15(S(x * (1 + st % 3)) * ((t >> 10) & 1 ? 1 : 0) + S(x + (t << 2)), 16384);"],
|
||
["odd partials, built up", "{\n uint32_t k, n = 1 + ((t >> 11) & 3);\n for (a = 0, k = 0; k < n; k++)\n a += S(x * (2 * k + 1)) / (int32_t)(2 * k + 1);\n return a * 3 >> 2;"],
|
||
["leaps", "return S(x * (2 + ((st * 5) & 7)) >> 1);"],
|
||
["a drum loop", "{\n uint32_t k = fr < 768 ? (768 - fr) * (768 - fr) >> 6 : 0;\n *aux += (int32_t)k + 30;\n a = (st & 3) == 0 ? sine_i((uint32_t)*aux << 13) * (int32_t)(768 - (fr < 768 ? fr : 768)) / 768 : 0;\n b = (t >> (8 + (st & 3))) & 1 ? (int32_t)(((t * 2654435761) >> 17) - 16384) * (int32_t)(1024 - (t & 1023)) >> 12 : 0;\n return (a + b + (S(x >> 1) >> 2)) >> 1;"],
|
||
["bytebeat in it", "return S(x * (1 + (((t >> 9) & (t >> 7)) & 7)) + (((t >> 9) & (t >> 7) & 255) << 9));"],
|
||
["FM 5:2, stepped", "return S(x * 2 + PM(S(x * 5), (int32_t)((t >> 11) & 3) * 8));"],
|
||
["squared", "a = S(x * (1 + (st & 3))); return mul64_sh15(a, a < 0 ? -a : a) * E >> 15;"],
|
||
["a bit of t dropped: jumps", "return S(x & ~(1 << (8 + (st & 7)))) * E >> 15;"],
|
||
["a descending line", "return S((x >> 4) * (34 - ((t >> 11) & 15)) >> 1) * E >> 15;"],
|
||
["a partial, struck", "return (S(x) + mulq15(S(x * (((t >> 13) & 3) + 2)), E)) >> 1;"],
|
||
["FM, its index a 1 Hz sine", "return S(x + PM(S(x * 2), S(t) >> 10));"],
|
||
["a glide up partials", "return S((x >> 4) * (16 + ((t >> 7) & 63)));"],
|
||
["a random line", "h = ((st + 1) * 2654435761) >> 29; return S((x >> 4) * R[h]) * E >> 15;"],
|
||
["euclid hats, a chord", "a = ((st * 5) & 7) < 5 ? E : 0;\n b = (int32_t)(((t * 2654435761) >> 17) - 16384) * (int32_t)(512 - (t & 511)) >> 11;\n h = (x >> 4) * R[(st >> 1) & 7] >> 4;\n return (S(h * 16) + S(h * 20) + S(h * 24)) / 4 + (mulq15(b, a) >> 1);\n }"],
|
||
["partials mod 5, stepped", "return S(x * (st % 5 + 1)) * E >> 15;"],
|
||
["FM 7:1, plucked", "return S(x + PM(S(x * 7), E >> 11));"],
|
||
["a fifth over a line", "return (S(x) + S(x * 3 >> 1) + S((x >> 4) * R[st & 7])) / 3;"],
|
||
["a melody with rests", "return (st & 3) != 3 ? S((x >> 4) * R[(st * 5) & 7] * 2) * E >> 15 : 0;"],
|
||
["a sub's FM, growling", "return S(x + PM(S(x >> 1), (int32_t)((t >> 9) & 15) * 2));"],
|
||
["half rectified", "a = S(x); return a > 0 ? a : a / 4;"],
|
||
["tremolo, octave leaps", "return S(x * (1 + ((t >> 10) & 1) * 2)) * S(t << 1) >> 15;"],
|
||
["a stair arpeggio", "return S((x >> 3) * (8 + ((t >> 8) & 7))) * E >> 15;"],
|
||
["the 2nd into the 3rd", "return (mulq15(S(x * 2), E) + mulq15(S(x * 3), 32767 - E)) >> 1;"],
|
||
["FM 5:1, its index stepped", "return S(x + PM(S(x * 5), (int32_t)(st & 7) * 4));"],
|
||
["a gated pad", "return fr < 1024 ? S((x >> 4) * R[(t >> 13) & 7]) * E >> 15 : 0;"],
|
||
["driven, two partials", "return softclip((S(x) * 3 + S(x * 2) * 2) >> 1);"],
|
||
["xor partials", "return S(x * ((((t >> 9) ^ (t >> 12)) & 7) | 1));"],
|
||
["chirps", "return S((x >> 5) * (32 + ((t >> 5) & 31))) * E >> 15;"],
|
||
["a ring over a sub", "return (S(x) * S(x * (1 + (st & 3))) >> 15) + (S(x >> 1) >> 2);"],
|
||
["FM 3:1, its index a slow sine", "return S(x + PM(S(x * 3), S(t << 1) >> 11));"]];
|
||
/* eng_lofi.c BYTE_T0: each formula's start (512 t steps) */
|
||
const MATH_T0 = [0, 0, 0, 0, 0, 0, 0, 31, 0, 0, 0, 0, 0, 4, 2, 0, 0, 0, 16, 0, 7, 16, 0, 1, 8, 15, 8, 0, 15, 23, 8, 0];
|
||
const MathVM = (() => {
|
||
const BIN = [["?"], ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "!="], ["<", "<=", ">", ">="], ["<<", ">>"], ["+", "-"], ["*", "/", "%"]];
|
||
const OPS = ["<<", ">>", "<=", ">=", "==", "!=", "&&", "||", "+", "-", "*", "/", "%", "&", "|", "^", "~", "!", "<", ">", "?", ":", "(", ")"];
|
||
function lex(src) {
|
||
const out = [];
|
||
for (let i = 0; i < src.length;) {
|
||
const c = src[i];
|
||
if (/\s/.test(c)) { i++; continue; }
|
||
let m;
|
||
if ((m = /^(0[xX][0-9a-fA-F]+|\d+)[uU]?/.exec(src.slice(i)))) {
|
||
const v = Number(m[1].toLowerCase().startsWith("0x") ? BigInt(m[1]) : BigInt(m[1]));
|
||
if (v > 0xFFFFFFFF) throw { message: "number too large (32 bits)", pos: i };
|
||
out.push({ k: "n", v: v >>> 0, pos: i }); i += m[0].length; continue;
|
||
}
|
||
if ((m = /^[A-Za-z_]\w*/.exec(src.slice(i)))) {
|
||
if (m[0] !== "t" && m[0] !== "a") throw { message: `unknown name "${m[0]}" (only t and a)`, pos: i };
|
||
out.push({ k: "id", v: m[0], pos: i }); i += m[0].length; continue;
|
||
}
|
||
const op = OPS.find((o) => src.startsWith(o, i));
|
||
if (!op) throw { message: `unexpected "${c}"`, pos: i };
|
||
out.push({ k: "op", v: op, pos: i }); i += op.length;
|
||
}
|
||
out.push({ k: "end", pos: src.length });
|
||
return out;
|
||
}
|
||
function parse(src) {
|
||
const tk = lex(String(src)); let i = 0;
|
||
const peek = () => tk[i], take = () => tk[i++];
|
||
const want = (v) => { const x = take(); if (x.k !== "op" || x.v !== v) throw { message: `expected "${v}"`, pos: x.pos }; };
|
||
function prim() {
|
||
const x = take();
|
||
if (x.k === "n") return { n: x.v };
|
||
if (x.k === "id") return { id: x.v };
|
||
if (x.k === "op" && x.v === "(") { const e = cond(); want(")"); return e; }
|
||
if (x.k === "op" && ["-", "~", "!", "+"].includes(x.v)) { const e = prim(); return x.v === "+" ? e : { u: x.v, e }; }
|
||
throw { message: x.k === "end" ? "the formula ends too soon" : `unexpected "${x.v}"`, pos: x.pos };
|
||
}
|
||
function bin(lv) {
|
||
if (lv >= BIN.length) return prim();
|
||
let l = bin(lv + 1);
|
||
while (peek().k === "op" && BIN[lv].includes(peek().v)) { const o = take().v; l = { o, l, r: bin(lv + 1) }; }
|
||
return l;
|
||
}
|
||
function cond() {
|
||
const c = bin(1);
|
||
if (peek().k === "op" && peek().v === "?") { take(); const y = cond(); want(":"); return { q: c, y, z: cond() }; }
|
||
return c;
|
||
}
|
||
const e = cond();
|
||
if (peek().k !== "end") throw { message: `unexpected "${peek().v}"`, pos: peek().pos };
|
||
return e;
|
||
}
|
||
/* the expression as JavaScript on uint32 numbers (only what parse built: numbers, t, a, operators) */
|
||
function js(e) {
|
||
if (e.n != null) return String(e.n);
|
||
if (e.id) return e.id;
|
||
if (e.u) { const x = js(e.e); return e.u === "-" ? `((0-${x})>>>0)` : e.u === "~" ? `((~${x})>>>0)` : `(${x}?0:1)`; }
|
||
if (e.q) return `(${js(e.q)}?${js(e.y)}:${js(e.z)})`;
|
||
const l = js(e.l), r = js(e.r);
|
||
switch (e.o) {
|
||
case "+": return `((${l}+${r})>>>0)`;
|
||
case "-": return `((${l}-${r})>>>0)`;
|
||
case "*": return `(Math.imul(${l},${r})>>>0)`;
|
||
case "/": return `D(${l},${r})`;
|
||
case "%": return `M(${l},${r})`;
|
||
case "&": return `((${l}&${r})>>>0)`;
|
||
case "|": return `((${l}|${r})>>>0)`;
|
||
case "^": return `((${l}^${r})>>>0)`;
|
||
case "<<": return `((${l}<<(${r}&31))>>>0)`;
|
||
case ">>": return `(${l}>>>(${r}&31))`;
|
||
case "&&": return `(${l}&&${r}?1:0)`;
|
||
case "||": return `(${l}||${r}?1:0)`;
|
||
default: return `(${l}${e.o === "==" ? "===" : e.o === "!=" ? "!==" : e.o}${r}?1:0)`;
|
||
}
|
||
}
|
||
const D = (x, y) => (y ? Math.floor(x / y) >>> 0 : 0), M = (x, y) => (y ? x % y : 0);
|
||
/* a canonical text (two formulas the same: one text) */
|
||
function canon(e) {
|
||
if (e.n != null) return String(e.n);
|
||
if (e.id) return e.id;
|
||
if (e.u) return `${e.u}(${canon(e.e)})`;
|
||
if (e.q) return `(${canon(e.q)})?(${canon(e.y)}):(${canon(e.z)})`;
|
||
return `(${canon(e.l)})${e.o}(${canon(e.r)})`;
|
||
}
|
||
function size(e) { return e.n != null || e.id ? 1 : e.u ? 1 + size(e.e) : e.q ? 1 + size(e.q) + size(e.y) + size(e.z) : 1 + size(e.l) + size(e.r); }
|
||
const STOCK = new Map(MATH_BYTE.map((s, k) => [canon(parse(s)), k]));
|
||
/* compile: {ok, fn (t, a) -> 0..255, stock (the B number - 1 when it is one of the firmware's), size, uses a} or
|
||
{ok: false, error, pos} */
|
||
function compile(src) {
|
||
try {
|
||
const e = parse(src);
|
||
if (size(e) > 400) return { ok: false, error: "too long (400 terms at most)", pos: 0 };
|
||
const body = js(e);
|
||
const f = new Function("D", "M", `return function(t,a){return (${body})&255;}`)(D, M);
|
||
return { ok: true, fn: f, stock: STOCK.get(canon(e)) ?? -1, size: size(e), usesA: /a/.test(body), canon: canon(e) };
|
||
} catch (err) { return { ok: false, error: err.message || String(err), pos: err.pos ?? 0 }; }
|
||
}
|
||
/* (the proposal, EDITOR_PROTOCOL.md "Proposal: a user formula") the formula as the bytecode a firmware VM would run:
|
||
a stack machine, one byte an op, 7-bit clean: 0x00 t, 0x01 a, 0x02 + 5 bytes a constant (7 bits each, LSB first), 0x03 + 1 byte a constant below 128,
|
||
0x10.. the binary ops in BINOP's order, 0x30 - 0x31 ~ 0x32 ! (unary), 0x40 ?: (pops z y c) */
|
||
const BINOP = ["+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", "<=", ">", ">=", "==", "!=", "&&", "||"];
|
||
function rpn(src) {
|
||
const e = parse(src), out = [];
|
||
let depth = 0, max = 0;
|
||
const push = () => { depth++; max = Math.max(max, depth); };
|
||
(function walk(x) {
|
||
if (x.n != null) { if (x.n < 128) { out.push(0x03, x.n); } else { out.push(0x02); for (let k = 0; k < 5; k++) out.push((x.n >>> (7 * k)) & 127); } push(); return; }
|
||
if (x.id) { out.push(x.id === "t" ? 0x00 : 0x01); push(); return; }
|
||
if (x.u) { walk(x.e); out.push(0x30 + ["-", "~", "!"].indexOf(x.u)); return; }
|
||
if (x.q) { walk(x.q); walk(x.y); walk(x.z); out.push(0x40); depth -= 2; return; }
|
||
walk(x.l); walk(x.r); out.push(0x10 + BINOP.indexOf(x.o)); depth--;
|
||
})(e);
|
||
return { code: out, stack: max };
|
||
}
|
||
/* the bytecode run as the firmware VM would (the test: rpn(f) == compile(f) for every formula) */
|
||
function run(code, t, a) {
|
||
const st = []; let sp = 0;
|
||
for (let i = 0; i < code.length;) {
|
||
const op = code[i++];
|
||
if (op === 0x00) st[sp++] = t >>> 0;
|
||
else if (op === 0x01) st[sp++] = a >>> 0;
|
||
else if (op === 0x03) st[sp++] = code[i++];
|
||
else if (op === 0x02) { let v = 0; for (let k = 0; k < 5; k++) v += code[i++] * 2 ** (7 * k); st[sp++] = v >>> 0; }
|
||
else if (op >= 0x30 && op <= 0x32) { const x = st[sp - 1]; st[sp - 1] = op === 0x30 ? (0 - x) >>> 0 : op === 0x31 ? (~x) >>> 0 : x ? 0 : 1; }
|
||
else if (op === 0x40) { const z = st[--sp], y = st[--sp], c = st[sp - 1]; st[sp - 1] = c ? y : z; }
|
||
else {
|
||
const r = st[--sp], l = st[sp - 1], o = BINOP[op - 0x10];
|
||
st[sp - 1] = o === "+" ? (l + r) >>> 0 : o === "-" ? (l - r) >>> 0 : o === "*" ? Math.imul(l, r) >>> 0 : o === "/" ? D(l, r) :
|
||
o === "%" ? M(l, r) : o === "&" ? (l & r) >>> 0 : o === "|" ? (l | r) >>> 0 : o === "^" ? (l ^ r) >>> 0 :
|
||
o === "<<" ? (l << (r & 31)) >>> 0 : o === ">>" ? l >>> (r & 31) : o === "<" ? +(l < r) : o === "<=" ? +(l <= r) :
|
||
o === ">" ? +(l > r) : o === ">=" ? +(l >= r) : o === "==" ? +(l === r) : o === "!=" ? +(l !== r) :
|
||
o === "&&" ? +(!!l && !!r) : +(!!l || !!r);
|
||
}
|
||
}
|
||
return st[0] & 255;
|
||
}
|
||
return { compile, parse, canon, rpn, run };
|
||
})();
|
||
/* (V10.8.75, MATH USER) JIANT BYTE's formula compiler (its firmware/src/fvm.c, GPL-3.0, the owner's: the grammar, the INT
|
||
and FIX types, the folding, the instructions) ported, and the bytes JIANT FM's math_user.c runs: the instructions BYTE's
|
||
fvm_compile makes, serialized. web/math_fvm_gold.json holds BYTE's own output for 142 formulas: math_test.mjs asks this
|
||
port for the same bytes and the same values. The language: C's expressions of t (the time), w (FLOAT's phase), a
|
||
(VARIANT's 1..16), n v (the note, its velocity); INT 32 bits unsigned (bytebeat), a number with a point FIX Q16.16
|
||
(floatbeat); sin cos tri saw sqr abs min max floor int fix rnd sat clip, a string read as a table ("36364689"[t>>11&7]).
|
||
JIANT FM has not BYTE's ph() lp() hp() (a state a voice) nor eu(): refused here. The bytes (EDITOR_PROTOCOL.md "100
|
||
FORMULA"): [0] the type (bit 0 FIX) | 2 a table pool follows ([1] its length, its bytes); then op | md << 6 each (md 0 the
|
||
stack, 1 a number (LEB128), 2 a variable's byte (bit 7 a per-sample one), 3 t); TAB (54) its table after it as a number.
|
||
At most 64 bytes, a stack of 12 */
|
||
const FVM = (() => {
|
||
const MAX = 64, DEPTH = 12, MAXINS = 64, POOL = 32, MAXNODE = 160, FS = 44100;
|
||
const INT = 0, FIX = 1;
|
||
const O = {};
|
||
["ADD", "SUB", "MUL", "DIVU", "MODU", "AND", "OR", "XOR", "SHL", "SHR", "LTU", "LEU", "GTU", "GEU", "EQ", "NE", "LTS", "LES",
|
||
"GTS", "GES", "LAND", "LOR", "MINU", "MAXU", "MINS", "MAXS", "MULF", "MULIF", "DIVF", "DIVFI", "MODF", "EU", "NBIN", "NEG", "NOT",
|
||
"LNOT", "ITOF", "FTOI", "ABS", "FLOOR", "SINI", "SINF", "TRII", "TRIF", "SAWI", "SAWF", "SQRI", "SQRF", "RNDI", "RNDF", "SAT",
|
||
"NUN", "PUSH", "SEL", "TAB", "PH", "LP", "HP", "SAVE", "MUSIC"].forEach((n, k) => { O[n] = k; });
|
||
const STK = 0, IMM = 1, UNI = 2, ARR = 3;
|
||
const SINE = Array.from({ length: 1025 }, (_, i) => Math.round(32767 * Math.sin(2 * Math.PI * i / 1024)));
|
||
const TANH = Array.from({ length: 257 }, (_, i) => Math.trunc(32767 * Math.tanh(i / 256 * 2)));
|
||
const sineI = (ph) => { const i = ph >>> 22, a = SINE[i], b = SINE[(i + 1) & 1023]; return a + (((b - a) * ((ph >>> 7) & 0x7FFF)) >> 15); };
|
||
const softclip = (x) => { const a = Math.abs(x), i = a >> 8, y = i >= 256 ? TANH[256] : TANH[i] + (((TANH[i + 1] - TANH[i]) * (a & 255)) >> 8); return x < 0 ? -y : y; };
|
||
const hash = (h) => { h = Math.imul(h, 0x9E3779B1); h ^= h >>> 15; h = Math.imul(h, 0x85EBCA77); return (h ^ (h >>> 13)) >>> 0; };
|
||
const EUT = [[3, 8], [5, 8], [2, 8], [3, 16], [5, 16], [7, 16], [9, 16], [4, 16], [11, 16], [5, 12], [7, 12], [4, 12], [3, 6], [2, 6], [6, 16], [13, 16]];
|
||
function eu(s, seed) { /* (BYTE's fvm_eu: only for folding eu() of numbers) */
|
||
const h = hash((Math.imul(seed, 0x9E3779B1) + Math.imul(s >>> 6, 0x85EBCA77)) >>> 0), g = [];
|
||
for (let i = 0; i < 2; i++) { const e = (h >>> (i * 8)) & 15, k = EUT[e][0], n = EUT[e][1], r = (h >>> (16 + i * 4)) & 15; g.push(+((Math.imul((s + r) >>> 0, k) >>> 0) % n < k)); }
|
||
switch (h >>> 30) { case 0: return g[0] | g[1]; case 1: return (g[0] & g[1]) | +((s & 15) === 0); case 2: return g[0] ^ g[1]; default: return (s >>> 4) & 1 ? g[1] : g[0]; }
|
||
}
|
||
const S = (x) => x | 0, U = (x) => x >>> 0;
|
||
function op2(o, a, b) { /* BYTE's FVM_OPS2 */
|
||
a >>>= 0; b >>>= 0;
|
||
switch (o) {
|
||
case O.ADD: return U(a + b); case O.SUB: return U(a - b); case O.MUL: case O.MULIF: return U(Math.imul(a, b));
|
||
case O.DIVU: return b ? U(Math.floor(a / b)) : 0; case O.MODU: return b ? a % b : 0;
|
||
case O.AND: return U(a & b); case O.OR: return U(a | b); case O.XOR: return U(a ^ b);
|
||
case O.SHL: return U(a << (b & 31)); case O.SHR: return a >>> (b & 31);
|
||
case O.LTU: return +(a < b); case O.LEU: return +(a <= b); case O.GTU: return +(a > b); case O.GEU: return +(a >= b);
|
||
case O.EQ: return +(a === b); case O.NE: return +(a !== b);
|
||
case O.LTS: return +(S(a) < S(b)); case O.LES: return +(S(a) <= S(b)); case O.GTS: return +(S(a) > S(b)); case O.GES: return +(S(a) >= S(b));
|
||
case O.LAND: return +(a !== 0 && b !== 0); case O.LOR: return +(a !== 0 || b !== 0);
|
||
case O.MINU: return a < b ? a : b; case O.MAXU: return a > b ? a : b;
|
||
case O.MINS: return S(a) < S(b) ? a : b; case O.MAXS: return S(a) > S(b) ? a : b;
|
||
case O.MULF: return U(Number(BigInt.asIntN(32, (BigInt(S(a)) * BigInt(S(b))) >> 16n)));
|
||
case O.DIVF: return S(b) ? U(Number(BigInt.asIntN(32, (BigInt(S(a)) * 65536n) / BigInt(S(b))))) : 0;
|
||
case O.DIVFI: return S(b) && S(b) !== -1 ? U(Math.trunc(S(a) / S(b))) : S(b) ? U(-S(a)) : 0;
|
||
case O.MODF: return S(b) && S(b) !== -1 ? U(S(a) % S(b)) : 0;
|
||
case O.EU: return eu(a, b);
|
||
}
|
||
return 0;
|
||
}
|
||
function op1(o, a) { /* BYTE's FVM_OPS1 */
|
||
a >>>= 0;
|
||
switch (o) {
|
||
case O.NEG: return U(-S(a)); case O.NOT: return U(~a); case O.LNOT: return +(a === 0);
|
||
case O.ITOF: return U(a << 16); case O.FTOI: return U(S(a) >> 16);
|
||
case O.ABS: return S(a) < 0 ? U(-S(a)) : a; case O.FLOOR: return U(a & 0xFFFF0000);
|
||
case O.SINI: return U((sineI(U(a << 24)) + 32768) >> 8); case O.SINF: return U(sineI(U(a << 16)) * 2);
|
||
case O.TRII: return a & 128 ? 255 - ((a & 127) << 1) : (a & 127) << 1;
|
||
case O.TRIF: return a & 0x8000 ? U(196608 - 4 * (a & 0xFFFF)) : U(4 * (a & 0xFFFF) - 65536);
|
||
case O.SAWI: return a & 255; case O.SAWF: return U(2 * (a & 0xFFFF) - 65536);
|
||
case O.SQRI: return a & 128 ? 0 : 255; case O.SQRF: return a & 0x8000 ? 0xFFFF0000 : 65536;
|
||
case O.RNDI: return hash(a); case O.RNDF: return U(S(hash(a)) >> 15);
|
||
case O.SAT: return U(softclip(S(a) >> 1) * 2);
|
||
}
|
||
return 0;
|
||
}
|
||
/* ---- the compiler: fvm.c's functions, in its order and with its names */
|
||
const NK = { NUM: 0, ARR: 1, UNI: 2, OP1: 3, OP2: 4, SEL: 5, TAB: 6, ST: 7 };
|
||
const TK = { ADD: 1, SUB: 2, MUL: 3, DIV: 4, MOD: 5, AND: 6, OR: 7, XOR: 8, SHL: 9, SHR: 10, LT: 11, LE: 12, GT: 13, GE: 14, EQ: 15, NE: 16, LAND: 17, LOR: 18, MIN: 19, MAX: 20 };
|
||
const VARS = { t: [NK.ARR, INT, 0], w: [NK.ARR, FIX, 1], T: [NK.ARR, FIX, 2], x: [NK.ARR, INT, 3], X: [NK.ARR, FIX, 4],
|
||
a: [NK.UNI, INT, 0], b: [NK.UNI, INT, 1], c: [NK.UNI, INT, 2], d: [NK.UNI, INT, 3], A: [NK.UNI, FIX, 4], B: [NK.UNI, FIX, 5],
|
||
C: [NK.UNI, FIX, 6], D: [NK.UNI, FIX, 7], n: [NK.UNI, INT, 8], v: [NK.UNI, INT, 9], s: [NK.UNI, INT, 10], P: [NK.ARR, FIX, 12],
|
||
p: [NK.UNI, FIX, 11], freq: [NK.UNI, FIX, 12], O1: [NK.ARR, FIX, 5], O2: [NK.ARR, FIX, 6], O3: [NK.ARR, FIX, 7], O4: [NK.ARR, FIX, 8],
|
||
O5: [NK.ARR, FIX, 9], O6: [NK.ARR, FIX, 10], I: [NK.ARR, FIX, 11], w3: [NK.ARR, FIX, 4], w5: [NK.ARR, FIX, 11], wd: [NK.ARR, FIX, 3] };
|
||
const CALLS = { sin: 1, cos: 1, tri: 1, saw: 1, sqr: 1, abs: 1, min: 2, max: 2, floor: 1, int: 1, fix: 1, rnd: 1, sat: 1, clip: 1, ph: 1, lp: 2, hp: 2, eu: 2,
|
||
note: 3, chord: 3, kick: 1, snare: 1, hat: 1 };
|
||
const BINS = [["*", 0, TK.MUL], ["/", 0, TK.DIV], ["%", 0, TK.MOD], ["+", 1, TK.ADD], ["-", 1, TK.SUB], ["<<", 2, TK.SHL], [">>", 2, TK.SHR],
|
||
["<=", 3, TK.LE], [">=", 3, TK.GE], ["<", 3, TK.LT], [">", 3, TK.GT], ["==", 4, TK.EQ], ["!=", 4, TK.NE], ["&", 5, TK.AND], ["^", 6, TK.XOR],
|
||
["|", 7, TK.OR], ["&&", 8, TK.LAND], ["||", 9, TK.LOR]];
|
||
const ERR = ["", "syntax", "unknown name", "wrong arguments", "too long (64 instructions)", "too deep", "too complex", "strings too long (32 bytes)", "", "empty"];
|
||
function compileIns(src) {
|
||
const c = { s: String(src), i: 0, nd: [], err: 0, pos: 0, pool: [], ins: [], sp: 0, maxsp: 0, pd: 0, gd: 0, bati: -1, batk: -1 };
|
||
const len = c.s.length, ch = () => (c.i < len ? c.s.charCodeAt(c.i) : 0);
|
||
const fail = (code) => { if (!c.err) { c.err = code; c.pos = c.i; } };
|
||
const nw = (kind, op, ty, a, b, cc, v) => { if (c.nd.length >= MAXNODE) { fail(6); return 0; } c.nd.push({ kind, op, ty, a, b, c: cc, v: v >>> 0 }); return c.nd.length - 1; };
|
||
const ND = (x) => c.nd[x] || { kind: NK.NUM, ty: INT, v: 0 };
|
||
const num = (ty, v) => nw(NK.NUM, 0, ty, 0, 0, 0, v);
|
||
const un = (op, a, ty) => (ND(a).kind === NK.NUM ? num(ty, op1(op, ND(a).v)) : nw(NK.OP1, op, ty, a, 0, 0, 0));
|
||
const tofix = (a) => (ND(a).ty === FIX ? a : un(O.ITOF, a, FIX));
|
||
const toint = (a) => (ND(a).ty === INT ? a : un(O.FTOI, a, INT));
|
||
const bin = (op, a, b, ty) => (ND(a).kind === NK.NUM && ND(b).kind === NK.NUM ? num(ty, op2(op, ND(a).v, ND(b).v)) : nw(NK.OP2, op, ty, a, b, 0, 0));
|
||
const OPI = [0, O.ADD, O.SUB, O.MUL, O.DIVU, O.MODU, 0, 0, 0, 0, 0, O.LTU, O.LEU, O.GTU, O.GEU, O.EQ, O.NE, 0, 0, O.MINU, O.MAXU];
|
||
const OPF = [0, O.ADD, O.SUB, O.MULF, O.DIVF, O.MODF, 0, 0, 0, 0, 0, O.LTS, O.LES, O.GTS, O.GES, O.EQ, O.NE, 0, 0, O.MINS, O.MAXS];
|
||
function binop(tk, a, b) {
|
||
switch (tk) {
|
||
case TK.AND: return bin(O.AND, toint(a), toint(b), INT); case TK.OR: return bin(O.OR, toint(a), toint(b), INT);
|
||
case TK.XOR: return bin(O.XOR, toint(a), toint(b), INT); case TK.SHL: return bin(O.SHL, toint(a), toint(b), INT);
|
||
case TK.SHR: return bin(O.SHR, toint(a), toint(b), INT); case TK.LAND: return bin(O.LAND, a, b, INT); case TK.LOR: return bin(O.LOR, a, b, INT);
|
||
}
|
||
if (ND(a).ty === INT && ND(b).ty === INT) return bin(OPI[tk], a, b, INT);
|
||
if (tk === TK.MUL && ND(a).ty !== ND(b).ty) { if (ND(a).ty === FIX) [a, b] = [b, a]; return bin(O.MULIF, a, b, FIX); }
|
||
if (tk === TK.DIV && ND(a).ty === FIX && ND(b).ty === INT) return bin(O.DIVFI, a, b, FIX);
|
||
a = tofix(a); b = tofix(b);
|
||
return bin(OPF[tk], a, b, tk >= TK.LT && tk <= TK.NE ? INT : FIX);
|
||
}
|
||
const ws = () => { while (c.i < len && " \t\n\r".includes(c.s[c.i])) c.i++; };
|
||
function eat(t) {
|
||
ws();
|
||
let k = 0;
|
||
while (k < t.length && c.i + k < len && c.s[c.i + k] === t[k]) k++;
|
||
if (k < t.length) return false;
|
||
if (t.length === 1 && c.i + 1 < len) {
|
||
const n = c.s[c.i + 1];
|
||
if ((t === "<" || t === ">") && (n === t || n === "=")) return false;
|
||
if ((t === "&" || t === "|") && n === t) return false;
|
||
if ((t === "=" || t === "!") && n === "=") return false;
|
||
}
|
||
c.i += k; return true;
|
||
}
|
||
const isal = (x) => (x >= 97 && x <= 122) || (x >= 65 && x <= 90) || x === 95, isdg = (x) => x >= 48 && x <= 57;
|
||
function number() {
|
||
let v = 0, fr = 0, sc = 1, isf = false;
|
||
if (ch() === 48 && c.i + 1 < len && (c.s[c.i + 1] === "x" || c.s[c.i + 1] === "X")) {
|
||
c.i += 2;
|
||
for (;;) { const x = ch(); let d; if (isdg(x)) d = x - 48; else if (x >= 97 && x <= 102) d = x - 87; else if (x >= 65 && x <= 70) d = x - 55; else break; v = U(Math.imul(v, 16) + d); c.i++; }
|
||
} else {
|
||
while (isdg(ch())) { v = U(Math.imul(v, 10) + ch() - 48); c.i++; }
|
||
if (ch() === 46) { isf = true; c.i++; while (isdg(ch())) { if (sc < 100000000) { fr = fr * 10 + ch() - 48; sc *= 10; } c.i++; } }
|
||
}
|
||
while (ch() === 117 || ch() === 85) c.i++;
|
||
if (isf) return num(FIX, U((v << 16) + Number((BigInt(fr) * 65536n + BigInt(Math.floor(sc / 2))) / BigInt(sc))));
|
||
return num(INT, v);
|
||
}
|
||
function call(nm, ar) {
|
||
const a = ar[0], b = ar[1], fx = ND(a).ty === FIX;
|
||
switch (nm) {
|
||
case "note": case "chord": case "kick": case "snare": case "hat": fail(2); return 0; /* (FUNC's: not here) */
|
||
case "sin": return fx ? un(O.SINF, a, FIX) : un(O.SINI, a, INT);
|
||
case "cos": return fx ? un(O.SINF, bin(O.ADD, a, num(FIX, 16384), FIX), FIX) : un(O.SINI, bin(O.ADD, a, num(INT, 64), INT), INT);
|
||
case "tri": return fx ? un(O.TRIF, a, FIX) : un(O.TRII, a, INT);
|
||
case "saw": return fx ? un(O.SAWF, a, FIX) : un(O.SAWI, a, INT);
|
||
case "sqr": return fx ? un(O.SQRF, a, FIX) : un(O.SQRI, a, INT);
|
||
case "abs": return un(O.ABS, a, ND(a).ty);
|
||
case "min": return binop(TK.MIN, a, b); case "max": return binop(TK.MAX, a, b);
|
||
case "floor": return fx ? un(O.FLOOR, a, FIX) : a;
|
||
case "int": return toint(a); case "fix": return tofix(a);
|
||
case "rnd": return fx ? un(O.RNDF, a, FIX) : un(O.RNDI, a, INT);
|
||
case "sat": return un(O.SAT, tofix(a), FIX);
|
||
case "clip": return bin(O.MAXS, bin(O.MINS, tofix(a), num(FIX, 65536), FIX), num(FIX, U(-65536)), FIX);
|
||
case "ph": return nw(NK.ST, O.PH, FIX, tofix(a), 0, 0, 0);
|
||
case "eu": return bin(O.EU, toint(a), toint(b), INT);
|
||
default: return nw(NK.ST, nm === "lp" ? O.LP : O.HP, FIX, tofix(a), tofix(b), 0, 0);
|
||
}
|
||
}
|
||
function primary() {
|
||
ws();
|
||
const x = ch();
|
||
if (isdg(x) || (x === 46 && c.i + 1 < len && isdg(c.s.charCodeAt(c.i + 1)))) return number();
|
||
if (x === 40) { c.i++; const k = expr(); if (!eat(")")) fail(1); return k; }
|
||
if (x === 34 || x === 39) { /* a string as a table: "..."[i] */
|
||
const q = c.s[c.i], st0 = c.pool.length;
|
||
let st = st0, n = 0;
|
||
c.i++;
|
||
while (c.i < len && c.s[c.i] !== q) { if (c.pool.length >= POOL) { fail(7); return 0; } c.pool.push(c.s.charCodeAt(c.i++) & 255); n++; }
|
||
if (c.s[c.i] !== q || !n || n > 255) { fail(1); return 0; }
|
||
c.i++;
|
||
for (let k0 = 0; k0 + n <= st0; k0++) { /* (the same string once) */
|
||
let j = 0;
|
||
while (j < n && c.pool[k0 + j] === c.pool[st0 + j]) j++;
|
||
if (j === n) { c.pool.length = st0; st = k0; break; }
|
||
}
|
||
if (!eat("[")) { fail(1); return 0; }
|
||
const ix = toint(expr());
|
||
if (!eat("]")) fail(1);
|
||
if (ND(ix).kind === NK.NUM) return num(INT, c.pool[st + ND(ix).v % n]);
|
||
return nw(NK.TAB, O.TAB, INT, ix, 0, 0, st << 8 | n);
|
||
}
|
||
if (isal(x)) {
|
||
const s0 = c.i;
|
||
while (isal(ch()) || isdg(ch())) c.i++;
|
||
const nm = c.s.slice(s0, c.i);
|
||
if (nm.length >= 8) { fail(2); return 0; }
|
||
ws();
|
||
if (ch() === 40) {
|
||
c.i++;
|
||
if (!Object.prototype.hasOwnProperty.call(CALLS, nm)) { c.i = s0; fail(2); return 0; }
|
||
const ar = [];
|
||
if (!eat(")")) {
|
||
do { if (ar.length >= 3) { fail(3); return 0; } ar.push(cond()); } while (eat(","));
|
||
if (!eat(")")) fail(1);
|
||
}
|
||
if (ar.length !== CALLS[nm]) { fail(3); return 0; }
|
||
return call(nm, ar);
|
||
}
|
||
if (nm === "sr") return num(INT, FS);
|
||
if (nm === "PI") return num(FIX, 205887);
|
||
if (Object.prototype.hasOwnProperty.call(VARS, nm)) { const [k, ty, ix] = VARS[nm]; return nw(k, 0, ty, 0, 0, 0, ix); }
|
||
c.i = s0; fail(2); return 0;
|
||
}
|
||
fail(1); return 0;
|
||
}
|
||
function unaryInner() {
|
||
if (c.err) return 0;
|
||
if (eat("-")) { const a = unary(); return un(O.NEG, a, ND(a).ty); }
|
||
if (eat("+")) return unary();
|
||
if (eat("~")) return un(O.NOT, toint(unary()), INT);
|
||
if (eat("!")) return un(O.LNOT, unary(), INT);
|
||
return primary();
|
||
}
|
||
function unary() { if (c.pd >= 16) { fail(5); return 0; } c.pd++; const r = unaryInner(); c.pd--; return r; }
|
||
function binat() {
|
||
ws();
|
||
if (c.bati === c.i) return c.batk;
|
||
c.bati = c.i; c.batk = -1;
|
||
const a = c.s[c.i] || "", b = c.s[c.i + 1] || "";
|
||
if (a === ">" && b === ">" && c.s[c.i + 2] === ">") return (c.batk = BINS.length);
|
||
for (let k = 0; k < BINS.length; k++) {
|
||
const t = BINS[k][0];
|
||
if (t[0] !== a) continue;
|
||
if (t.length > 1) { if (t[1] === b) return (c.batk = k); continue; }
|
||
if ((a === "<" || a === ">") && (b === a || b === "=")) continue;
|
||
if ((a === "&" || a === "|") && b === a) continue;
|
||
if ((a === "=" || a === "!") && b === "=") continue;
|
||
return (c.batk = k);
|
||
}
|
||
return -1;
|
||
}
|
||
function level(lv) {
|
||
let a = lv ? level(lv - 1) : unary();
|
||
for (;;) {
|
||
if (c.err) return 0;
|
||
const k = binat();
|
||
if (k === BINS.length && lv === 2) { c.i += 3; a = binop(TK.SHR, a, level(1)); }
|
||
else if (k >= 0 && k < BINS.length && BINS[k][1] === lv) { c.i += BINS[k][0].length; a = binop(BINS[k][2], a, lv ? level(lv - 1) : unary()); }
|
||
else return a;
|
||
}
|
||
}
|
||
function cond() {
|
||
const q = level(9);
|
||
if (c.err || !eat("?")) return q;
|
||
let x = expr();
|
||
if (!eat(":")) { fail(1); return 0; }
|
||
let y = cond();
|
||
if (ND(x).ty !== ND(y).ty) { x = tofix(x); y = tofix(y); }
|
||
if (ND(q).kind === NK.NUM) return ND(q).v ? x : y;
|
||
return nw(NK.SEL, O.SEL, ND(x).ty, q, x, y, 0);
|
||
}
|
||
function expr() { let a = cond(); while (!c.err && eat(",")) a = cond(); return a; }
|
||
/* the tree to the instructions */
|
||
const emit = (op, md, k) => { if (c.ins.length >= MAXINS) { fail(4); return; } c.ins.push({ op, md, k: k >>> 0 }); };
|
||
const psp = (d) => { c.sp += d; if (c.sp > c.maxsp) c.maxsp = c.sp; };
|
||
const leaf = (n) => (n.kind === NK.NUM ? IMM : n.kind === NK.UNI ? UNI : n.kind === NK.ARR ? ARR : STK);
|
||
const commut = (op) => [O.ADD, O.MUL, O.AND, O.OR, O.XOR, O.EQ, O.NE, O.LAND, O.LOR, O.MINU, O.MAXU, O.MINS, O.MAXS, O.MULF].includes(op);
|
||
const MIRROR = { [O.LTU]: O.GTU, [O.GTU]: O.LTU, [O.LEU]: O.GEU, [O.GEU]: O.LEU, [O.LTS]: O.GTS, [O.GTS]: O.LTS, [O.LES]: O.GES, [O.GES]: O.LES };
|
||
const mirror = (op) => (op in MIRROR ? MIRROR[op] : commut(op) ? op : O.NBIN);
|
||
function gen(x) { if (c.gd >= 24) { fail(5); return; } c.gd++; genInner(x); c.gd--; }
|
||
function genInner(x) {
|
||
const n = ND(x);
|
||
if (c.err) return;
|
||
switch (n.kind) {
|
||
case NK.NUM: case NK.UNI: case NK.ARR: emit(O.PUSH, leaf(n), n.v); psp(1); return;
|
||
case NK.OP1: gen(n.a); emit(n.op, STK, 0); return;
|
||
case NK.TAB: gen(n.a); emit(O.TAB, STK, n.v); return;
|
||
case NK.SEL: gen(n.a); gen(n.b); gen(n.c); emit(O.SEL, STK, 0); psp(-2); return;
|
||
case NK.ST: {
|
||
gen(n.a);
|
||
if (n.op === O.PH) { emit(O.PH, STK, 0); return; }
|
||
const md = leaf(ND(n.b));
|
||
if (md === STK) { gen(n.b); psp(-1); }
|
||
emit(n.op, md, ND(n.b).v); return;
|
||
}
|
||
case NK.OP2: {
|
||
let op = n.op, l = n.a, r = n.b;
|
||
const ml = leaf(ND(l));
|
||
let md = leaf(ND(r));
|
||
if (md === STK && ml !== STK && mirror(op) !== O.NBIN) { op = mirror(op); r = n.a; l = n.b; md = leaf(ND(r)); }
|
||
gen(l);
|
||
if (md === STK) { gen(r); psp(-1); }
|
||
emit(op, md, md === STK ? 0 : ND(r).v); return;
|
||
}
|
||
}
|
||
}
|
||
ws();
|
||
let ty = INT;
|
||
if (c.i >= len) c.err = 9;
|
||
else if (/^func\b/.test(c.s.slice(c.i))) fail(2);
|
||
else {
|
||
const root = expr();
|
||
ws();
|
||
if (!c.err && c.i < len) fail(1);
|
||
if (!c.err) { ty = ND(root).ty; gen(root); }
|
||
if (!c.err && c.maxsp > DEPTH) fail(5);
|
||
}
|
||
return { err: c.err, pos: c.pos, ins: c.ins, pool: c.pool, ty, depth: c.maxsp };
|
||
}
|
||
/* compile: {ok, code (the bytes), ty, fix, depth} or {ok: false, error, pos} */
|
||
function compile(src) {
|
||
const r = compileIns(src);
|
||
if (r.err) return { ok: false, error: ERR[r.err] || "error", pos: r.pos };
|
||
const out = [r.ty | (r.pool.length ? 2 : 0)];
|
||
if (r.pool.length) out.push(r.pool.length, ...r.pool);
|
||
const leb = (k) => { do { const b = k & 127; k >>>= 7; out.push(b | (k ? 128 : 0)); } while (k); };
|
||
for (const ins of r.ins) {
|
||
if (ins.op === O.PH || ins.op === O.LP || ins.op === O.HP || ins.op === O.EU || ins.op > O.TAB)
|
||
return { ok: false, error: "ph() lp() hp() eu(): JIANT BYTE's only, not in JIANT FM", pos: 0 };
|
||
if (ins.md === ARR && ins.k === 0) { out.push(ins.op | 3 << 6); continue; }
|
||
out.push(ins.op | (ins.md === STK ? 0 : ins.md === IMM ? 1 : 2) << 6);
|
||
if (ins.op === O.TAB || ins.md === IMM) leb(ins.k);
|
||
else if (ins.md === UNI) out.push(ins.k);
|
||
else if (ins.md === ARR) out.push(128 | ins.k);
|
||
}
|
||
if (out.length > MAX) return { ok: false, error: `too long for JIANT FM (${out.length} of ${MAX} bytes)`, pos: 0 };
|
||
return { ok: true, code: out, ty: r.ty, fix: r.ty === FIX, depth: r.depth };
|
||
}
|
||
/* the bytes run as math_user.c mu_run runs them (the same values; its masks: any bytes) */
|
||
function run(code, t, w, a, n = 60, v = 100) {
|
||
const s = new Uint32Array(16), u = [a >>> 0, n, v], e = Math.min(code.length, MAX);
|
||
let sp = 0, p = 1;
|
||
if (code[0] & 2) p = 2 + (code[1] & 31);
|
||
while (p < e) {
|
||
let o = code[p++] | 0, b = 0, k;
|
||
const md = o >> 6;
|
||
o &= 63;
|
||
if (md === 1 || o === O.TAB) { for (let sh = 0; sh < 32; sh += 7) { k = code[p++] | 0; b = U(b | (k & 127) << sh); if (!(k & 128)) break; } }
|
||
else if (md === 2) { k = code[p++] | 0; b = k === 128 ? t >>> 0 : k === 129 ? w >>> 0 : k === 0 ? u[0] : k === 8 ? u[1] : k === 9 ? u[2] : 0; }
|
||
else if (md === 3) b = t >>> 0;
|
||
else if (o < O.NBIN) b = s[--sp & 15];
|
||
if (o === O.PUSH) { s[sp++ & 15] = b; continue; }
|
||
const i = (sp - 1) & 15;
|
||
if (o === O.SEL) { sp -= 2; s[(sp - 1) & 15] = s[(sp - 1) & 15] ? s[sp & 15] : s[(sp + 1) & 15]; }
|
||
else if (o === O.TAB) { k = b & 255; s[i] = k ? (code[2 + (((b >>> 8) + s[i] % k) & 31)] | 0) : 0; }
|
||
else s[i] = o < O.NBIN ? op2(o, s[i], b) : op1(o, s[i]);
|
||
}
|
||
return s[0];
|
||
}
|
||
/* the sample it plays (BYTE's fvm_sample: INT its low byte as bytebeat, FIX -1 .. 1), Q15 */
|
||
const sample = (code, x) => ((code[0] & 1) ? Math.max(-32767, Math.min(32767, (x | 0) >> 1)) : (x & 255) * 256 - 32640);
|
||
/* pack7 (BACKUP_PUT's groups: a byte of the group's bits 7, then up to 7 bytes) and back */
|
||
function pack7(b) {
|
||
const o = [];
|
||
for (let i = 0; i < b.length; i += 7) {
|
||
const g = b.slice(i, i + 7);
|
||
let m = 0;
|
||
g.forEach((x, j) => { m |= (x >> 7) << j; });
|
||
o.push(m, ...g.map((x) => x & 127));
|
||
}
|
||
return o;
|
||
}
|
||
function unpack7(a) {
|
||
const o = [];
|
||
for (let i = 0; i < a.length;) { const m = a[i++], k = Math.min(7, a.length - i); for (let j = 0; j < k; j++) o.push(a[i++] | ((m >> j) & 1) << 7); }
|
||
return o;
|
||
}
|
||
return { compile, run, sample, pack7, unpack7, MAX, DEPTH, O, hash };
|
||
})();
|
||
/* eng_lofi.c lofi_mut: VAR as a mutation of the time (v >> 4 the way, v & 15 how much) */
|
||
function mathMut(t, v) {
|
||
const k = v & 15;
|
||
switch ((v >> 4) & 7) {
|
||
case 0: return t >>> 0;
|
||
case 1: return (t + Math.imul(t >>> (9 - (k >> 1)), k + 1)) >>> 0;
|
||
case 2: return (t ^ (t >>> (2 + (k >> 1)))) >>> 0;
|
||
case 3: return (t | (t >>> (1 + (k >> 1)))) >>> 0;
|
||
case 4: return (t & ~(1 << (2 + (k >> 1)))) >>> 0;
|
||
case 5: { const m = ((1 << (3 + (k >> 1))) - 1) >>> 0; return ((t & ~m) | (~t & m)) >>> 0; }
|
||
case 6: return Math.imul(t, 3 + k) >>> 0;
|
||
default: return (t ^ Math.imul(t >>> 3, (Math.imul(k + 1, 0x9E3779B1) >>> 0) >>> 24)) >>> 0;
|
||
}
|
||
}
|
||
/* eng_lofi.c lofi_motion: MOTION 0..127 -> the slow time's speed, Q8 (64: 256, as written) */
|
||
function mathMotion(m) { const e = Math.max(0, Math.min(127, m >= 128 ? m - 128 : m)) + 64; return ((16 + (e & 15)) << (e >> 4)) >>> 4; }
|
||
/* the BYTE voice (lofi_byte_render) as a model: the note's time t (31 x its frequency a second), MOTION's slow bits,
|
||
LOOP's window, the start, VAR's mutation, BEND's fold, the 8 bits as a sample, GRIT's / 4B/2's hold, CHIP's bits, the
|
||
two smoothing poles; then LOFI_GAIN, the DC out and a plain envelope (the FILTER page open; the effects not here). opt: {fn, f
|
||
(a stock index: its start), note, chip, var, motion, grit, bend, loop, rate, secs, gate} -> Float32Array */
|
||
function mathRenderByte(o) {
|
||
const rate = o.rate || 44100, n = Math.round((o.secs || 2) * rate), out = new Float32Array(n);
|
||
const fn = o.fn, vr = Math.max(0, Math.min(127, o.var | 0)), a = 1 + (vr >> 3), chip = o.chip ?? 2;
|
||
const bits = chip === 2 ? 8 : chip === 3 ? 1 : 4;
|
||
let hold = (1 + (chip === 1 ? 1 : 0)) * (1 + ((o.grit | 0) >> 3));
|
||
const bs = o.bend ? 13 - Math.floor(o.bend / 11) : 0;
|
||
const lm = o.loop ? ((1 << (17 - Math.floor(o.loop * 12 / 127))) - 1) >>> 0 : 0xFFFFFFFF;
|
||
const t0 = (o.f >= 0 && o.f < 32 ? MATH_T0[o.f] : 0) << 9;
|
||
const mul = mathMotion(o.motion | 0);
|
||
/* the firmware's integers: inc (pitch_inc, a turn = 2^32 at 44.1 kHz), ti = (inc >> 8) * 31 t a sample (Q24), the slow
|
||
time ((ti >> 8) * mul) >> 16 a sample (Q8: truncated, as the device's) */
|
||
const inc = Math.round(440 * Math.pow(2, ((o.note ?? 60) - 69) / 12) / 44100 * 4294967296) * 44100 / rate;
|
||
const ti = Math.floor(inc / 256) * 31, tsi = Math.floor(Math.floor(ti / 256) * mul / 65536);
|
||
let tt = 0, tf = 0, ts = 0, held = 0, cnt = 0, l1 = 0, l2 = 0, dx = 0, dy = 0;
|
||
const dk = 1 - 2 * Math.PI * 20 / rate; /* (the output's DC out, as the device's mix: ~20 Hz) */
|
||
const gate = Math.round((o.gate ?? (o.secs || 2) * 0.8) * rate), atk = rate * 0.004, rel = rate * 0.08;
|
||
for (let i = 0; i < n; i++) {
|
||
if (--cnt <= 0) {
|
||
const te = mul === 256 ? tt : ((tt & 255) | ((ts >>> 8) & ~255)) >>> 0;
|
||
const tl = mathMut((((te & lm) >>> 0) + t0) >>> 0, vr), tw = bs ? (tl ^ (tl >>> bs)) >>> 0 : tl;
|
||
let s = (fn(tw, a) & 255) * 256 - 32640;
|
||
if (bits < 8) s = ((s + (1 << (15 - bits))) >> (16 - bits)) << (16 - bits);
|
||
held = s; cnt = hold;
|
||
}
|
||
tf += ti; tt = (tt + Math.floor(tf / 16777216)) >>> 0; tf %= 16777216;
|
||
ts = (ts + tsi) >>> 0;
|
||
l1 += (((held >> 1) - l1) * 2) / 4;
|
||
l2 += ((l1 - l2) * 2) / 4;
|
||
const env = Math.min(1, i / atk) * (i < gate ? 1 : Math.max(0, 1 - (i - gate) / rel));
|
||
dy = l2 - dx + dk * dy; dx = l2;
|
||
out[i] = dy / 32768 * 0.13 * env; /* (0.13: as loud as the emulator's MATH, its median) */
|
||
}
|
||
return out;
|
||
}
|
||
/* the generator (the owner: "poco versátiles, cambios muy suaves"): seeded (xorshift32, as ui_euclid.c eu_rnd), in
|
||
families each its own sound, and CHAOS (0 .. 100) changing the formula's build, not only its numbers. A formula of
|
||
JIANT FM's MATH USER (V10.8.75): FVM compiles it to at most 64 bytes and a stack of 12, with none of ph() lp() hp()
|
||
eu() nor FUNC's calls and only t w a n v; INT (bytebeat, WAVE BYTE: 5) or FIX (floatbeat, WAVE FLOAT: 6).
|
||
mathGenerate(seed) a text (as before): a family from the seed, CHAOS 40
|
||
mathGenerate(seed, {family, chaos}) {src, fix, wave (5 | 6), family, chaos, bytes, stack}; family one of
|
||
MATH_FAMILIES' ids or "any" (from the seed); one (seed, family, chaos) is
|
||
one formula
|
||
CHAOS: 0 the family's own shapes with its musical numbers; then, the higher, the more odd numbers in them and the more
|
||
rewrites of the formula (each one kept only while it still fits the device): from a rhythmic gate or a second voice
|
||
(20 ..) to t or w bent into another time, a bit-crush, an xor, a phase modulation (30 ..), to a modulo, a waveshaper,
|
||
a switch between two formulas, another family's formula mixed in (55 ..), and t replaced by a whole other formula,
|
||
every t bent, two formulas multiplied (80 ..). Each is heard (FVM.run, as the device) before it is kept: sounding in
|
||
most of four places far apart, not stuck at one value, not white noise, changing over time; else the next try (a
|
||
seed's tries are its own, so the same again) */
|
||
const MATH_FAMILIES = [
|
||
{ id: "sierpinski", en: "Sierpinski / XOR", es: "Sierpinski / XOR", ja: "シェルピンスキー / XOR", fix: false },
|
||
{ id: "melodic", en: "Melodic", es: "Melódica", ja: "メロディ", fix: false },
|
||
{ id: "fm", en: "FM / float", es: "FM / float", ja: "FM / フロート", fix: true },
|
||
{ id: "glitch", en: "Glitch / granular", es: "Glitch / granular", ja: "グリッチ / グラニュラー", fix: false },
|
||
{ id: "drone", en: "Drone", es: "Drone", ja: "ドローン", fix: true },
|
||
{ id: "rhythm", en: "Rhythm", es: "Ritmo", ja: "リズム", fix: false },
|
||
{ id: "chip", en: "Chip / pulse", es: "Chip / pulso", ja: "チップ / パルス", fix: false },
|
||
];
|
||
function mathRng(seed) { let s = (seed >>> 0) || 0x9E3779B9; return () => { s ^= s << 13; s >>>= 0; s ^= s >>> 17; s ^= s << 5; s >>>= 0; return s; }; }
|
||
/* the scales as a table's characters (each the ratio x 48: 48 '0' the root, 72 'H' the fifth, 96 '`' the octave; never
|
||
a quote or a backslash): major and minor pentatonic, the harmonics, dorian, minor */
|
||
const MG_SCALES = [[48, 54, 60, 72, 80, 96, 108], [48, 58, 64, 72, 86, 96, 115], [48, 60, 72, 84, 96, 108, 120],
|
||
[48, 54, 58, 64, 72, 80, 86, 96], [48, 54, 58, 64, 72, 77, 86, 96]];
|
||
const MG_FIX = (v) => { const s = String(Math.round(v * 1000) / 1000); return s.includes(".") ? s : s + ".0"; };
|
||
function mgCtx(r, c) {
|
||
const g = { r, c, u: () => r() / 4294967296, pick: (a) => a[r() % a.length], rn: (lo, hi) => lo + r() % (hi - lo + 1) };
|
||
g.odd = () => g.u() < c * 0.7; /* (an odd number instead of a musical one) */
|
||
g.k = (list, lo, hi) => (g.odd() ? g.rn(lo, hi) : g.pick(list));
|
||
g.kf = (list, lo, hi) => MG_FIX(g.odd() ? lo + g.u() * (hi - lo) : g.pick(list));
|
||
g.ka = (list, lo, hi) => (g.u() < 0.15 ? "a" : g.k(list, lo, hi)); /* (VARIANT's a now and then) */
|
||
/* a line of n notes of a scale (a walk, now and then a leap; at CHAOS anywhere), as a table */
|
||
g.seq = (n) => {
|
||
const sc = g.pick(MG_SCALES); let i = 0, s = "";
|
||
for (let k = 0; k < n; k++) {
|
||
const ch = g.odd() && g.u() < 0.5 ? g.pick([40, 43, 45, 47, 49, 53, 59, 61, 67, 71, 79, 83, 89, 97, 101, 103, 107, 113])
|
||
: sc[i];
|
||
s += String.fromCharCode(ch);
|
||
i = Math.max(0, Math.min(sc.length - 1, i + g.pick([-2, -1, -1, 1, 1, 2, 0, 3, -3])));
|
||
}
|
||
return `"${s}"`;
|
||
};
|
||
g.chord = () => { const sc = g.pick(MG_SCALES), r0 = g.rn(0, 2); return `"${[0, 2, 4, 6].map((d) => String.fromCharCode(sc[Math.min(sc.length - 1, r0 + d)])).join("")}"`; };
|
||
return g;
|
||
}
|
||
/* the families' own shapes (CHAOS 0: one of these with musical numbers) */
|
||
const MG_FAM = {
|
||
sierpinski: (g) => g.pick([
|
||
() => `t & t >> ${g.rn(6, 9)}`,
|
||
() => `t * (t >> ${g.rn(10, 12)} & t >> ${g.rn(7, 9)} & ${g.k([123, 63, 47, 29], 17, 250)} & t >> ${g.rn(3, 5)})`,
|
||
() => `(t * ${g.ka([3, 5, 7, 9], 3, 31)} & t >> ${g.rn(5, 8)}) | (t * ${g.k([2, 3, 4, 5], 2, 29)} & t >> ${g.rn(8, 11)})`,
|
||
() => `t * ((t >> ${g.rn(9, 12)} | t >> ${g.rn(7, 9)}) & ${g.k([63, 46, 82, 29], 13, 127)} & t >> ${g.rn(3, 6)})`,
|
||
() => `(t ^ t >> ${g.rn(5, 9)}) * (t >> ${g.rn(10, 13)} & ${g.ka([3, 5, 7], 3, 15)})`,
|
||
() => `(t & t >> ${g.rn(8, 10)}) * (t >> ${g.rn(4, 6)} & t >> ${g.rn(9, 12)})`,
|
||
() => `t * (t >> ${g.rn(8, 10)} ^ t >> ${g.rn(11, 13)}) & t >> ${g.rn(5, 7)}`,
|
||
() => `(t * ${g.k([9, 5, 3], 3, 21)} & t >> ${g.rn(4, 5)}) | (t * ${g.k([5, 3, 2], 2, 13)} & t >> ${g.rn(7, 8)}) | (t * ${g.k([3, 2], 2, 9)} & t >> ${g.rn(10, 11)})`,
|
||
])(),
|
||
melodic: (g) => {
|
||
const K = g.rn(11, 13), S = g.rn(2, 3), q = g.seq(8);
|
||
return g.pick([
|
||
() => `t * ${q}[t >> ${K} & 7] >> ${S}`,
|
||
() => `(t * ${q}[t >> ${K} & 7] >> ${S} & 255) * (~t >> ${K - 8} & 255) >> 8`,
|
||
() => `sin(t * ${q}[t >> ${K} & 7] >> ${S}) + sin(t * ${q}[t - ${1 << (K - 1)} >> ${K} & 7] >> ${S + 1}) >> 1`,
|
||
() => `tri(t * ${g.chord()}[t >> ${g.rn(9, 10)} & 3] >> ${S}) + (t * ${g.seq(4)}[t >> ${K + 1} & 3] >> ${S + 2} & 127) >> 1`,
|
||
() => `(t * ${q}[t >> ${K} & 7] >> ${S} & 127) + (t * ${g.seq(4)}[t >> ${K + 2} & 3] >> ${S + 2} & 127)`,
|
||
() => { const sc = g.pick([[4, 5, 6, 8, 9, 10, 12, 15], [6, 8, 9, 12, 15], [4, 6, 8, 9, 12], [5, 6, 8, 10, 12, 15]]); let h = 0;
|
||
for (let k = 0; k < 8; k++) h = (h * 16 + g.pick(sc)) >>> 0; return `t * (0x${h.toString(16).toUpperCase()} >> (t >> ${K - 2} & 28) & 15) >> 1`; },
|
||
])();
|
||
},
|
||
fm: (g) => {
|
||
const R = g.k([1, 1, 2, 3], 1, 6), M = g.k([2, 3, 4, 5, 7], 2, 13), I = g.kf([0.15, 0.25, 0.35], 0.05, 1.2);
|
||
return g.pick([
|
||
() => `sin(w * ${R} + sin(w * ${M}) * fix(~t >> ${g.rn(4, 6)} & 255) / ${g.k([256, 384, 512], 150, 1000)})`,
|
||
() => `sin(w * ((t >> ${g.rn(11, 13)} & 3) + 1) + sin(w * ${M}) * ${I})`,
|
||
() => `sin(w + sin(w * ${M} + sin(w * ${g.k([2, 3, 5], 2, 11)}) * ${g.kf([0.1, 0.2], 0.05, 0.8)}) * fix(~t >> 5 & 255) / ${g.k([400, 600], 200, 1200)})`,
|
||
() => `(sin(w) + sin(w * ${g.k([2, 3], 2, 9)}) / 2 + sin(w * ${g.k([4, 5, 6], 3, 15)}) / 3) * fix(~t >> ${g.rn(4, 5)} & 255) / 400`,
|
||
() => `sin(w * ${R}) * sin(w * ((t >> ${g.rn(11, 13)} & 7) + ${M}) + sin(w) * ${I})`,
|
||
() => `sin(w * ("${g.pick(["1235", "1234", "2345", "1246", "1358"])}"[t >> ${g.rn(11, 13)} & 3] & 15) + sin(w * ${M}) * ${I})`,
|
||
])();
|
||
},
|
||
glitch: (g) => {
|
||
const K = g.rn(11, 13), T = "(" + g.pick([
|
||
() => `(t >> ${K} << ${K} | t & ${(1 << g.rn(8, 10)) - 1})`, /* a slice stuttered */
|
||
() => `((rnd(t >> ${K}) & ${0x3F << 10}) + (t & ${(1 << g.rn(9, 11)) - 1}))`, /* grains, anywhere */
|
||
() => `(t ^ (t >> ${K} & 1) * ${(1 << K) - 1})`, /* slices reversed */
|
||
() => `t % (${g.k([700, 1100, 1500], 300, 3000)} + (t >> ${K} & 3) * ${g.k([400, 600], 100, 900)})`, /* chopped */
|
||
() => `(t >> ${g.rn(3, 5)} << ${g.rn(3, 5)} | t >> ${K} & ${g.k([255, 127], 31, 511)})`, /* held, a rate down */
|
||
])() + ")";
|
||
const base = g.pick([
|
||
() => `${T} * (${T} >> ${g.rn(9, 11)} & ${g.k([5, 7, 13, 46], 3, 63)})`,
|
||
() => `${T} * ${g.k([3, 5, 7], 3, 17)} & ${T} >> ${g.rn(5, 8)}`,
|
||
() => `${T} * ${g.seq(4)}[${T} >> ${g.rn(10, 12)} & 3] >> ${g.rn(3, 5)}`,
|
||
() => `(${T} >> ${g.rn(4, 6)} | ${T} >> ${g.rn(6, 9)}) * ${g.k([3, 5, 10], 2, 30)}`,
|
||
])();
|
||
return g.pick([() => base, () => `(${base}) & ${g.k([0xF0, 0xE0, 0xC0], 0x81, 0xFE)}`, () => `(${base}) >> ${g.rn(5, 6)} << ${g.rn(5, 6)}`])();
|
||
},
|
||
drone: (g) => {
|
||
const d = () => MG_FIX(1 + (g.odd() ? g.u() * 0.03 : g.pick([0.002, 0.003, 0.004, 0.006, 0.009])) * (g.r() & 1 ? 1 : -1));
|
||
const iv = () => MG_FIX(g.pick([0.5, 1.5, 2, 1.25, 1.333, 3, 0.75]) * (1 + (g.u() * 0.012 - 0.006)) + (g.odd() ? g.u() * 0.2 : 0));
|
||
const L = g.rn(7, 9), F = () => g.pick(["sin", "sin", "tri", "saw", "sqr"]);
|
||
return g.pick([
|
||
() => `(saw(w) + saw(w * ${d()}) + saw(w * ${d()})) / 4`,
|
||
() => `(${F()}(w) + ${F()}(w * ${d()}) + ${F()}(w * ${iv()})) / ${g.k([3, 4], 3, 6)}`,
|
||
() => `(sin(w) + sin(w * ${d()}) + sin(w * ${iv()}) + sin(w * ${iv()})) / 4`,
|
||
() => `${F()}(w * ${d()} + sin(w * ${g.k([2, 3], 2, 7)}) * fix(sin(t >> ${L})) / ${g.k([300, 400], 150, 900)})`,
|
||
() => `tri(w) * 0.5 + sin(w * ${d()} * 2 + tri(w * 0.5) * fix(sin(t >> ${L})) / 600) * 0.4`,
|
||
() => `(t * ${g.k([2, 3, 4], 2, 7)} & 255) + (t * ${g.rn(514, 520) + 256 * g.rn(0, 2)} >> 8 & 255) >> 1`,
|
||
() => `(${F()}(w * 0.5) + ${F()}(w * ${d()}) + ${F()}(w * ${iv()})) * (fix(sin(t >> ${L})) / 1024 + 0.1)`,
|
||
() => `(${F()}(w * 0.5) + ${F()}(w * ${iv()})) * (0.3 + fix(sin(t >> ${L})) / ${g.k([1024, 768], 512, 2048)})`,
|
||
() => `${F()}(w + fix(rnd(t >> ${g.rn(5, 7)}) & 255) / ${g.k([2048, 4096], 1024, 8192)}) * 0.6 + ${F()}(w * ${d()}) * 0.3`,
|
||
])();
|
||
},
|
||
rhythm: (g) => {
|
||
const B = g.rn(11, 12), c0 = g.k([1000, 1200, 1400, 1700, 2000], 600, 3000), kc = Math.round(c0 * c0 * g.rn(B === 12 ? 4 : 7, B === 12 ? 7 : 11));
|
||
const kick = `(sin(${kc} / ((t & ${(1 << B) - 1}) + ${c0})) * (~t >> ${B - 8} & 255) >> ${g.pick([8, 9, 9])})`;
|
||
const hat = `((rnd(t * ${g.rn(1, 60) * 2 + 1}) & 255 >> (t >> ${B - g.rn(5, 7)} & 15)) >> ${g.rn(2, 3)})`;
|
||
const pat = () => g.k([0x93, 0xB5, 0x89, 0xA9, 0x95, 0xD5, 0x8B, 0xAD], 0x81, 0xFF);
|
||
return g.pick([
|
||
() => `${kick} + ${hat}`,
|
||
() => `(${pat()} >> (t >> ${B} & 7) & 1 ? ${kick} : 0) + ${hat}`,
|
||
() => `${kick} + (rnd(t) & (t >> ${B} & 1 ? ~t >> ${B - 8} & 255 : 0)) / ${g.rn(2, 4)}`,
|
||
() => `${kick} + (t * ${g.seq(4)}[t >> ${B + 2} & 3] >> ${g.rn(5, 6)} & (~t >> ${B - 8} & 127))`,
|
||
() => `(t * ${g.seq(4)}[t >> ${B - 2} & 3] >> ${g.rn(3, 5)} & 255) * (~t >> ${B - 10} & 63) >> 6 | ${hat}`,
|
||
() => `(${pat()} >> (t >> ${B - 1} & 7) & 1) * (t * ${g.k([3, 5], 2, 9)} >> ${g.rn(1, 3)} & ~t >> ${B - 9} & 255)`,
|
||
() => `(${pat()} >> (t >> ${B - 1} & 7) & 1 ? ${kick} : 0) + (rnd(t >> ${g.rn(0, 2)}) & (${pat()} >> (t >> ${B - 2} & 7) & 1 ? ~t >> ${B - 10} & 127 : 0))`,
|
||
() => `(${pat()} >> (t >> ${B - 2} & 7) & 1) * (sin(t * ${g.k([3, 5, 7], 2, 11)} >> 1) & ~t >> ${B - 10} & 255) + ${hat}`,
|
||
])();
|
||
},
|
||
chip: (g) => {
|
||
const A = g.rn(6, 8), S = g.rn(2, 4), K = g.rn(11, 12);
|
||
return g.pick([
|
||
() => `(t * ${g.chord()}[t >> ${A} & 3] >> ${S} & 255) < ${g.pick([128, 64, `(t >> ${g.rn(5, 7)} & 255)`])} ? ${g.k([200, 180], 140, 250)} : ${g.k([56, 70], 10, 100)}`,
|
||
() => `(t * ${g.seq(8)}[t >> ${K} & 7] >> ${S} & 128) + tri(t * ${g.seq(4)}[t >> ${K + 2} & 3] >> ${S + 2}) >> 1`,
|
||
() => `(t * ${g.ka([3, 4, 6], 2, 9)} >> ${S} & 64) + (t * ${g.seq(8)}[t >> ${K} & 7] >> ${S} & 64) + (t * ${g.chord()}[t >> ${A} & 3] >> ${S + 1} & 64)`,
|
||
() => `(t * ${g.chord()}[t >> ${A} & 3] >> ${S} & 128) + (rnd(t >> 2) & ~t >> ${K - 8} & ${g.k([63, 127], 15, 255)})`,
|
||
() => `(t * ${g.seq(8)}[t >> ${K} & 7] >> ${S} & 255) > (t >> ${g.rn(3, 6)} & 255) ? ~t >> ${K - 8} & 255 : 0`,
|
||
])();
|
||
},
|
||
};
|
||
/* a t (or w) outside the strings, one of them chosen (all: every one), replaced by rep (which may hold t) */
|
||
function mgSub(g, src, name, rep, all) {
|
||
const parts = src.split(/("[^"]*")/), at = [];
|
||
parts.forEach((p, k) => { if (k & 1) return; const re = new RegExp(`\\b${name}\\b`, "g"); let m; while ((m = re.exec(p))) at.push([k, m.index]); });
|
||
if (!at.length) return src;
|
||
for (const [k, i] of (all ? at.reverse() : [g.pick(at)])) parts[k] = parts[k].slice(0, i) + `(${typeof rep === "function" ? rep() : rep})` + parts[k].slice(i + 1);
|
||
return parts.join("");
|
||
}
|
||
/* one number outside the strings made odd: a shift a step, any other a number near it */
|
||
function mgOdd(g, src) {
|
||
const parts = src.split(/("[^"]*")/), at = [];
|
||
parts.forEach((p, k) => { if (k & 1) return; const re = /(?<![\w.])(\d+\.\d+|\d+)(?![\w.])/g; let m; while ((m = re.exec(p))) at.push([k, m.index, m[0]]); });
|
||
if (!at.length) return src;
|
||
const [k, i, s] = g.pick(at), v = Number(s);
|
||
const nv = s.includes(".") ? MG_FIX(v * (0.6 + g.u() * 0.9) + 0.001) : v <= 16 ? String(Math.max(1, v + g.pick([-2, -1, 1, 2]))) : String((Math.round(v * (0.5 + g.u() * 1.5)) | 1) >>> 0);
|
||
parts[k] = parts[k].slice(0, i) + nv + parts[k].slice(i + s.length);
|
||
return parts.join("");
|
||
}
|
||
/* t bent: another time */
|
||
const MG_INT_WARP = (g) => g.pick([() => `t ^ t >> ${g.rn(5, 10)}`, () => `t | t >> ${g.rn(3, 8)}`, () => `t % ${g.k([3000, 4096, 6000], 500, 9000)}`,
|
||
() => `t >> ${g.rn(3, 6)} << ${g.rn(3, 6)}`, () => `t * ${g.k([3, 5], 2, 13)} >> ${g.rn(1, 3)}`, () => `t + (t >> ${g.rn(7, 10)} & t >> ${g.rn(10, 13)})`,
|
||
() => `t >> ${g.rn(11, 13)} & 1 ? t : ${g.k([2048, 4096], 1000, 9000)} - t`])();
|
||
/* the rewrites: [the CHAOS from, the formula's type (fix; null either), (g, x, fam) -> x', the families whose own idiom it
|
||
is (null: every family's)]. Another family's idiom only from CHAOS 80: the families keep their own sound below */
|
||
const MG_SIE = ["sierpinski", "glitch"], MG_TON = ["melodic", "chip"];
|
||
const MG_REW = [
|
||
[0.15, false, (g, x) => `(${x}) >> (t >> ${g.rn(12, 14)} & 1)`, null],
|
||
[0.15, false, (g, x, f) => { const y = MG_FAM[MG_INT.includes(f) ? f : g.pick(MG_INT)](g); return y === x ? x : `(${x}) + (${y}) >> 1`; }, null],
|
||
[0.15, false, (g, x) => `(${x}) | t >> ${g.rn(4, 7)}`, MG_SIE],
|
||
[0.15, false, (g, x) => `((${x}) & 255) * (~t >> ${g.rn(3, 5)} & 255) >> 8`, ["melodic", "chip", "rhythm"]],
|
||
[0.15, false, (g, x) => `(${x}) + ((rnd(t) & 255 >> (t >> ${g.rn(5, 6)} & 15)) >> 2)`, ["rhythm"]],
|
||
[0.15, true, (g, x) => `(${x}) * 0.7 + sin(w * ${g.k([2, 3, 4], 2, 9)}) * ${g.kf([0.2, 0.3], 0.1, 0.5)}`, null],
|
||
[0.15, true, (g, x) => `(${x}) * fix(~t >> ${g.rn(4, 6)} & 255) / 256`, ["fm"]],
|
||
[0.15, true, (g, x, f) => { const y = MG_FAM[MG_FLT.includes(f) ? f : g.pick(MG_FLT)](g); return y === x ? x : `((${x}) + (${y})) / 2`; }, null],
|
||
[0.15, true, (g, x) => `(${x}) * 0.7 + saw(w * ${MG_FIX(1 + g.kf([0.004, 0.007], 0.001, 0.04) * (g.r() & 1 ? 1 : -1))}) * 0.3`, ["drone"]],
|
||
[0.3, false, (g, x) => mgSub(g, x, "t", MG_INT_WARP(g)), MG_SIE],
|
||
[0.3, false, (g, x) => `(${x}) & ${g.k([0xF0, 0xE0, 0xC8], 0x81, 0xFE)}`, ["glitch"]],
|
||
[0.3, false, (g, x) => `(${x}) >> ${g.rn(4, 6)} << ${g.rn(4, 6)}`, ["glitch"]],
|
||
[0.3, false, (g, x) => mgSub(g, x, "t", () => `t >> ${g.rn(12, 13)} << ${g.rn(12, 13)} | t & ${(1 << g.rn(8, 10)) - 1}`), ["glitch"]],
|
||
[0.3, false, (g, x) => `(${x}) ^ t >> ${g.rn(4, 9)}`, MG_SIE],
|
||
[0.3, false, (g, x) => `(${x}) * (t >> ${g.rn(10, 13)} & 3)`, ["sierpinski"]],
|
||
[0.3, false, (g, x) => mgSub(g, x, "t", () => `t << (t >> ${g.rn(13, 15)} & 1)`), MG_TON],
|
||
[0.3, false, (g, x) => mgSub(g, x, "t", () => `t + (sin(t >> ${g.rn(2, 4)}) >> ${g.rn(2, 4)})`), MG_TON],
|
||
[0.3, false, (g, x) => `(${x}) + (t * ${g.chord()}[t >> ${g.rn(6, 8)} & 3] >> ${g.rn(3, 4)} & 64) >> 1`, ["chip"]],
|
||
[0.3, false, (g, x) => `(${x}) | rnd(t * ${g.rn(1, 60) * 2 + 1} >> ${g.rn(1, 3)}) & ~t >> ${g.rn(3, 4)} & ${g.k([31, 63], 7, 127)}`, ["chip", "rhythm"]],
|
||
[0.3, false, (g, x) => `(${x}) * (${g.k([0xB7, 0xDB, 0xEE], 0x81, 0xFF)} >> (t >> ${g.rn(11, 12)} & 7) & 1)`, ["rhythm", "melodic"]],
|
||
[0.3, false, (g, x) => mgSub(g, x, "t", () => `t + (t >> ${g.rn(10, 11)} & 1) * ${g.k([200, 300], 50, 700)}`), ["rhythm"]],
|
||
[0.3, false, (g, x) => `(${x}) + (t * ${g.k([3, 4, 6], 2, 9)} >> ${g.rn(5, 6)} & ~t >> ${g.rn(3, 5)} & 63)`, ["rhythm"]],
|
||
[0.3, true, (g, x) => mgSub(g, x, "w", () => `w + sin(w * ${g.k([2, 3, 5], 2, 13)}) * ${g.kf([0.1, 0.2], 0.05, 0.6)}`), null],
|
||
[0.3, true, (g, x) => mgSub(g, x, "w", () => `w * ((t >> ${g.rn(11, 13)} & 3) + 1)`), ["fm"]],
|
||
[0.3, true, (g, x) => mgSub(g, x, "w", () => `w + sin(w * ${g.k([2, 3], 2, 7)}) * fix(sin(t >> ${g.rn(7, 9)})) / ${g.k([1024, 2048], 512, 4096)}`), ["drone"]],
|
||
[0.3, true, (g, x) => `sin((${x}) * ${g.kf([0.5, 0.75], 0.3, 1.6)})`, null],
|
||
[0.3, true, (g, x) => `sat((${x}) * ${g.k([2, 3], 2, 6)})`, null],
|
||
[0.3, true, (g, x) => `(${x}) * sin(w * ${g.kf([1.5, 3.0], 0.5, 7.3)})`, ["fm"]],
|
||
[0.55, false, (g, x) => `(${x}) % ${g.k([251, 193, 127], 37, 251)}`, null],
|
||
[0.55, false, (g, x) => `${g.pick(["sin", "tri"])}(${x})`, null],
|
||
[0.55, false, (g, x, f) => `t >> ${g.rn(11, 14)} & 1 ? ${x} : ${MG_FAM[g.pick(MG_INT)](g)}`, null],
|
||
[0.55, false, (g, x) => `(${x}) ${g.pick(["^", "+", "|", "-"])} (${MG_FAM[g.pick(MG_INT)](g)})`, null],
|
||
[0.55, false, (g, x) => `(${x}) + sin(t * ${g.k([3, 4, 6], 2, 9)} + sin(t * ${g.k([2, 3, 5], 2, 11)})) >> 1`, null],
|
||
[0.55, true, (g, x) => `floor((${x}) * ${g.k([4, 6], 2, 9)}) / ${g.k([4, 6], 2, 9)}`, null],
|
||
[0.55, true, (g, x) => `abs(${x}) * 2 - 1.0`, null],
|
||
[0.55, true, (g, x) => `(${x}) * 0.7 + fix(${MG_FAM[g.pick(MG_INT)](g)} & 255) / 768`, null],
|
||
[0.55, true, (g, x) => `t >> ${g.rn(11, 14)} & 1 ? ${x} : ${MG_FAM[g.pick(MG_FLT)](g)}`, null],
|
||
[0.55, null, (g, x) => mgOdd(g, x), null],
|
||
[0.55, null, (g, x) => mgOdd(g, x), null],
|
||
[0.8, false, (g, x) => mgSub(g, x, "t", () => `t * (${MG_FAM[g.pick(MG_INT)](g)} & ${g.k([7, 15], 3, 31)}) >> ${g.rn(2, 4)}`), null],
|
||
[0.8, false, (g, x) => mgSub(g, x, "t", MG_INT_WARP(g), true), null],
|
||
[0.8, false, (g, x) => `(${x}) * (${MG_FAM[g.pick(MG_INT)](g)}) >> ${g.rn(6, 8)}`, null],
|
||
[0.8, null, (g, x) => mgSub(g, x, "t", MG_INT_WARP(g)), null],
|
||
[0.8, true, (g, x) => mgSub(g, x, "w", () => `w + fix(${MG_FAM[g.pick(MG_INT)](g)} & 255) / ${g.k([512, 1024], 256, 2048)}`), null],
|
||
[0.8, true, (g, x) => `sin((${x}) * ${g.kf([0.7, 1.3], 0.4, 2.5)} + w * ${g.k([1, 2], 1, 5)})`, null],
|
||
[0.8, true, (g, x) => mgSub(g, x, "w", () => `w * fix(t >> ${g.rn(10, 12)} & 7) / 4`), null],
|
||
];
|
||
const MG_INT = MATH_FAMILIES.filter((f) => !f.fix).map((f) => f.id), MG_FLT = MATH_FAMILIES.filter((f) => f.fix).map((f) => f.id);
|
||
/* heard as the device runs it (FVM.run; FIX: w the phase, t << 11): four windows of 2048 t far apart (at C4 t moves at
|
||
~8 kHz) -> {loud (windows sounding), dc, zcr (white noise: 0.5), moves (windows unlike)} */
|
||
function mathGenHear(code, a = 5, W = 2048) {
|
||
const fix = !!(code[0] & 1), hs = new Set();
|
||
let loud = 0, dc = 0, zcr = 0;
|
||
for (const t0 of [0, 12288, 40960, 98304]) {
|
||
const xs = new Float32Array(W);
|
||
let m = 0, h = 0;
|
||
for (let i = 0; i < W; i++) {
|
||
const t = t0 + i, v = fix ? FVM.sample(code, FVM.run(code, t, (t << 11) >>> 0, a)) / 32768 : ((FVM.run(code, t, 0, a) & 255) - 127.5) / 128;
|
||
xs[i] = v; m += v; h = Math.imul(h ^ Math.round(v * 64), 16777619) >>> 0;
|
||
}
|
||
m /= W;
|
||
let s2 = 0, z = 0;
|
||
for (let i = 0; i < W; i++) { s2 += (xs[i] - m) ** 2; if (i && (xs[i] > m) !== (xs[i - 1] > m)) z++; }
|
||
if (Math.sqrt(s2 / W) > 0.04) loud++;
|
||
dc += Math.abs(m) / 4; zcr += z / W / 4; hs.add(h);
|
||
}
|
||
return { loud, dc, zcr, moves: hs.size };
|
||
}
|
||
const mgOk = (h) => h.loud >= 3 && h.dc < 0.85 && h.zcr < 0.42 && h.moves >= 2;
|
||
/* the text a formula of the device's: compiled (FVM), at most 64 bytes, a stack of 12 (FVM refuses more), no state's
|
||
or FUNC's calls, only the variables JIANT FM gives */
|
||
function mathGenValid(src) {
|
||
if (/\b(ph|lp|hp|eu|note|chord|kick|snare|hat)\s*\(/.test(src)) return null;
|
||
const names = src.replace(/"[^"]*"/g, "").match(/\b[A-Za-z_]\w*\b/g) || [];
|
||
if (names.some((n) => !/^(t|w|a|n|v|sin|cos|tri|saw|sqr|abs|min|max|floor|int|fix|rnd|sat|clip)$/.test(n) && !/^0x/i.test(n))) return null;
|
||
const c = FVM.compile(src);
|
||
return c.ok && c.code.length <= FVM.MAX && c.depth <= FVM.DEPTH ? c : null;
|
||
}
|
||
function mathGenerate(seed, opt) {
|
||
const legacy = opt == null || typeof opt !== "object", o = legacy ? {} : opt;
|
||
const chaos = Math.max(0, Math.min(100, Math.round(Number.isFinite(+o.chaos) ? +o.chaos : 40))), c = chaos / 100;
|
||
const h32 = (x) => FVM.hash(x >>> 0);
|
||
let fi = MATH_FAMILIES.findIndex((f) => f.id === o.family);
|
||
if (fi < 0) fi = h32((seed >>> 0) ^ 0xA5A5) % MATH_FAMILIES.length; /* (any: the seed's own, whatever the CHAOS) */
|
||
const fam = MATH_FAMILIES[fi].id, g = mgCtx(mathRng(h32(h32(seed >>> 0) + fi * 0x9E3779B9 + chaos * 0x85EBCA77) || 1), c);
|
||
const rew = MG_REW.map(([lv, fx, fn, fams]) => [fams && !fams.includes(fam) ? Math.max(lv, 0.8) : lv, fx, fn]).filter(([lv]) => lv <= c);
|
||
let best = null;
|
||
for (let tries = 0; tries < 24; tries++) {
|
||
let src = MG_FAM[fam](g);
|
||
let cc = mathGenValid(src);
|
||
if (!cc) continue;
|
||
const n = Math.round(c * 6 + g.u() * c * 2);
|
||
const used = new Set();
|
||
for (let i = 0, k = 0; i < n && k < n * 4; k++) {
|
||
/* (the rewrites of the formula's type, not one twice; those of the CHAOS's own height three times as likely) */
|
||
const can = [];
|
||
rew.forEach(([lv, f], j) => { if ((f === null || f === !!cc.fix) && !used.has(j)) for (let w = lv >= c - 0.3 ? 3 : 1; w--;) can.push(j); });
|
||
if (!can.length) break;
|
||
const j = g.pick(can), s2 = rew[j][2](g, src, fam), c2 = s2 !== src && mathGenValid(s2);
|
||
if (c2 && mgOk(mathGenHear(c2.code, 5, 512))) { src = s2; cc = c2; used.add(j); i++; }
|
||
}
|
||
const h = mathGenHear(cc.code), ok = mgOk(h);
|
||
if (!best || (ok && !best.ok)) best = { src, cc, ok };
|
||
if (ok) break;
|
||
}
|
||
if (!best) { const src = MATH_FAMILIES[fi].fix ? "sin(w + sin(w * 2) * fix(~t >> 5 & 255) / 512)" : "t * (t >> 11 & t >> 8 & 123 & t >> 3)"; best = { src, cc: FVM.compile(src) }; }
|
||
if (legacy) return best.src;
|
||
const fix = !!best.cc.fix;
|
||
return { src: best.src, fix, wave: fix ? 6 : 5, family: fam, chaos, bytes: best.cc.code.length, stack: best.cc.depth, toString() { return this.src; } };
|
||
}
|
||
mathGenerate.FAMILIES = MATH_FAMILIES; /* (for a page that takes only mathGenerate: JIANT Studio) */
|
||
/* how musical a formula sounds, 0..1: it changes over time (bars apart), it is neither silent nor white noise */
|
||
function mathScore(fn, a) {
|
||
const N = 8192, at = (t) => fn(t, a) & 255;
|
||
let zc = 0, mean = 0, prev = at(0);
|
||
for (let t = 1; t < N; t++) { const v = at(t); if ((v >= 128) !== (prev >= 128)) zc++; mean += v; prev = v; }
|
||
const zr = zc / N;
|
||
const blk = (t0) => { let h = 0; for (let t = 0; t < 2048; t++) h = (h + at(t0 + t) * (t + 1)) >>> 0; return h; };
|
||
const pages = new Set([0, 16384, 32768, 49152, 65536, 98304].map(blk)).size;
|
||
const moves = (pages - 1) / 5, noisy = zr > 0.35 ? 0 : 1, flat = zr < 0.002 ? 0 : 1;
|
||
return moves * noisy * flat * (1 - Math.abs(zr - 0.08));
|
||
}
|
||
/* a MATH sound's eight values (P_E0..P_E7, eng_lofi.c ENG_LOFI .edit): BYTE {CHIP, WAVE 5 (7: SYNC), ALGO, VARIANT,
|
||
MOTION, GRIT, BEND, LOOP}; FLOAT {ALGO B, WAVE 6, ALGO, VARIANT, MOTION, FEEDBK, MORPH, LOOP}. ALGO is the formula x 4 */
|
||
function mathValues(o) {
|
||
const algo = o.user ? -4 : o.f * 4; /* (V10.8.75) ALGO USER: -4, the track's own formula */
|
||
return o.wave === 6 ? [(o.algoB | 0) * 4, 6, algo, o.var | 0, o.motion | 0, o.fbk | 0, o.morph | 0, o.loop | 0]
|
||
: [o.chip ?? 2, o.sync ? 7 : 5, algo, o.var | 0, o.motion | 0, o.grit | 0, o.bend | 0, o.loop | 0];
|
||
}
|
||
/* the emulator (felucca.wasm with editor-api.h) playing it: a fresh device, track 1 made MATH as the editor's send does
|
||
(SET of G_ENGSEL: the engine and its first preset, then the eight values), the other tracks out of the mix, a note on
|
||
MIDI channel 1 held for o.gate seconds. dry: the FILTER open, no envelope or effects (the model's comparison).
|
||
ex: a new instance's exports -> {l, r} at 44.1 kHz, the device's own samples */
|
||
function mathEmuRender(ex, o) {
|
||
const ed = (a) => { new Uint8Array(ex.memory.buffer, ex.web_ed_buf(), a.length).set(a); const n = ex.web_ed(a.length);
|
||
return n ? Array.from(new Uint8Array(ex.memory.buffer, ex.web_ed_reply(), n)) : null; };
|
||
const v14 = (v) => { const u = Math.max(-8192, Math.min(8191, v | 0)) + 8192; return [u & 127, u >> 7]; };
|
||
ex._initialize(); ex.web_nor_erase(); ex.web_master(o.master ?? 700); ex.web_seed(1); ex.web_boot();
|
||
for (let i = 0; i < 12; i++) ex.web_render(1024);
|
||
ed([27, 0]); ed([3, 1, 20, ...v14(3)]);
|
||
const info = ed([1]), pe0 = info ? info[info.indexOf(0) + 5] : 115; /* (INFO: version, 0, NENGINES P_COUNT G_COUNT NSTEP P_E0) */
|
||
const dry = o.dry ? { 113: 127, 114: 0, 33: 0, 34: 0, 35: 0, 36: 0, 1: 0, 3: 127, 5: 0, 6: 0, 7: 0, 51: 0, 54: 0, 57: 0, 60: 0, 13: 0, 14: 0, 15: 0, 16: 0 } : {};
|
||
for (const [id, v] of Object.entries(dry)) ed([31, 0, +id, ...v14(v)]);
|
||
const fr = o.code ? ed([100, 0, 1, ...FVM.pack7(o.code)]) : null; /* (V10.8.75) MATH USER: track 1's formula, the device's
|
||
VM (null: a firmware without FORMULA) */
|
||
mathValues(o).forEach((v, k) => ed([31, 0, pe0 + k, ...v14(v)]));
|
||
ex.web_mix_skip(0x3E);
|
||
for (let i = 0; i < 8; i++) ex.web_render(1024);
|
||
const secs = o.secs || 2, n = Math.round(secs * 44100), gate = Math.round((o.gate ?? secs * 0.8) * 44100);
|
||
const l = new Float32Array(n), r = new Float32Array(n);
|
||
ex.web_midi(0x90, o.note ?? 60, o.vel ?? 100);
|
||
for (let k = 0; k < n; k += 1024) {
|
||
const m = Math.min(1024, n - k);
|
||
if (k <= gate && gate < k + m) ex.web_midi(0x80, o.note ?? 60, 0);
|
||
ex.web_render(m);
|
||
l.set(new Float32Array(ex.memory.buffer, ex.web_out_l(), m), k);
|
||
r.set(new Float32Array(ex.memory.buffer, ex.web_out_r(), m), k);
|
||
}
|
||
return { l, r, formula: !!(fr && fr[1] === 0) };
|
||
}
|
||
/*MATH-END*/
|
||
|
||
|
||
/* ===================================================================== UI === */
|
||
if (typeof document !== "undefined") (() => {
|
||
const $ = (id) => document.getElementById(id);
|
||
const el = (tag, attrs = {}, ...kids) => {
|
||
const e = document.createElement(tag);
|
||
for (const [k, v] of Object.entries(attrs)) {
|
||
if (k === "text") e.textContent = v;
|
||
else if (k === "ic") continue;
|
||
else if (k.startsWith("on")) e.addEventListener(k.slice(2), v);
|
||
else if (v !== false && v != null) e.setAttribute(k, v === true ? "" : v);
|
||
}
|
||
for (const k of kids) e.append(k);
|
||
if (attrs.ic) e.prepend(icon(attrs.ic));
|
||
return e;
|
||
};
|
||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||
|
||
/* ---------------------------------------------------------------- icons --- */
|
||
/* Fukiai glyphs by their names in hugelton-plugin-rules lib/include/hugelton/Glyphs.h */
|
||
const GLYPH = {
|
||
port_usb_c: 0xEA3F, symbol_audio: 0xEA40, symbol_download: 0xEAD4, symbol_upload: 0xEAD5,
|
||
symbol_folder: 0xEAB8, symbol_folder_open: 0xEAB9, port_disk: 0xEAB3, symbol_trash: 0xEAC1,
|
||
control_arrow_loop: 0xEAD6, note_eight: 0xEAEF, symbol_waves: 0xEAE6, function_env_adsr_exp: 0xEA12,
|
||
ui_knob: 0xEA70, symbol_keyboard: 0xEABC, symbol_effector: 0xEAB7, symbol_echo: 0xEAB5, symbol_spring: 0xEAD1,
|
||
symbol_tuning: 0xEAA7, control_arrow_up_down: 0xEACF, symbol_grid: 0xEABA, symbol_cog: 0xEA46,
|
||
function_filter_lpf_peak: 0xEAA0, ui_slider_vertical: 0xEA73, symbol_books: 0xEADC, control_rec_f: 0xEA09, control_stop_f: 0xEA0F,
|
||
symbol_pan: 0xEA53, control_speaker_mute: 0xEAEB,
|
||
waveform_sine: 0xEA85, waveform_triangle_ac: 0xEA89, waveform_sawtooth_ac: 0xEA81, waveform_square: 0xEA87,
|
||
waveform_pulse_quarter: 0xEA7F, waveform_pulse_eighth: 0xEA7B, waveform_noise_step: 0xEA79,
|
||
waveform_noise_white: 0xEA7A, waveform_harmonic: 0xEAC5,
|
||
};
|
||
/* section headings (LAYOUT titles) and page titles */
|
||
const HEAD_IC = { ENV: "function_env_adsr_exp", LFO: "waveform_sine", MOD: "symbol_waves", EDIT: "ui_knob", VOICE: "symbol_keyboard",
|
||
FX: "symbol_effector", SCL: "symbol_tuning", ARP: "control_arrow_up_down", "SEQ PATTERN": "symbol_grid",
|
||
GLOBAL: "symbol_cog", INSTRUMENT: "symbol_keyboard", FILTER: "function_filter_lpf_peak" };
|
||
const PAGE_IC = { FLT: "function_filter_lpf_peak", FILT: "function_filter_lpf_peak", DLY: "symbol_echo", REVERB: "symbol_spring", CHORUS: "symbol_waves",
|
||
SLICER: "symbol_grid", CHORD: "symbol_keyboard" };
|
||
/* WAVE / WAVE2 choices; phase-distortion shapes without a close glyph (SPLS, RSAW, RTRI, RTRP) get none */
|
||
const WAVE_IC = { SIN: "waveform_sine", TRI: "waveform_triangle_ac", SAW: "waveform_sawtooth_ac", SQR: "waveform_square",
|
||
PLS: "waveform_pulse_quarter", PWM: "waveform_pulse_eighth", "S&H": "waveform_noise_step", NOIS: "waveform_noise_white",
|
||
DSIN: "waveform_harmonic" };
|
||
/* options can hold an icon only where the browser draws the picker itself; a native menu would show a box */
|
||
const RICH_SELECT = typeof CSS !== "undefined" && CSS.supports && CSS.supports("appearance", "base-select");
|
||
function icon(name) { return el("span", { class: "ic", "aria-hidden": "true", text: String.fromCharCode(GLYPH[name]) }); }
|
||
function setLabel(e, txt) { e.replaceChildren(...(e.dataset.ic ? [icon(e.dataset.ic)] : []), txt); }
|
||
/* icons stay hidden (html:not(.fk)) until the face has loaded; on failure, or from file://, words only */
|
||
(async () => {
|
||
try {
|
||
const probe = "1em Fukiai", ch = String.fromCharCode(GLYPH.waveform_sine);
|
||
const faces = await document.fonts.load(probe, ch);
|
||
if (faces.length && faces.every((f) => f.status === "loaded") && document.fonts.check(probe, ch)) document.documentElement.classList.add("fk");
|
||
} catch (e) { /* no icons */ }
|
||
})();
|
||
|
||
const TEXT = {
|
||
ja: {
|
||
tabFm6: "6-OP FM", fm6Help: "FM6 エンジンの音色(6 オペレーター)をまるごと編集します。本体のノブはこの音色の上にかかるマクロです。SysEx を読み込み、音色を選んで編集し、トラックへ送るとすぐ鳴ります。トラックの音色はひとつで、読み込んだものがそのトラックの音色になります(SLOT は OWN)。",
|
||
fm6Source: "音色の出し入れ", fm6ReadBtn: "トラックから読む", fm6SendBtn: "トラックへ送る", fm6Live: "編集しながら送る",
|
||
fm6Import: "SysEx を読み込む", fm6Export: "SysEx に書き出し",
|
||
fm6Init: "初期音色", fm6Voice: "ボイス", fm6Ops: "オペレーター", fm6Carriers: "キャリア", fm6Feedback: "フィードバック",
|
||
fm6PitchEg: "ピッチ EG", fm6Freq: "周波数",
|
||
fm6Legend: "R1〜R4 / L1〜L4: EG のレートとレベル、BP LD RD LC RC: キーボードレベルスケーリング、RS: レートスケーリング、AMS: LFO 音量変調、KVS: ベロシティ、OL: 出力レベル、MODE: 比率 / 固定、FC FF: 周波数(粗・細)、DET: デチューン(7 が中央)。● はキャリア。",
|
||
midiPorts: "MIDI ポート(自動接続できない場合)", midiPortHelp: "ブラウザが認識したポートです。入力と出力が両方必要です。空の場合は MIDI ポートが認識されていません。SMK-37 は FM-1 と同じく USB で接続します。JIANT FM アプリ(スタンドアロン)は設定で MIDI 入力と出力を選び、その相手のポート(仮想 MIDI ケーブルなど)をここで選んでください。MPC Sample のアプリはまだエディターに応答しません。", midiInput: "入力", midiOutput: "出力",
|
||
fm6BankSend: "本体のボイスバンクへ送る (B1–B32)", fm6BankSent: "ボイスバンクを送りました:", fm6BankFail: "ボイスバンクを送れませんでした (rc ", fm6BankNow: "本体のボイスバンク:", fm6BankNone: "なし",
|
||
fm6Pick: "読み込んだファイルの音色(押すと編集へ):", fm6Picked: "編集中:", fm6Sent: "トラックへ送りました:", fm6Read: "トラックから読みました",
|
||
fm6Loaded: "読み込みました", fm6BadSum: "チェックサム不一致あり",
|
||
fm6Keep: "残すには、トラックへ送ってから本体でユーザープリセット(SAVE)かプロジェクトに保存してください。",
|
||
fm6Short: "途中で切れたデータあり", fm6Skipped: "音色以外の {x} 件は無視",
|
||
fm6NoVoice: "6 オペレーター FM の音色が見つかりません(32 音色バンクか 1 音色の SysEx が必要です)",
|
||
fm6NotSysex: "SysEx ファイルではありません(6 オペレーター FM の 32 音色バンクか 1 音色の SysEx が必要です)",
|
||
fm6Is4op: "4 オペレーター FM の音色データです。FM6 は 6 オペレーターの音色だけ読み込めます",
|
||
fm6OtherBlocks: "6 オペレーターのファイル形式ですが、音色ではないデータ(パフォーマンスや補助データなど)だけでした",
|
||
fm6OtherMaker: "別のメーカーの SysEx です", fm6Universal: "音色ではない汎用 SysEx です",
|
||
fm6Factories: "ファクトリー音色",
|
||
fm6NeedDevice: "FM-1 を接続すると 6-OP FM の音色を編集してトラックへ送れます。",
|
||
fm6NoFw: "このファームウェアには 6-OP FM(FM6)がありません。Felucca 1.0 以降に更新すると使えます。",
|
||
motion: "オートメーション", motionOn: "再生", motionClear: "オートメーションを消去", motionConfirm: "選択トラックのオートメーションを消しますか?", chance: "確率 %", ratchet: "ラチェット", motionStep: "ステップ", motionParam: "パラメーター", motionValue: "値",
|
||
backupTitle: "全体バックアップ", backupExport: "バックアップ保存", backupImport: "バックアップ復元", backupHelp: "現在の曲・A〜D・音色バンク・設定を、このパソコンへ保存。", backupOld: "全体バックアップには対応版への更新が必要です。", backupConfirm: "全体バックアップを復元しますか? 現在の曲と保存データを置き換えます。USBを抜かないでください。", backupWorking: "バックアップ処理中 ", backupDone: "バックアップを保存しました", backupRestored: "全体バックアップを復元しました",
|
||
deviceDisplay: "本体の画面",
|
||
deviceDisplayHelp: "FM-1 の画面に反映し、保存します。再生中の変更は停止後に保存されます。",
|
||
devicePresets: "本体のプリセット",
|
||
deviceFavHelp: "お気に入りと表示フィルターは FM-1 と同期します。パソコンのライブラリの音色は、本体のユーザースロットに保存してから登録してください。",
|
||
deviceList: "表示",
|
||
deviceAll: "すべてのプリセット",
|
||
deviceFavorites: "お気に入りのみ",
|
||
deviceEmpty: "お気に入りはまだありません。「すべてのプリセット」から追加してください。",
|
||
deviceTheme: "テーマ",
|
||
deviceFont: "フォント",
|
||
deviceMonitor: "MIDI モニター",
|
||
deviceRegular: "標準",
|
||
deviceBold: "太字",
|
||
deviceOff: "オフ",
|
||
deviceEvents: "イベント",
|
||
deviceNotes: "保持中の音・和音",
|
||
deviceStar: "お気に入りに追加",
|
||
deviceUnstar: "お気に入りから削除",
|
||
deviceUnsaved: "反映されましたが、本体に保存できませんでした。もう一度お試しください。",
|
||
deviceRejected: "本体がこの設定を受け付けませんでした。",
|
||
devicePending: "反映しました。再生を停止すると保存されます。",
|
||
|
||
other: "English", connect: "接続", disconnect: "切断", mock: "モック(実機なし)",
|
||
tabMath: "MATH", mathHelp: "MATH の数式。BYTE はバイトビート(時間 t の式、その下位 8 ビットが音)、FLOAT はその正弦版です。本体の 48 + 48 から選ぶか、自作の数式を書いて(JIANT BYTE と同じ言語: t w a n v、sin cos tri saw sqr abs min max floor int fix rnd sat clip、\"...\"[i] の表)、試聴、生成、トラックへ送信できます。自作の数式は V10.8.75 以降の本体で MATH USER(ALGO USER)として演奏されます: 64 バイトまで。",
|
||
mathGrammarT: "文法(ファームウェアと同じ)", mathGrammar: "t: 時間。ノート 1 周期に 31 ステップ(C4 で約 8 kHz)。MOTION は遅いビットの速さ(0: 1/16、64: そのまま、128..255 SYNC: 小節に同期)、LOOP は t を窓に閉じ込め、VARIANT は t を変形(方法: VAR / 16、量: VAR % 16)し a = 1 + VAR / 8(1..16)を与え、BEND は t を折り返します。\n数値: 123、0x1F(u は任意)。演算子は C と同じで、すべて符号なし 32 ビット: ( )、単項 - ~ !、* / %、+ -、<< >>、< <= > >=、== !=、&、^、|、&&、||、c ? x : y。比較と ! は 0 か 1。下位 8 ビットが鳴ります(CHIP: 8、4、1 ビット)。\n例(本体): t * (42 & t >> 10) · t * (0xCA98 >> (t >> 9 & 14) & 15) | t >> 8 · (t >> 13 | t % 24) & (t >> 7 | t % 19)。",
|
||
mathOwn: "— 自作 —", mathFloatRo: "FLOAT の数式はファームウェアの C(固定小数点の正弦)です。試聴と送信のみ。編集は BYTE で。",
|
||
mathErr: "エラー:", mathAt: "位置", mathIsStock: "本体の数式: 送信できます", mathOwnOk: "自作の数式(MATH USER)", mathTerms: "項",
|
||
mathPlay: "再生", mathStop: "停止", mathLoop: "ループ", mathRendering: "計算中…", mathNoEmu: "エミュレーターに届きません: FLOAT は試聴できません。",
|
||
mathFixFirst: "先に数式を直してください。", mathSrcEmu: "試聴: エミュレーターのサンプル(本体のコード)", mathSrcModel: "試聴: MATH の BYTE ボイスのモデル(自作の数式)",
|
||
mathSeed: "シード", mathFamily: "ファミリー", mathChaos: "カオス", mathAny: "おまかせ", mathGen: "数式を生成", mathGenPatch: "音色を生成", mathGenerated: "生成しました: シード",
|
||
mathSend: "トラックへ送る", mathRead: "トラックから読む", mathConnect: "送るには FM-1(またはエミュレーター)を接続してください。",
|
||
mathOwnNoSend: "送信不可: この本体のファームウェアは自作の数式(V10.8.75 の MATH USER)に未対応です。", mathUserSend: "自作の数式: トラックの数式として送り、ALGO を USER にします。", mathUserRefused: "本体が数式を拒否しました:", mathReadUser: "読みました(数式のテキストはこのブラウザにありません):", mathSent: "送信しました:", mathSentClamped: "送信しました(本体が一部の値を補正):",
|
||
mathNotMath: "MATH トラックではありません:", mathReadOk: "読みました:",
|
||
tabRoll: "ピアノロール", rollFit: "全体表示", rollUndo: "元に戻す", rollReading: "ステップを読み込み中", rollGrid: "DRUM グリッド", rollNotes: "ノート",
|
||
rollHelp: "空いたマスをタップするとノートを追加します(DRUM トラックではヒット)。ノートをタップすると選択、もう一度タップで削除。ノートを上下にドラッグで音程、右へドラッグで長さ(TIE ステップ)。それ以外のドラッグでスクロール、ピンチ(または Ctrl + ホイール)でズーム。上の帯で小節へ移動、下のレーンでベロシティ・チャンス・ラチェットを描きます。キー: 矢印、Delete、A アクセント、S スライド、Ctrl+Z 元に戻す。変更はすぐにトラックへ書き込まれます。",
|
||
rollPick: "ステップを選んでください(ノート、ヒット、ステップ番号をタップ)。", rollStep: "ステップ", rollPastLen: "LEN の外", rollTapToAdd: "ノートなし: ロールをタップして追加。",
|
||
rollClear: "ステップを消去", rollNoHit: "ヒットなし", rollLocks: "ロックとオートメーション", rollLockParam: "パラメーター", rollAddLock: "ロックを追加",
|
||
rollNoLocks: "このファームウェアはオートメーションのみ(パラメーターロックなし)。", rollChordFull: "1 ステップは最大 4 ノートです。",
|
||
rollNoUndo: "このトラックで元に戻せる操作はありません。", rollFull: "モーションの 64 件を使い切りました", rollRefused: "本体が拒否しました",
|
||
rollMicroMissing: "MICRO、ステップのコンポーネント(COMP 1 / 2、EVERY、LEN、N:M)、EUCLID 自体の設定は本体に残りますが、エディタープロトコルでは読み書きできません。ここでステップを書いてもそれらは変わりません。",
|
||
rollEuHelp: "ユークリッドリズム(本体と同じ式): HITS を STEPS に均等に配置し ROTATE で回転、トラックの LEN 全体に繰り返します。DRUM トラックでは ALL で DENSITY 1..8 のキット、またはレーンを選択。プレビューで枠表示、書き込みで反映(元に戻す 1 回)。",
|
||
rollPreview: "プレビュー", rollWriteSteps: "ステップを書き込む",
|
||
rollMsHelp: "トラックのモジュレーションシーケンス(MOD > SEQ): 16 レベル。LEN・DIV・SLEW はサウンドタブ。レベルを描くと、マトリクスのソース STEP になります。",
|
||
rollSlcHelp: "SLICER バスのピッチステップ(グローバル、SLICER を通る全トラック): -24..24 半音の 16 ステップ。LEN はサウンドタブのグローバル。",
|
||
sound: "音色", engine: "エンジン", presets: "プリセット", initSound: "音色を初期化",
|
||
track: "トラック",
|
||
saveFile: "ファイルに保存", loadFile: "ファイルを読み込む", projects: "プロジェクト",
|
||
load: "読込", save: "保存", used: "使用中", empty: "空", unknown: "—",
|
||
steps: "ステップ", reload: "再読み込み", clearSeq: "シーケンスを消去",
|
||
notesHelp: "ノートは C4 E4 G4 のように入力(最大 4 音、C4 = 60)。ヒットは DRUM のレーン名(KICK >SNARE HATCL、> はアクセント)。",
|
||
notes: "ノート", hits: "ヒット", time: "タイム", acc: "アクセント", slide: "スライド", vel: "ベロシティ",
|
||
foot: "Chrome か Edge で使えます。", iconsCredit: "アイコン: Fukiai(MIT)Hügelton Instruments",
|
||
nomidi: "このブラウザでは使えません。Chrome か Edge で開いてください。",
|
||
denied: "MIDI(SysEx)の使用が許可されませんでした。",
|
||
nodevice: "JIANT が見つかりません。USB で接続して、もう一度押してください。", portsSeen: "見えている MIDI ポート:", portsNone: "MIDI ポートがありません。データ用ケーブルか、MENU > USB が CONSOLE か確認してください",
|
||
connecting: "接続中", reading: "読み込み中 ", steploading: "ステップを読み込み中 ",
|
||
ready: "接続しました", disconnected: "切断されました", lost: "JIANT が外されました", instbusy: "別のタブでインストーラーが書き込み中です。終わってから接続してください。",
|
||
noreply: "応答がありません", error: "エラー: ", busy: "処理中",
|
||
screenBtn: "画面", screenTitle: "画面", screenSharp: "シャープ", screenFull: "全画面", screenClose: "閉じる",
|
||
screenWait: "FM-1 の画面を待っています…", screenRate: " KB/s", screenNo: "このファームウェアには画面ミラーがありません(JIANT FM を更新してください)",
|
||
screenHelp: "スマートフォンで大きく見るには: このエディターをスマートフォンの Chrome で開き、FM-1 を USB-C(OTG)でつなぎます。",
|
||
applying: "書き込み中 ", applied: "読み込みました", badfile: "ファイルを読み込めません: ",
|
||
savedSlot: "保存しました: スロット ", loadedSlot: "読み込みました: スロット ", emptySlot: "空のスロットです: ",
|
||
confirmSave: "スロット {n} に上書き保存しますか?", confirmLoad: "スロット {n} を読み込みますか? すべてのトラックの音色とシーケンスが置き換わります(元に戻せません)。",
|
||
confirmClear: "シーケンスを全部消しますか?", confirmInit: "音色を初期化しますか? シーケンスはそのままです(本体の SAVE 長押しで元に戻せます)。",
|
||
erase: "消去", remove: "外す",
|
||
layout: "(ファームウェアのパラメーター数が想定と違うため、簡易表示にしています)",
|
||
ctlHelp: "スライダーはクリックしてからホイールか矢印キーで微調整(Shift で 10 ずつ)、ダブルクリックで初期値。",
|
||
lyricT: "歌詞(VOICE WORDS)",
|
||
lyricHelp: "VOICE トラックの歌詞(63 文字まで)。EDIT > WORDS の LANG で言語(ES / EN / JA、日本語はローマ字)、LYRIC を TEXT に。音符ごとに次の音節を歌い、「-」は母音をもう一音のばす。",
|
||
lyricSend: "送信",
|
||
lyricLang: "LANG",
|
||
lyricSrc: "LYRIC",
|
||
lyricSent: "歌詞を送りました",
|
||
live: "● リアルタイム", polling: "○ ポーリング(古いファームウェア)",
|
||
library: "ライブラリ", libSearch: "名前・タグで検索", allEngines: "全エンジン", allTags: "全タグ",
|
||
sortModified: "更新順", sortCreated: "作成順", sortName: "名前順", sortEngine: "エンジン順",
|
||
name: "名前", tagsCol: "タグ", date: "更新",
|
||
audition: "試聴", toSlot: "本体スロットへ", rename: "名前変更", tags: "タグ", duplicate: "複製", delete: "削除",
|
||
exportPatch: "書き出し", saveToLib: "今の音色をライブラリへ", import: "読み込み", exportLib: "ライブラリを書き出し",
|
||
factoryToLib: "ライブラリへコピー", libEmpty: "ライブラリは空です。「今の音色をライブラリへ」やファクトリープリセットのコピー、本体スロットからの取り込み、ファイルの読み込みで追加できます。",
|
||
noMatch: "該当なし", noLibDB: "(ブラウザに保存できません。再読み込みで消えます)",
|
||
bank: "本体のユーザープリセット", bankLoad: "読込", bankStore: "今の音色を保存", bankGet: "ライブラリへ",
|
||
exportBank: "バンクを書き出し", dndHelp: "ライブラリとスロットの間はドラッグでもコピーできます。",
|
||
confirmOverwrite: "スロット {n}({name})を上書きしますか?", confirmEraseSlot: "スロット {n}({name})を消去しますか?",
|
||
confirmDelete: "「{name}」をライブラリから削除しますか?",
|
||
promptName: "名前(本体では英数字 12 文字まで)", promptTags: "タグ(カンマ区切り)",
|
||
promptNameAuto: "名前(英数字 12 文字まで。空なら本体が自動で付けます)",
|
||
auditioning: "試聴の準備中 ", auditioned: "試聴中(音色だけ。シーケンスはそのまま。本体の SAVE 長押しで元の音色に戻せます): ",
|
||
savedLib: "ライブラリに保存しました: ", copiedLib: "ライブラリにコピーしました: ", imported: "読み込みました: ",
|
||
skippedN: " 件(読めないもの {n} 件)", patchesN: " 件",
|
||
putDone: "本体に書き込みました: スロット ", storedSlot: "本体に保存しました: スロット ", erasedSlot: "消去しました: スロット ",
|
||
loadedUser: "音色を読み込みました(シーケンスはそのまま。パターンは本体の SEQ > PHRASES から。SAVE 長押しで元に戻せます): ", reloaded: "本体で音色が変わったので読み直しました", readingBank: "スロットを読み込み中",
|
||
badEngine: "このファームウェアにないエンジンです: ", flashFail: "書き込みに失敗しました(rc {rc})",
|
||
installer: "JIANT インストーラー",
|
||
tabSeq: "シーケンサー", tabTracks: "トラック", tabSettings: "設定",
|
||
needDevice: "FM-1 を接続すると編集できます。",
|
||
bankConnect: "FM-1 を接続すると本体のユーザープリセットも扱えます。", bankNone: "このファームウェアにはユーザープリセットがありません。",
|
||
mixer: "ミキサー", mixHelp: "本体の MIXER ページと同じトラック。フェーダーはレベル。パンはどのトラックも選択を変えずに書き込みます(0.8 のファームウェアでは一瞬そのトラックを選びます)。REC は本体での録音待機の表示です。",
|
||
level: "レベル", pan: "パン", mute: "ミュート", rec: "REC", selectTrack: "選択", selectedTrack: "選択中",
|
||
projHelp: "プロジェクトは本体の状態をまとめて保存します: 全トラックの音色とパターン、曲の並び順、選択中のトラック、グローバル設定。",
|
||
slot: "スロット", songTitle: "ソング", songHelp: "保存スロットのパターンと繰り返す回数を順に並べます。音色は現在のまま。並び順を残すには、上のプロジェクトを保存してください。切替はトラック1のパターン終端、曲末で停止します。", songAdd: "行を追加", songRemove: "最後の行を削除", songPlay: "先頭から再生", songStop: "停止", songReps: "回", songEmpty: "行を追加してください", songBusy: "停止してから編集してください", songInvalid: "スロットと回数を確認してください", songPlaying: "再生中の行", songSaved: "並び順を変更しました。プロジェクトを保存すると残せます。",
|
||
system: "システム", deviceL: "デバイス", firmware: "ファームウェア", sync: "同期", tracksN: "トラック", stepsN: "ステップ数", enginesL: "エンジン",
|
||
userBank: "ユーザープリセット", none: "なし",
|
||
},
|
||
en: {
|
||
tabFm6: "6-OP FM", fm6Help: "Edit the whole patch of the FM6 engine (six operators). The device's knobs are macros on top of it. Import a SysEx file, pick a voice, edit it and send it to a track: it plays at once. A track has one patch: whatever you load becomes it (SLOT shows OWN).",
|
||
fm6Source: "Patches in and out", fm6ReadBtn: "Read from track", fm6SendBtn: "Send to track", fm6Live: "Send while editing",
|
||
fm6Import: "Import SysEx", fm6Export: "Export SysEx",
|
||
fm6Init: "Init voice", fm6Voice: "Voice", fm6Ops: "Operators", fm6Carriers: "carriers", fm6Feedback: "feedback",
|
||
fm6PitchEg: "Pitch EG", fm6Freq: "Frequency",
|
||
fm6Legend: "R1..R4 / L1..L4: EG rates and levels; BP LD RD LC RC: keyboard level scaling; RS: rate scaling; AMS: LFO amplitude modulation; KVS: velocity; OL: output level; MODE: ratio / fixed; FC FF: coarse / fine frequency; DET: detune (7 = centre). ● = carrier.",
|
||
midiPorts: "MIDI ports (choose manually if Auto fails)", midiPortHelp: "These are the ports reported by the browser. Both an input and an output are required; empty lists mean the browser is not seeing a MIDI port. An SMK-37 connects by USB as the FM-1 does. The JIANT FM app (standalone): pick a MIDI input and output in its settings, then their other ends here (a virtual MIDI cable, for example). The MPC Sample's app does not answer the editor yet.", midiInput: "Input", midiOutput: "Output",
|
||
fm6BankSend: "Send to the device's voice bank (B1–B32)", fm6BankSent: "Voice bank sent:", fm6BankFail: "The voice bank was not sent (rc ", fm6BankNow: "The device's voice bank:", fm6BankNone: "none",
|
||
fm6Pick: "Voices of the imported file (click to edit):", fm6Picked: "Editing:", fm6Sent: "Sent to track", fm6Read: "Read from track",
|
||
fm6Loaded: "Loaded", fm6BadSum: "a checksum did not match",
|
||
fm6Keep: "To keep a voice, send it to a track, then save a user preset (SAVE) or a project on the device.",
|
||
fm6Short: "some data was cut short", fm6Skipped: "{x} non-voice blocks skipped",
|
||
fm6NoVoice: "No 6-operator FM voices found (expects a 32-voice bank or single-voice SysEx)",
|
||
fm6NotSysex: "Not a SysEx file (expects a 6-operator FM 32-voice bank or single-voice SysEx)",
|
||
fm6Is4op: "These are 4-operator FM voices: FM6 reads 6-operator voices only",
|
||
fm6OtherBlocks: "6-operator file format, but no voices (performance or supplement data only)",
|
||
fm6OtherMaker: "SysEx from another manufacturer", fm6Universal: "Universal SysEx, not voice data",
|
||
fm6Factories: "Factory patch",
|
||
fm6NeedDevice: "Connect the FM-1 to edit 6-OP FM voices and send them to a track.",
|
||
fm6NoFw: "This firmware has no 6-OP FM (FM6). Update to Felucca 1.0 or later to use it.",
|
||
motion: "Automation", motionOn: "Play automation", motionClear: "Clear automation", motionConfirm: "Clear this track's automation?", chance: "Chance %", ratchet: "Ratchet", motionStep: "Step", motionParam: "Parameter", motionValue: "Value",
|
||
backupTitle: "Complete backup", backupExport: "Save backup", backupImport: "Restore backup", backupHelp: "Save the current music, A–D, sound banks and settings to this computer.", backupOld: "Complete backups need firmware with archive support.", backupConfirm: "Restore this complete backup? Current music and saved data will be replaced. Keep USB connected.", backupWorking: "Backing up / restoring ", backupDone: "Backup saved", backupRestored: "Complete backup restored",
|
||
deviceDisplay: "Device display",
|
||
deviceDisplayHelp: "Changes apply to the FM-1 screen and save. Changes made while playing save after STOP.",
|
||
devicePresets: "Device presets",
|
||
deviceFavHelp: "Stars and the favorites filter sync with the FM-1. Save computer-library sounds to a device user slot before starring them.",
|
||
deviceList: "Show",
|
||
deviceAll: "All presets",
|
||
deviceFavorites: "Favorites only",
|
||
deviceEmpty: "No favorites yet. Choose All presets to add some.",
|
||
deviceTheme: "Theme",
|
||
deviceFont: "Font",
|
||
deviceMonitor: "MIDI monitor",
|
||
deviceRegular: "Regular",
|
||
deviceBold: "Bold",
|
||
deviceOff: "Off",
|
||
deviceEvents: "Events",
|
||
deviceNotes: "Held notes / chords",
|
||
deviceStar: "Add favorite",
|
||
deviceUnstar: "Remove favorite",
|
||
deviceUnsaved: "Applied, but could not save on the device. Try again.",
|
||
deviceRejected: "The device rejected that setting.",
|
||
devicePending: "Applied. Settings will save when playback stops.",
|
||
|
||
other: "Español", connect: "Connect", disconnect: "Disconnect", mock: "Mock device (no hardware)",
|
||
tabMath: "MATH", mathHelp: "MATH's formulas. BYTE is bytebeat: a formula of the time t whose low 8 bits are the sound; FLOAT its sibling of sines. Pick one of the device's 48 + 48 or write your own (JIANT BYTE's language: t w a n v, sin cos tri saw sqr abs min max floor int fix rnd sat clip, a \"...\"[i] table), hear it, generate one, and send it to a track. From V10.8.75 the device plays your own as MATH USER (ALGO USER): up to 64 bytes of its bytecode.",
|
||
mathGrammarT: "Grammar (the firmware's)", mathGrammar: "t: the time, 31 steps a cycle of the note (C4: about 8 kHz); MOTION runs its slow bits at their own speed (0: 1/16, 64: as written, 128..255 SYNC: on the bar), LOOP holds t in a window, VARIANT mutates t (its way: VAR / 16, how much: VAR % 16) and gives a = 1 + VAR / 8 (1..16), BEND folds t.\nNumbers: 123, 0x1F (an optional u). Operators as in C, all unsigned 32-bit: ( ), unary - ~ !, then * / %, + -, << >>, < <= > >=, == !=, &, ^, |, &&, ||, c ? x : y. A comparison or ! gives 0 or 1. The low 8 bits are played (CHIP: 8, 4 or 1 of them).\nExamples (the device's): t * (42 & t >> 10) · t * (0xCA98 >> (t >> 9 & 14) & 15) | t >> 8 · (t >> 13 | t % 24) & (t >> 7 | t % 19).",
|
||
mathOwn: "— your own —", mathFloatRo: "FLOAT's formulas are the firmware's own C (sines in fixed point): listen and send; edit BYTE formulas.",
|
||
mathErr: "Error:", mathAt: "at", mathIsStock: "the device's own formula: it can be sent", mathOwnOk: "Your formula (MATH USER)", mathTerms: "terms",
|
||
mathPlay: "Play", mathStop: "Stop", mathLoop: "Loop", mathRendering: "Rendering…", mathNoEmu: "The emulator is not reachable from here: no sound for FLOAT.",
|
||
mathFixFirst: "Fix the formula first.", mathSrcEmu: "Heard: the emulator's own samples (the device's code)", mathSrcModel: "Heard: the model of MATH's BYTE voice (your formula)",
|
||
mathSeed: "Seed", mathFamily: "Family", mathChaos: "Chaos", mathAny: "Any", mathGen: "Generate formula", mathGenPatch: "Generate sound", mathGenerated: "Generated: seed",
|
||
mathSend: "Send to track", mathRead: "Read track", mathConnect: "Connect the FM-1 (or the emulator) to send.",
|
||
mathOwnNoSend: "Not sendable: this device's firmware has no formulas of one's own (MATH USER, V10.8.75).", mathUserSend: "Your formula: sent as the track's own, ALGO set to USER.", mathUserRefused: "The device refused the formula:", mathReadUser: "Read (the formula's text is not in this browser) from", mathSent: "Sent to", mathSentClamped: "Sent (some values clamped by the device) to",
|
||
mathNotMath: "Not a MATH track:", mathReadOk: "Read from",
|
||
tabRoll: "Piano roll", rollFit: "Fit", rollUndo: "Undo", rollReading: "Reading the steps", rollGrid: "DRUM grid", rollNotes: "notes",
|
||
rollHelp: "Tap an empty cell to add a note (a hit on a DRUM track); tap a note to select it, tap it again to remove it. Drag a note up or down to change its pitch, to the right to hold it (TIE steps). Drag elsewhere to scroll, pinch (or Ctrl + wheel) to zoom. The strip at the top jumps to a bar; the lane at the bottom draws velocity, chance or ratchet. Keys: arrows, Delete, A accent, S slide, Ctrl+Z undo. Every change is written to the track at once.",
|
||
rollPick: "Select a step: tap a note, a hit or a step number.", rollStep: "Step", rollPastLen: "past LEN", rollTapToAdd: "No notes: tap the roll to add one.",
|
||
rollClear: "Clear step", rollNoHit: "no hit", rollLocks: "Locks and automation", rollLockParam: "Parameter", rollAddLock: "Add lock",
|
||
rollNoLocks: "This firmware has automation only (no parameter locks).", rollChordFull: "A step holds four notes at most.",
|
||
rollNoUndo: "Nothing to undo on this track.", rollFull: "The 64 motion records are used", rollRefused: "Refused by the device",
|
||
rollMicroMissing: "MICRO, the step components (COMP 1 / 2, EVERY, LEN, N:M) and EUCLID's own settings are kept on the device but the editor protocol cannot read or write them; writing a step here keeps them as they are.",
|
||
rollEuHelp: "Euclidean rhythms (the device's own formula): HITS spread over STEPS, turned by ROTATE, repeated over the track's LEN. On a DRUM track ALL makes a kit from a DENSITY 1..8, or pick one lane. Preview outlines the steps, Write writes them (one undo).",
|
||
rollPreview: "Preview", rollWriteSteps: "Write steps",
|
||
rollMsHelp: "The track's modulation sequence (MOD > SEQ): 16 levels, LEN, DIV and SLEW on the Sound tab. Draw the levels; the matrix reads them as source STEP.",
|
||
rollSlcHelp: "The SLICER bus's pitch steps (global, every track through the SLICER): 16 steps of -24..24 semitones, LEN on the Sound tab's globals.",
|
||
|
||
sound: "Sound", engine: "Engine", presets: "Presets", initSound: "Init sound",
|
||
track: "Track",
|
||
saveFile: "Save to file", loadFile: "Load file", projects: "Projects",
|
||
load: "Load", save: "Save", used: "used", empty: "empty", unknown: "—",
|
||
steps: "Steps", reload: "Reload", clearSeq: "Clear sequence",
|
||
notesHelp: "Enter notes like C4 E4 G4 (up to 4, C4 = 60). Hits are DRUM lanes: KICK >SNARE HATCL (> = accent).",
|
||
notes: "Notes", hits: "Hits", time: "Time", acc: "Accent", slide: "Slide", vel: "Velocity",
|
||
foot: "Works in Chrome or Edge.", iconsCredit: "Icons: Fukiai (MIT), Hügelton Instruments",
|
||
nomidi: "This browser cannot do it. Open the page in Chrome or Edge.",
|
||
denied: "MIDI (SysEx) access was not allowed.",
|
||
nodevice: "JIANT not found. Connect it by USB and press Connect again.", portsSeen: "MIDI ports seen:", portsNone: "no MIDI port at all: check the cable carries data and MENU > USB is CONSOLE",
|
||
connecting: "Connecting", reading: "Reading ", steploading: "Reading steps ",
|
||
ready: "Connected", disconnected: "Disconnected", lost: "JIANT was unplugged", instbusy: "The installer is writing in another tab: connect when it has finished.",
|
||
noreply: "No reply from the device", error: "Error: ", busy: "Busy",
|
||
screenBtn: "Screen", screenTitle: "Screen", screenSharp: "Sharp", screenFull: "Full screen", screenClose: "Close",
|
||
screenWait: "Waiting for the FM-1's screen…", screenRate: " KB/s", screenNo: "This firmware has no screen mirror (update JIANT FM)",
|
||
screenHelp: "To see it big on a phone: open this editor in Chrome on the phone and plug the FM-1 into its USB-C port (OTG).",
|
||
applying: "Writing ", applied: "Loaded", badfile: "Cannot read the file: ",
|
||
savedSlot: "Saved to slot ", loadedSlot: "Loaded slot ", emptySlot: "Empty slot: ",
|
||
confirmSave: "Overwrite slot {n}?", confirmLoad: "Load slot {n}? The sounds and sequences of all tracks are replaced (no undo).",
|
||
confirmClear: "Clear the whole sequence?", confirmInit: "Reset the sound to the engine defaults? The sequence stays (hold SAVE on the device to undo).",
|
||
erase: "Erase", remove: "Remove",
|
||
layout: "(The firmware has a different parameter count; showing a plain list.)",
|
||
ctlHelp: "Sliders: click, then fine-tune with the wheel or arrow keys (Shift: steps of 10); double-click resets.",
|
||
lyricT: "Lyric (VOICE WORDS)",
|
||
lyricHelp: "The VOICE track's lyric (up to 63 characters). EDIT > WORDS: LANG picks the language (ES / EN / JA, Japanese in romaji), LYRIC TEXT sings this. Each note sings the next syllable; a \"-\" holds the vowel one more note.",
|
||
lyricSend: "Send",
|
||
lyricLang: "LANG",
|
||
lyricSrc: "LYRIC",
|
||
lyricSent: "Lyric sent",
|
||
live: "● Live", polling: "○ Polling (older firmware)",
|
||
library: "Library", libSearch: "Search name or tag", allEngines: "All engines", allTags: "All tags",
|
||
sortModified: "Recently changed", sortCreated: "Recently added", sortName: "Name", sortEngine: "Engine",
|
||
name: "Name", tagsCol: "Tags", date: "Changed",
|
||
audition: "Audition", toSlot: "To device slot", rename: "Rename", tags: "Tags", duplicate: "Duplicate", delete: "Delete",
|
||
exportPatch: "Export", saveToLib: "Save current sound", import: "Import", exportLib: "Export library",
|
||
factoryToLib: "Copy to library", libEmpty: "The library is empty. Add sounds with \"Save current sound\", by copying a factory preset or a device slot, or by importing a file.",
|
||
noMatch: "No match", noLibDB: "(this browser cannot store it: it is gone after a reload)",
|
||
bank: "User presets on the device", bankLoad: "Load", bankStore: "Store current sound", bankGet: "To library",
|
||
exportBank: "Export bank", dndHelp: "You can also drag between the library and the slots.",
|
||
confirmOverwrite: "Overwrite slot {n} ({name})?", confirmEraseSlot: "Erase slot {n} ({name})?",
|
||
confirmDelete: "Delete \"{name}\" from the library?",
|
||
promptName: "Name (the device keeps 12 ASCII characters)", promptTags: "Tags (comma separated)",
|
||
promptNameAuto: "Name (12 ASCII characters; empty: the device names it)",
|
||
auditioning: "Preparing audition ", auditioned: "Auditioning (the sound only, the sequence stays; hold SAVE on the device to undo): ",
|
||
savedLib: "Saved to the library: ", copiedLib: "Copied to the library: ", imported: "Imported: ",
|
||
skippedN: " ({n} unreadable)", patchesN: " patches",
|
||
putDone: "Written to the device: slot ", storedSlot: "Stored on the device: slot ", erasedSlot: "Erased slot ",
|
||
loadedUser: "Sound loaded (the sequence stays; its pattern is on the device under SEQ > PHRASES; hold SAVE to undo): ", reloaded: "The sound changed on the device: read again", readingBank: "Reading the slots",
|
||
badEngine: "This firmware has no such engine: ", flashFail: "Write failed (rc {rc})",
|
||
installer: "JIANT installer",
|
||
tabSeq: "Sequencer", tabTracks: "Tracks", tabSettings: "Settings",
|
||
needDevice: "Connect the FM-1 to edit.",
|
||
bankConnect: "Connect the FM-1 to see its user presets too.", bankNone: "This firmware has no user presets.",
|
||
mixer: "Mixer", mixHelp: "The tracks of the device's MIXER page. The fader is the level. Pan is written to any track without changing the selection (firmware 0.8: by selecting it for a moment). REC shows a track armed for live recording on the device.",
|
||
level: "Level", pan: "Pan", mute: "Mute", rec: "REC", selectTrack: "Select", selectedTrack: "Selected",
|
||
projHelp: "A project keeps the sounds and patterns of all tracks, the song chain, the selected track and the global settings.",
|
||
slot: "Slot", songTitle: "Song", songHelp: "Arrange sections (the saved projects A–D, with their sounds) and choose how many bars each plays (1–64). Save a project above to keep the chain. Rows change on the bar; the song stops at the end and the music before it comes back.", songAdd: "Add row", songRemove: "Remove last row", songPlay: "Play from start", songStop: "Stop", songReps: "bars", songEmpty: "Add a row first", songBusy: "Stop before editing", songInvalid: "Check sections and bars", songPlaying: "Playing row", songSaved: "Chain changed. Save a project to keep it.",
|
||
system: "System", deviceL: "Device", firmware: "Firmware", sync: "Sync", tracksN: "Tracks", stepsN: "Steps", enginesL: "Engines",
|
||
userBank: "User presets", none: "none",
|
||
},
|
||
es: {
|
||
tabMath: "MATH", mathHelp: "Las fórmulas de MATH. BYTE es bytebeat: una fórmula del tiempo t cuyos 8 bits bajos son el sonido; FLOAT, su hermana de senos. Elegí una de las 48 + 48 del equipo o escribí la tuya (el lenguaje de JIANT BYTE: t w a n v, sin cos tri saw sqr abs min max floor int fix rnd sat clip, una tabla \"...\"[i]), escuchala, generá una y mandala a una pista. Desde V10.8.75 el equipo toca la tuya como MATH USER (ALGO USER): hasta 64 bytes de su bytecode.",
|
||
mathGrammarT: "Gramática (la del firmware)", mathGrammar: "t: el tiempo, 31 pasos por ciclo de la nota (C4: unos 8 kHz); MOTION mueve sus bits lentos a su propia velocidad (0: 1/16, 64: tal cual, 128..255 SYNC: con el compás), LOOP encierra t en una ventana, VARIANT muta t (la forma: VAR / 16, cuánto: VAR % 16) y da a = 1 + VAR / 8 (1..16), BEND pliega t.\nNúmeros: 123, 0x1F (con u opcional). Operadores como en C, todo sin signo de 32 bits: ( ), unarios - ~ !, luego * / %, + -, << >>, < <= > >=, == !=, &, ^, |, &&, ||, c ? x : y. Una comparación o ! da 0 o 1. Suenan los 8 bits bajos (CHIP: 8, 4 o 1).\nEjemplos (del equipo): t * (42 & t >> 10) · t * (0xCA98 >> (t >> 9 & 14) & 15) | t >> 8 · (t >> 13 | t % 24) & (t >> 7 | t % 19).",
|
||
mathOwn: "— la tuya —", mathFloatRo: "Las fórmulas FLOAT son el C del firmware (senos en punto fijo): escuchalas y mandalas; se editan las BYTE.",
|
||
mathErr: "Error:", mathAt: "en", mathIsStock: "una fórmula del equipo: se puede mandar", mathOwnOk: "Tu fórmula (MATH USER)", mathTerms: "términos",
|
||
mathPlay: "Tocar", mathStop: "Parar", mathLoop: "Repetir", mathRendering: "Calculando…", mathNoEmu: "No se llega al emulador desde acá: FLOAT sin sonido.",
|
||
mathFixFirst: "Corregí la fórmula primero.", mathSrcEmu: "Suena: las muestras del emulador (el código del equipo)", mathSrcModel: "Suena: el modelo de la voz BYTE de MATH (tu fórmula)",
|
||
mathSeed: "Semilla", mathFamily: "Familia", mathChaos: "Caos", mathAny: "Cualquiera", mathGen: "Generar fórmula", mathGenPatch: "Generar sonido", mathGenerated: "Generado: semilla",
|
||
mathSend: "Mandar a la pista", mathRead: "Leer pista", mathConnect: "Conectá el FM-1 (o el emulador) para mandar.",
|
||
mathOwnNoSend: "No se puede mandar: el firmware de este equipo no tiene fórmulas propias (MATH USER, V10.8.75).", mathUserSend: "Tu fórmula: va como la fórmula propia de la pista, ALGO en USER.", mathUserRefused: "El equipo rechazó la fórmula:", mathReadUser: "Leído (el texto de la fórmula no está en este navegador) de", mathSent: "Mandado a", mathSentClamped: "Mandado (el equipo ajustó algún valor) a",
|
||
mathNotMath: "No es una pista MATH:", mathReadOk: "Leído de", track: "Pista",
|
||
other: "日本語", connect: "Conectar", disconnect: "Desconectar", sound: "Sonido", tabSeq: "Secuenciador", tabTracks: "Pistas",
|
||
tabSettings: "Ajustes", library: "Biblioteca", projects: "Proyectos", reload: "Releer", remove: "Quitar", time: "Tiempo",
|
||
chance: "Chance", motionValue: "Valor", songBusy: "Pará la canción antes de editar", ready: "Listo",
|
||
tabRoll: "Piano roll", rollFit: "Ajustar", rollUndo: "Deshacer", rollReading: "Leyendo los pasos", rollGrid: "Grilla DRUM", rollNotes: "notas",
|
||
rollHelp: "Tocá una celda vacía para agregar una nota (un golpe en una pista DRUM); tocá una nota para elegirla y otra vez para borrarla. Arrastrá una nota arriba o abajo para cambiar su altura, a la derecha para sostenerla (pasos TIE). Arrastrá en otro lado para moverte, pellizcá (o Ctrl + rueda) para hacer zoom. La tira de arriba salta a un compás; el carril de abajo dibuja velocidad, chance o ratchet. Teclas: flechas, Supr, A acento, S slide, Ctrl+Z deshacer. Cada cambio se escribe en la pista al instante.",
|
||
rollPick: "Elegí un paso: tocá una nota, un golpe o el número de un paso.", rollStep: "Paso", rollPastLen: "fuera de LEN", rollTapToAdd: "Sin notas: tocá el roll para agregar una.",
|
||
rollClear: "Borrar paso", rollNoHit: "sin golpe", rollLocks: "Locks y automatización", rollLockParam: "Parámetro", rollAddLock: "Agregar lock",
|
||
rollNoLocks: "Este firmware solo tiene automatización (sin locks de parámetros).", rollChordFull: "Un paso tiene cuatro notas como máximo.",
|
||
rollNoUndo: "Nada para deshacer en esta pista.", rollFull: "Los 64 registros de motion están usados", rollRefused: "El equipo lo rechazó",
|
||
rollMicroMissing: "MICRO, los componentes del paso (COMP 1 / 2, EVERY, LEN, N:M) y los ajustes propios de EUCLID quedan en el equipo, pero el protocolo del editor no los puede leer ni escribir; escribir un paso acá los deja como están.",
|
||
rollEuHelp: "Ritmos euclidianos (la fórmula del equipo): HITS repartidos en STEPS, girados por ROTATE, repetidos a lo largo del LEN de la pista. En una pista DRUM, ALL arma un kit con una DENSIDAD 1..8, o elegí un carril. Vista previa marca los pasos, Escribir los escribe (un deshacer).",
|
||
rollPreview: "Vista previa", rollWriteSteps: "Escribir pasos",
|
||
rollMsHelp: "La secuencia de modulación de la pista (MOD > SEQ): 16 niveles; LEN, DIV y SLEW en la pestaña Sonido. Dibujá los niveles; la matriz los lee como fuente STEP.",
|
||
rollSlcHelp: "Los pasos de altura del bus SLICER (global, toda pista que pasa por el SLICER): 16 pasos de -24..24 semitonos; LEN en los globales de la pestaña Sonido.",
|
||
},
|
||
};
|
||
/* (the formula editor) the generator's families, named in each language */
|
||
for (const f of MATH_FAMILIES) for (const l of ["en", "es", "ja"]) TEXT[l]["mfam_" + f.id] = f[l];
|
||
/* (the piano roll, the formula editor) English, Spanish and Japanese; a text a language lacks is the English one */
|
||
let lang = (() => { const l = (navigator.language || "en").toLowerCase(); return l.startsWith("ja") ? "ja" : l.startsWith("es") ? "es" : "en"; })();
|
||
const t = (k) => TEXT[lang][k] ?? TEXT.en[k] ?? k;
|
||
let lastKey = null, lastArg = "";
|
||
function sayK(k, arg = "") { lastKey = k; lastArg = arg; $("status").textContent = t(k) + arg; }
|
||
function applyLang() {
|
||
document.documentElement.lang = lang;
|
||
document.querySelectorAll("[data-t]").forEach((e) => setLabel(e, t(e.dataset.t)));
|
||
$("lang").textContent = t("other");
|
||
setLabel($("connect"), t(dev ? "disconnect" : "connect"));
|
||
if (lastKey) $("status").textContent = t(lastKey) + lastArg;
|
||
$("libq").placeholder = t("libSearch");
|
||
renderLive();
|
||
renderLib();
|
||
renderBank();
|
||
renderPreferences(true);
|
||
renderPanels();
|
||
if (dev) { renderSlots(); renderStepHead(); renderTrackbar(); renderMixer(); renderSysinfo(); renderFm6(); }
|
||
}
|
||
$("lang").addEventListener("click", () => { lang = { en: "es", es: "ja", ja: "en" }[lang] || "en"; applyLang(); });
|
||
|
||
/* ---------------------------------------------------------------- tabs --- */
|
||
/* one panel at a time; the last one is remembered (localStorage) and in the URL hash (#sound ...) */
|
||
const TABS = ["sound", "fm6", "sequencer", "roll", "math", "tracks", "library", "projects", "settings"];
|
||
const TAB_KEY = "felucca-editor-tab";
|
||
const TRACK_TABS = new Set(["sound", "sequencer", "roll", "tracks"]);
|
||
let tab = (() => {
|
||
const h = location.hash.slice(1);
|
||
if (TABS.includes(h)) return h;
|
||
try { const v = localStorage.getItem(TAB_KEY); if (TABS.includes(v)) return v; } catch (e) { /* no storage */ }
|
||
return "sound";
|
||
})();
|
||
const hasTracks = () => !!dev && !!dev.info && !!dev.info.ntrk;
|
||
function showTab(name) {
|
||
if (!TABS.includes(name)) name = "sound";
|
||
const prev = tab;
|
||
tab = name;
|
||
try { localStorage.setItem(TAB_KEY, name); } catch (e) { /* no storage */ }
|
||
if (location.hash !== "#" + name) history.replaceState(null, "", location.pathname + location.search + "#" + name);
|
||
renderPanels();
|
||
if (name === "tracks" && prev !== "tracks" && hasTracks() && dev.dump) op(readMixer);
|
||
if (name === "fm6" && prev !== "fm6" && dev && dev.dump && dev.info.fm6 && !fm6Listing) op(fm6Refresh);
|
||
}
|
||
function renderPanels() {
|
||
/* the Tracks tab only with a four-track firmware */
|
||
const tracksOk = !dev || hasTracks() || !dev.info;
|
||
const fm6Off = !!dev && !!dev.info && !dev.info.fm6; /* the 6-OP FM tab: a hint without FM6 firmware */
|
||
const want = tab === "tracks" && dev && dev.info && !hasTracks() ? "sound" : tab;
|
||
for (const b of $("tabs").querySelectorAll("button[data-tab]")) {
|
||
const on = b.dataset.tab === want;
|
||
b.setAttribute("aria-selected", on ? "true" : "false");
|
||
b.tabIndex = on ? 0 : -1;
|
||
if (b.dataset.tab === "tracks") b.hidden = !tracksOk;
|
||
}
|
||
const ready = !!dev && !!dev.dump;
|
||
let hint = "";
|
||
for (const p of document.querySelectorAll(".panel")) {
|
||
const mine = p.dataset.tab === want;
|
||
let show = mine && (!("dev" in p.dataset) || ready);
|
||
if (mine && "dev" in p.dataset && !dev) hint = want === "fm6" ? "fm6NeedDevice" : "needDevice"; /* (while connecting the status line says it) */
|
||
if (show && want === "fm6" && fm6Off) { show = false; hint = "fm6NoFw"; }
|
||
p.hidden = !show;
|
||
}
|
||
$("hint").hidden = !hint;
|
||
if (hint) $("hint").textContent = t(hint);
|
||
$("trackbar").hidden = !(ready && hasTracks() && TRACK_TABS.has(want));
|
||
rollShow(want === "roll" && ready && hasTracks()); /* (the piano roll: read and drawn only while it shows) */
|
||
mathShow(want === "math"); /* (MATH: built when it first shows; its sound stops when it goes) */
|
||
/* the FM6 slot names: listed once the tab shows with a device (also when it was already open at connect) */
|
||
if (ready && want === "fm6" && dev.info.fm6 && !fm6List && !fm6Asked) { fm6Asked = true; op(fm6Refresh); }
|
||
}
|
||
$("tabs").addEventListener("click", (e) => { const b = e.target.closest("button[data-tab]"); if (b) showTab(b.dataset.tab); });
|
||
$("tabs").addEventListener("keydown", (e) => { /* arrow keys move between the tabs */
|
||
const dir = { ArrowRight: 1, ArrowLeft: -1 }[e.key];
|
||
if (!dir) return;
|
||
const bs = [...$("tabs").querySelectorAll("button[data-tab]:not([hidden])")];
|
||
const i = bs.findIndex((b) => b.getAttribute("aria-selected") === "true");
|
||
const n = bs[(i + dir + bs.length) % bs.length];
|
||
e.preventDefault();
|
||
showTab(n.dataset.tab);
|
||
n.focus();
|
||
});
|
||
window.addEventListener("hashchange", () => { const h = location.hash.slice(1); if (TABS.includes(h) && h !== tab) showTab(h); });
|
||
|
||
const QS = new URLSearchParams(location.search);
|
||
/* (studio) ?emu=1 inside JIANT Studio: the editor edits the emulator beside it (studio.js emuMidi), not a USB FM-1 */
|
||
const EMU = QS.get("emu") === "1" && (() => { try { return window.parent !== window && window.parent.jiantStudio; } catch (_) { return null; } })();
|
||
const MOCK = QS.get("mock") === "1";
|
||
$("mock").hidden = !MOCK;
|
||
let mock = null;
|
||
|
||
/* -------------------------------------------------------------- state --- */
|
||
let access = null; /* MIDIAccess */
|
||
let dev = null; /* {link, input, output, info, pdesc[], gdesc[], names[][], dump, steps[], slotUsed[],
|
||
keys[] (paramKeys), watch (pushes on), bank ({total, slots[]} or null: no user bank)} */
|
||
let busy = 0; /* multi-request operations in progress: no polling */
|
||
/* A completion from an unplugged device must not release a new session's work. */
|
||
let busyEpoch = 0;
|
||
function beginBusy() {
|
||
const epoch = busyEpoch;
|
||
let released = false;
|
||
busy++;
|
||
return () => {
|
||
if (!released && epoch === busyEpoch) busy--;
|
||
released = true;
|
||
};
|
||
}
|
||
function resetBusy() { busyEpoch++; busy = 0; }
|
||
let dragging = null; /* key of the slider being dragged */
|
||
let wantConnected = false;
|
||
const ctl = new Map(); /* key "s:id" -> {input, out, desc, scope, id, row} */
|
||
const sets = new Map(); /* key -> {last: time of the user's last change, sent: the value last requested} */
|
||
let needReload = false; /* a RELOAD push came: re-read DESC, DUMP and steps when free */
|
||
let lastDump = 0; /* Date.now() of the last DUMP */
|
||
/* the device also pushes RELOAD after loads the editor asked for (PROJECT load, UP_LOAD; before INFO 53 bit 1
|
||
also SET of G_ENGSEL and PRESET); the editor re-reads after those anyway, so it skips that many RELOADs for a
|
||
moment. sound: a PRESET / G_ENGSEL load (no RELOAD comes from newer firmware: none to skip) */
|
||
const selfReload = { n: 0, until: 0 };
|
||
function selfLoad(sound = false) {
|
||
if (!dev || !dev.watch || (sound && dev.info && dev.info.syncCaps & 2)) return;
|
||
const now = Date.now();
|
||
selfReload.n = now < selfReload.until ? selfReload.n + 1 : 1;
|
||
selfReload.until = now + 1500;
|
||
}
|
||
const stepEdit = new Map(); /* index -> time of the last edit */
|
||
|
||
/* parameter ids (firmware/src/core.h); used only when P_COUNT / G_COUNT match */
|
||
const EXPECT = { pcount: 91, gcount: 27, pe0: 83 };
|
||
/* the same layout without the chord keys (P_COUNT 89, P_E0 81), the FM operator ENVs too (69, 61) or the matrix
|
||
(firmware 1.0: 57, 49) */
|
||
/* (V10.8.77, a user: "the sound editor's modules became a vertical list") the firmware appends: globals past 73 (77 since
|
||
the OTT, GATE, ...) and track parameters past 123 keep every id the layout names, so a newer firmware is known too: any
|
||
G_COUNT from 73 up, any P_COUNT from 123 up with its 8 engine slots last (P_E0 = P_COUNT - 8); web/editor_layout_test.mjs */
|
||
const knownLayout = (info) => ([EXPECT.gcount, 32, 36, 37, 66, 67, 69, 71].includes(info.gcount) || info.gcount >= 73) && /* (JIANT FUNB: 5, 9, then 10 more globals; 0.6.3: the SLICER's 29) */
|
||
([[120, 112], [99, 91], [91, 83], [89, 81], [69, 61], [57, 49]].some(([c, e]) => info.pcount === c && info.pe0 === e) ||
|
||
(info.pcount >= 123 && info.pcount < 128 && info.pe0 === info.pcount - 8));
|
||
const P = { LEVEL: 0, SLEN: 29 };
|
||
const LAYOUT = (pe0) => [
|
||
{ t: "ENV", pages: [["ENV", 0, [1, 2, 3, 4]], ["ENV DEST", 0, [5, 6, 7, 8]]] },
|
||
{ t: "LFO", pages: [["LFO", 0, [9, 10, 11, 12]], ["LFO DEST", 0, [13, 14, 15, 16]],
|
||
...(pe0 >= 112 ? [["MSEQ", 0, [93, 95, 94]], ...[0, 1, 2, 3].map((k) => [`STEPS ${4 * k + 1}-${4 * k + 4}`, 0,
|
||
[96 + 4 * k, 97 + 4 * k, 98 + 4 * k, 99 + 4 * k]])] : [])] }, /* (JIANT) the modulation sequence: LEN DIV SLEW, its 16 levels */
|
||
...(pe0 >= 61 ? [{ t: "MOD", mod: 49 }] : []), /* the matrix: P_M1SRC 49 .. P_M4AMT 60, one row per slot */
|
||
{ t: "EDIT", engine: true, pages: [["EDIT 1", 0, [pe0, pe0 + 1, pe0 + 2, pe0 + 3]], ["EDIT 2", 0, [pe0 + 4, pe0 + 5, pe0 + 6, pe0 + 7]],
|
||
...(pe0 >= 91 && engName() === "DRUM" ? [["LANES", 0, P_LANES.slice(0, 4)], ["LANES 2", 0, P_LANES.slice(4)]] : []), /* lane levels 83..90 */
|
||
...hpPages(pe0)] }, /* (ports/) SAMPLE's TRIG REC, GRAIN's TRAVEL SOURCE PITCH, DRUM-X's SAMPLES */
|
||
...(pe0 >= 115 ? [{ t: "FILTER", pages: [["FILTER", 0, [112, 113, 114]]] }] : []), /* (JIANT 0.5) TYPE CUT RES (P_FTYPE ..) */
|
||
...(pe0 >= 81 && engName() === "DIGITAL" ? [{ t: "OP ENV", pages: [ /* P_FM1_ATK 61: ATK DEC SUS REL LVL per operator (a
|
||
FELUCCA_FM4=1 firmware only: DIGITAL retired, its engine is "-") */
|
||
...[0, 1, 2, 3].map((k) => [`OP${k + 1}`, 0, [61 + 5 * k, 62 + 5 * k, 63 + 5 * k, 64 + 5 * k]]),
|
||
["OP LVL", 0, [65, 70, 75, 80]]] }] : []),
|
||
{ t: "VOICE", pages: [["LEVEL", 0, [0]], ["VOICE", 0, [37, 38, 41, 42]]] }, /* (JIANT 0.4: no VOICE 2: PAN on MIXER, MUTE there and GLO) */
|
||
{ t: "FX", pages: [["FX", 0, [33, 34, 35, 36]], ["MASTER", 1, [21, 25, 26, 13]], ...(dev && dev.gdesc && dev.gdesc[17] && dev.gdesc[17].label === "DJ FILT" ? [["DJ FILTER", 1, [17]]] : []), /* (0.9.1, as the device names it) */ ...(pe0 >= 112 ? [["DIST", 0, [33, 91, 92]]] : []), ...(dev && dev.info && dev.info.gcount >= 66 ? [["AUTO PAN", 0, [45, 46, 48, 47]], ["SLICER", 1, [37, 38, 39, 40]], ["SL BUS", 1, [41, 42, 43, 44]],
|
||
["SL BUS 2", 1, [45, 46, 47]], ["SL PITCH", 1, [48, 49]], ...[0, 1, 2, 3].map((k) => [`PITCH ${4 * k + 1}-${4 * k + 4}`, 1,
|
||
[50 + 4 * k, 51 + 4 * k, 52 + 4 * k, 53 + 4 * k]])] : [["SLICER", 0, [45, 46, 47, 48]]]), /* (0.6.3: one, on a bus) */
|
||
["DLY", 1, [4, 5, 6, 7]], ...(pe0 >= 112 ? [["DLY 2", 1, [28, 34, 35, ...(dev && dev.info && dev.info.gcount >= 67 ? [66] : [])]],
|
||
...(dev && dev.info && dev.info.gcount >= 69 ? [["DLY 3", 1, [67, 68]]] : [])] : []), ["REVERB", 1, pe0 >= 112 ? [24, 8, 9, 31] : [24, 8, 9]],
|
||
...(pe0 >= 112 ? [["REVERB 2", 1, [29, 30, 32, 33]]] : []), ["CHORUS", 1, pe0 >= 112 ? [10, 11, 27] : [10, 11]]] }, /* G_RTYPE 24: ROOM SPRING SHIMR RESO CLOUD; MASTER: CLIP PNCH DUCK REL; (0.6.9) AUTOPAN: DPTH RATE SYNC WAVE, CHORUS: STER (27) */
|
||
{ t: "SCL", pages: [["SCL", 0, [25, 26, 27, 28]], ["SCL 2", 1, [36]]] }, /* (JIANT 0.4) G_STRN 36: every sequence along the scale */
|
||
{ t: "ARP", pages: [["ARP", 0, [17, 18, 19, 20]], ["ARP 2", 0, [21, 22, 23, 24]]] },
|
||
{ t: "SEQ PATTERN", tab: "seqgroups", pages: [["PATTERN", 0, [29, 30, 31, 32]], ...(pe0 >= 83 ? [["STRETCH · TRACK", 0, P_SHIFT]] : [])] }, /* ROTATE PITCH 81, 82 (SHIFT until 0.6.91) */
|
||
{ t: "GLOBAL", tab: "setgroups", pages: [["GLOBAL", 1, [0, 1, 2, 3]], ["SYSTEM", 1, [14]]] }, /* G_ROUTE: MIDI IN */
|
||
];
|
||
function hpPages(pe0) {
|
||
const hp = dev && dev.info && dev.info.hostPower;
|
||
const name = engName();
|
||
if (!hp || pe0 < 115 || !(name === "SAMPLE" && hp.sample || name === "GRAIN" && hp.grain || name === "DRUM" && hp.drumSamples)) return [];
|
||
return HP_PAGES[name];
|
||
}
|
||
/* globals that are actions or placeholders on the device: buttons instead, or hidden */
|
||
const G_SKIP = new Set(["SLOT", "NAME", "LOAD", "SAVE", "ENG", "SET", "CLRSQ", "INIT", "MIDI", "SYNC", "CPU", "CLK"]);
|
||
const key = (s, id) => s + ":" + id;
|
||
const engName = () => (dev && dev.info && dev.dump ? dev.info.engines[dev.dump.engine] : "");
|
||
const gEng = () => { const i = dev.gdesc.findIndex((d) => d && d.label === "ENG"); return i >= 0 ? i : 20; };
|
||
const pSlen = () => { const i = dev.pdesc.findIndex((d) => d && d.fmt === F.STEPS); return i >= 0 ? i : P.SLEN; };
|
||
/* mixer ids by DESC label (core.h: P_PAN 39, P_MUTE 40) */
|
||
const pById = (label, def) => { const i = dev.pdesc.findIndex((d, k) => d && k < dev.info.pe0 && d.label === label); return i >= 0 ? i : def; };
|
||
const pPan = () => pById("PAN", 39), pMute = () => pById("MUTE", 40);
|
||
|
||
/* -------------------------------------------------------------- MIDI --- */
|
||
let connecting = false, portsClosing = Promise.resolve();
|
||
const portStates = new Map();
|
||
function renderMidiPorts() {
|
||
if (!access) return;
|
||
$("midiportcounts").textContent = `${t("midiInput")}: ${[...access.inputs.values()].filter(p=>p.state!=="disconnected").length} · ${t("midiOutput")}: ${[...access.outputs.values()].filter(p=>p.state!=="disconnected").length}`;
|
||
for (const [id, ports] of [["midiinput",access.inputs],["midioutput",access.outputs]]) {
|
||
const box=$(id), value=box.value;
|
||
box.replaceChildren(el("option",{value:"",text:"Auto (JIANT / FM1)"}), ...[...ports.values()].filter(p=>p.state!=="disconnected").map(p=>el("option",{value:p.id,text:p.name || p.id})));
|
||
if ([...box.options].some(o=>o.value===value)) box.value=value;
|
||
}
|
||
}
|
||
/* (0.9.11) the web installer in another tab of this browser (web/index_pkg.html): while it writes, the editor lets the
|
||
* FM-1 go and does not reconnect by itself (the update loader's port is a "JIANT" one too); it says it is here */
|
||
let installerUntil = 0;
|
||
try {
|
||
const bc = new BroadcastChannel("jiant-midi");
|
||
bc.onmessage = (e) => {
|
||
const m = e.data || {};
|
||
if (m.type === "who") bc.postMessage({ type: "editor", connected: !!dev });
|
||
if (m.type === "installer") {
|
||
installerUntil = m.busy ? Date.now() + 60000 : 0;
|
||
if (m.busy) {
|
||
wantConnected = false;
|
||
if (dev) disconnect("instbusy"); /* (the screen mirror closes with it) */
|
||
Promise.resolve(portsClosing).then(() => bc.postMessage({ type: "released", who: "editor" })); /* (the installer waits) */
|
||
}
|
||
}
|
||
};
|
||
} catch (_) {}
|
||
async function connect() {
|
||
if (connecting || dev) return;
|
||
if (Date.now() < installerUntil) { sayK("instbusy"); return; }
|
||
connecting = true;
|
||
let connectedDevice = null;
|
||
wantConnected = true;
|
||
if (!MOCK && !EMU && !navigator.requestMIDIAccess) { connecting = false; sayK("nomidi"); return; }
|
||
$("connect").disabled = true;
|
||
sayK("connecting");
|
||
try {
|
||
if (!access) {
|
||
if (MOCK) { mock = makeMockDevice({ legacy: QS.get("legacy") === "1", hostPower: QS.get("hp") === "1", /* (?hp=1: a big CPU, ?board=1: an SMK-37) */
|
||
board: +QS.get("board") || 0, portName: QS.get("port") || undefined }); access = mock.access; }
|
||
else {
|
||
try { access = EMU ? EMU.emuMidi() : await navigator.requestMIDIAccess({ sysex: true }); }
|
||
catch (e) { sayK("denied"); return; }
|
||
}
|
||
access.onstatechange = onState;
|
||
}
|
||
await portsClosing;
|
||
renderMidiPorts();
|
||
for (const p of [...access.inputs.values(), ...access.outputs.values()]) portStates.set(p.id, p.state);
|
||
const opened = await openEditorMidi(access, {
|
||
onUnknown: f => console.debug("ignored reply", f), onTimeout: () => sayK("noreply"),
|
||
onPush: f => onPush(f), onGap: () => { rewatch = true; },
|
||
}, {input: $("midiinput").value, output: $("midioutput").value});
|
||
dev = { ...opened, pdesc: [], gdesc: [], names: [], dump: null, steps: [], slotUsed: [null, null, null, null],
|
||
keys: null, watch: false, bank: null };
|
||
connectedDevice = dev;
|
||
setLabel($("connect"), t("disconnect"));
|
||
await load(connectedDevice);
|
||
if (connectedDevice === dev) {
|
||
connectedDevice.screen = await screenSupported(connectedDevice);
|
||
renderScreenBtn();
|
||
if (connectedDevice.screen && QS.has("screen")) openMirror(); /* (?screen: straight to the screen, a phone's bookmark) */
|
||
}
|
||
} catch (e) {
|
||
console.error(e);
|
||
if (!connectedDevice || connectedDevice === dev) {
|
||
const timeout = /^timeout/.test(e.message);
|
||
if (connectedDevice) disconnect();
|
||
if (e.message === "no MIDI ports") $("midiports").open = true;
|
||
const notFound = e.message === "no MIDI ports" || /^Not a JIANT/.test(e.message) || timeout;
|
||
sayK(notFound ? "nodevice" : "error", notFound ? (seenPorts ? ` (${t("portsSeen")} ${seenPorts})` : ` (${t("portsNone")})`) : e.message);
|
||
}
|
||
} finally {
|
||
connecting = false;
|
||
$("connect").disabled = false;
|
||
}
|
||
}
|
||
|
||
function disconnect(reasonKey = "disconnected") {
|
||
if (dev) {
|
||
dev.link.close();
|
||
dev.input.onmidimessage = null;
|
||
portsClosing = Promise.allSettled([dev.input.close?.(), dev.output.close?.()]);
|
||
}
|
||
dev = null;
|
||
closeMirror(false);
|
||
renderScreenBtn();
|
||
resetBusy();
|
||
needReload = false;
|
||
renderPanels();
|
||
renderMixer();
|
||
renderSysinfo();
|
||
renderLive();
|
||
renderLib();
|
||
renderBank();
|
||
renderPreferences(true);
|
||
$("version").textContent = "";
|
||
setLabel($("connect"), t("connect"));
|
||
sayK(reasonKey);
|
||
}
|
||
|
||
function onState(e) {
|
||
const p = e.port;
|
||
if (!p) return;
|
||
const chosen = p.id === $("midiinput").value || p.id === $("midioutput").value || dev && (p.id===dev.input.id || p.id===dev.output.id);
|
||
if (!chosen && !editorPort({name:p.name,state:"connected"})) return;
|
||
if (portStates.get(p.id) === p.state) return; /* open/close is not a physical reconnect */
|
||
portStates.set(p.id, p.state);
|
||
renderMidiPorts();
|
||
if (dev && p.state === "disconnected" && (p.id === dev.input.id || p.id === dev.output.id)) {
|
||
disconnect("lost");
|
||
} else if (!dev && wantConnected && p.state === "connected" && p.type === "output") {
|
||
clearTimeout(onState.tm); /* the device came back: reconnect */
|
||
onState.tm = setTimeout(() => { if (!dev && wantConnected) connect(); }, 800);
|
||
}
|
||
}
|
||
|
||
function assertSession(d) { if (!d || d !== dev) throw new Error("closed"); }
|
||
async function sessionRequest(d, r, opt) {
|
||
assertSession(d);
|
||
const reply = await d.link.request(r, opt);
|
||
assertSession(d);
|
||
return reply;
|
||
}
|
||
const rq = (r, opt) => sessionRequest(dev, r, opt);
|
||
async function getDesc(scope, id, d = dev) { return parse[CMD.DESC](await sessionRequest(d, req.desc(scope, id))); }
|
||
async function getDump(d = dev) { const reply = await sessionRequest(d, req.dump()); lastDump = Date.now(); return parse[CMD.DUMP](reply, d.info); }
|
||
async function getStep(i, d = dev) { return parse[CMD.STEP_GET](await sessionRequest(d, req.stepGet(i, !!(d && d.info && d.info.laneModes)))); }
|
||
|
||
/* the whole connect sequence */
|
||
async function load(d) {
|
||
const releaseBusy = beginBusy();
|
||
try {
|
||
/* the first frame after opening the port can be lost: a few tries */
|
||
d.info = d.info || parse[CMD.INFO](await sessionRequest(d, req.info(), { timeout: 800, retries: 3 }));
|
||
$("version").textContent = d.info.version;
|
||
const total = d.info.pcount + d.info.gcount;
|
||
for (let i = 0; i < d.info.pcount; i++) { sayK("reading", `${i + 1}/${total}`); d.pdesc[i] = await getDescOrNull(0, i, d); }
|
||
for (let i = 0; i < d.info.gcount; i++) { sayK("reading", `${d.info.pcount + i + 1}/${total}`); d.gdesc[i] = await getDescOrNull(1, i, d); }
|
||
d.titles = [];
|
||
for (let e = 0; e < d.info.nengines; e++) {
|
||
const r = parse[CMD.NAMES](await sessionRequest(d, req.names(e)));
|
||
d.names[e] = r.names;
|
||
d.titles[e] = r.titles;
|
||
}
|
||
for (let k = 0; k < 4; k++) { /* PROJECT op 2: is the slot used */
|
||
try { d.slotUsed[k] = parse[CMD.PROJECT](await sessionRequest(d, req.project(2, k))).used; }
|
||
catch (e) { if (e.message === "closed") throw e; }
|
||
}
|
||
d.keys = paramKeys(d.pdesc, d.info.pe0, d.info.pcount);
|
||
await libAdopt(d);
|
||
assertSession(d);
|
||
if (d.info.ntrk) d.sel = parse[CMD.TRACK](await sessionRequest(d, req.track())).sel; /* v3: the selected track */
|
||
d.dump = await getDump(d);
|
||
if (d.info.chainRows) d.song = parse[CMD.SONG](await sessionRequest(d, req.song()));
|
||
buildUI();
|
||
renderPanels();
|
||
await loadSteps(d);
|
||
if (d.info.ntrk) await readMixer(d);
|
||
/* protocol v2: live pushes and the user bank; older firmware: DUMP polling, no bank */
|
||
const rqd = (r, o) => sessionRequest(d, r, o);
|
||
d.watch = await startWatch(rqd);
|
||
d.v4 = d.watch === 3; /* TRACK_PARAM / TRACK_CHANGED */
|
||
if (d.watch) {
|
||
sayK("readingBank");
|
||
try { d.bank = await bank.list((r, o) => sessionRequest(d, r, { ...o, quiet: true })); }
|
||
catch (e) { if (e.message === "closed") throw e; d.bank = null; }
|
||
}
|
||
await syncPreferences(d);
|
||
renderLive();
|
||
renderLib();
|
||
renderBank();
|
||
renderSysinfo();
|
||
sayK("ready");
|
||
} finally { releaseBusy(); }
|
||
}
|
||
async function getDescOrNull(s, i, d = dev) { try { return await getDesc(s, i, d); } catch (e) { if (e.message === "closed") throw e; return null; } }
|
||
|
||
/* rebuilds the controls only when the engine or its parameters changed (a slider being dragged survives) */
|
||
const HP_ALL = [...new Set(Object.keys(HP_PAGES).flatMap(hpIds))];
|
||
async function rereadEngineDesc(d = dev) {
|
||
assertSession(d);
|
||
const pe0 = d.info.pe0;
|
||
const before = JSON.stringify(d.pdesc.slice(pe0));
|
||
for (let i = 0; i < 8 && pe0 + i < d.info.pcount; i++) d.pdesc[pe0 + i] = await getDescOrNull(0, pe0 + i, d);
|
||
/* (ports/) the values a big CPU keeps in other engines' slots: their descriptors are the track engine's (and its
|
||
SAMPLE TRIG's: AMOUNT's name); read again for every engine that has them, and when leaving one (the slots' own) */
|
||
const hpBefore = JSON.stringify(HP_ALL.map((i) => d.pdesc[i]));
|
||
if (d.info.hostPower) for (const i of HP_ALL) if (i < d.info.pcount) d.pdesc[i] = await getDescOrNull(0, i, d);
|
||
if (d.built !== d.dump.engine || JSON.stringify(d.pdesc.slice(pe0)) !== before || JSON.stringify(HP_ALL.map((i) => d.pdesc[i])) !== hpBefore) buildGroups();
|
||
}
|
||
|
||
async function loadSteps(d = dev) {
|
||
assertSession(d);
|
||
const n = d.info.nstep;
|
||
for (let i = 0; i < n; i++) {
|
||
if (i % 8 === 0) sayK("steploading", `${i}/${n}`);
|
||
d.steps[i] = await getStep(i, d);
|
||
}
|
||
renderSteps();
|
||
if (d.info.motionMax) await readMotion(d);
|
||
}
|
||
|
||
/* --------------------------------------------------------------- UI --- */
|
||
function buildUI() {
|
||
const sel = $("engine");
|
||
/* (engine 1, "-": DIGITAL retired, reserved: never offered) */
|
||
sel.replaceChildren(...engineOrder(dev.info.engines).map((i) => el("option", { value: i, text: dev.info.engines[i] }))); /* (shown order) */
|
||
dev.mix = null;
|
||
buildGroups();
|
||
updateBrowser();
|
||
renderSlots();
|
||
renderSysinfo();
|
||
fm6List = null;
|
||
fm6Asked = false;
|
||
fm6Picked = -1;
|
||
renderFm6();
|
||
}
|
||
|
||
/* the track selector (v3): the four parts; the editor shows the selected one */
|
||
function renderTrackbar() {
|
||
const box = $("trackbtns");
|
||
const ntrk = hasTracks() ? dev.info.ntrk : 0;
|
||
if (box.children.length !== ntrk || box.dataset.lang !== lang) {
|
||
box.dataset.lang = lang;
|
||
box.replaceChildren(...Array.from({ length: ntrk }, (_, i) => el("button", { type: "button", "data-i": i,
|
||
onclick: () => selectTrack(i) }, String(i + 1))));
|
||
}
|
||
for (const b of box.children) b.setAttribute("aria-pressed", +b.dataset.i === (dev.sel || 0) ? "true" : "false");
|
||
}
|
||
function selectTrack(i) {
|
||
if (!dev || !hasTracks() || i === dev.sel) return;
|
||
op(async () => {
|
||
dev.sel = parse[CMD.TRACK](await rq(req.track(i))).sel;
|
||
await afterSoundChange();
|
||
});
|
||
}
|
||
|
||
/* settings > system: what the device reported */
|
||
function renderSysinfo() {
|
||
const box = $("sysinfo");
|
||
if (!dev || !dev.info) { box.replaceChildren(); return; }
|
||
const i = dev.info;
|
||
$("version").textContent = `${deviceName(i, dev.input && dev.input.name)} · ${i.version}`; /* (SMK-37, ports/) which device */
|
||
const rows = [
|
||
["deviceL", deviceName(i, dev.input && dev.input.name)], ["firmware", i.version], ["sync", t(dev.watch ? "live" : "polling")], ["enginesL", i.engines.join(", ")],
|
||
["tracksN", i.ntrk ? String(i.ntrk) : "1"], ["stepsN", String(i.nstep)],
|
||
["userBank", dev.bank ? String(dev.bank.total) : t("none")],
|
||
];
|
||
box.replaceChildren(...rows.map(([k, v]) => el("tr", {}, el("th", { text: t(k) }), el("td", { text: v }))));
|
||
}
|
||
|
||
/* (0.8.5) the VOICE track's lyric (LYRIC, cmd 39): shown for a VOICE track on a firmware that has it */
|
||
function lyricShown() { return !!dev && !!dev.info && !!dev.info.lyric && !!dev.dump && dev.info.engines[dev.dump.engine] === "VOICE"; }
|
||
async function lyricRead(d = dev) {
|
||
if (!lyricShown()) return;
|
||
const r = parse[CMD.LYRIC](await rq(req.lyric(d.sel || 0)));
|
||
if (document.activeElement !== $("lyric")) $("lyric").value = r.text;
|
||
}
|
||
$("lyricsend").addEventListener("click", () => {
|
||
if (!lyricShown()) return;
|
||
op(async () => {
|
||
const r = parse[CMD.LYRIC](await rq(req.lyric(dev.sel || 0, $("lyric").value)));
|
||
$("lyric").value = r.text;
|
||
sayK("lyricSent");
|
||
});
|
||
});
|
||
/* LANG (P_VLANG, id 61) and LYRIC (P_VLYR, id 74): VOICE's words, in other engines' slots (sing.c) */
|
||
const LYR_LANG = ["OFF", "ES", "EN", "JA"];
|
||
const LYR_SRC = ["TEXT", ...Array.from({ length: 16 }, (_, i) => `W${i + 1}`), ...Array.from({ length: 8 }, (_, i) => `S${i + 1}`)];
|
||
const LYR_ID = { lang: 61, src: 74 };
|
||
for (const [id, names, key] of [["lyrlang", LYR_LANG, "lang"], ["lyrsrc", LYR_SRC, "src"]]) {
|
||
$(id).replaceChildren(...names.map((n, i) => el("option", { value: i, text: n })));
|
||
$(id).addEventListener("change", () => {
|
||
if (!lyricShown()) return;
|
||
op(async () => { parse[CMD.SET](await rq(req.set(0, LYR_ID[key], +$(id).value))); dev.dump = await getDump(); refreshAll(); });
|
||
});
|
||
}
|
||
function updateBrowser() {
|
||
const e = dev.dump.engine;
|
||
const sel = $("engine");
|
||
$("lyricbox").hidden = !lyricShown();
|
||
if (lyricShown()) {
|
||
if (document.activeElement !== $("lyrlang")) $("lyrlang").value = String(Math.max(0, Math.min(3, dev.dump.p[LYR_ID.lang] | 0)));
|
||
if (document.activeElement !== $("lyrsrc")) $("lyrsrc").value = String(Math.max(0, Math.min(24, dev.dump.p[LYR_ID.src] | 0)));
|
||
}
|
||
renderTrackbar();
|
||
if (document.activeElement !== sel) sel.value = String(e);
|
||
const ps = $("preset");
|
||
const names = dev.names[e] || [];
|
||
if (ps.dataset.engine !== String(e)) {
|
||
ps.replaceChildren(...names.map((n, i) => el("option", { value: i, text: n, hidden: aliasOf(names, i) !== i })));
|
||
ps.dataset.engine = String(e);
|
||
}
|
||
if (document.activeElement !== ps) ps.value = String(dev.dump.preset);
|
||
}
|
||
|
||
function visible(d) { return d && d.max > d.min && d.label !== "-"; }
|
||
/* a matrix destination E1..E8 by the engine's label of that parameter (as the device shows it) */
|
||
function modDst(d, txt) {
|
||
const m = d && /^DST\d$/.test(d.label) && /^E([1-8])$/.exec(txt);
|
||
const e = m && dev && dev.pdesc[dev.info.pe0 + +m[1] - 1];
|
||
return e && visible(e) ? e.label : txt;
|
||
}
|
||
|
||
function buildGroups() {
|
||
ctl.clear();
|
||
dev.built = dev.dump.engine;
|
||
/* Sound: the selected track's parameters; Sequencer: its pattern settings; Settings: globals */
|
||
const groups = { groups: [], seqgroups: [], setgroups: [] };
|
||
const { info } = dev;
|
||
if (knownLayout(info)) {
|
||
for (const g of LAYOUT(info.pe0)) {
|
||
const div = el("div", { class: "group" }, el("h2", { ic: HEAD_IC[g.t], text: g.engine ? `EDIT ${info.engines[dev.dump.engine] || ""}` : g.t }));
|
||
if (g.mod != null) { /* MOD: slot number, SRC, DST, AMT in one row */
|
||
for (let k = 0; k < 4; k++) {
|
||
const r = [0, 1, 2].map((j) => paramRow(0, g.mod + 3 * k + j));
|
||
if (r.some((x) => !x)) continue;
|
||
const row = el("div", { class: "row modrow" }, el("span", { text: String(k + 1) }), r[0].children[1], r[1].children[1],
|
||
r[2].children[1], r[2].children[2]);
|
||
for (let j = 0; j < 3; j++) ctl.get(key(0, g.mod + 3 * k + j)).row = row; /* (the push highlight) */
|
||
div.append(row);
|
||
}
|
||
groups.groups.push(div);
|
||
continue;
|
||
}
|
||
for (const [title, s, ids] of g.pages) {
|
||
const rows = ids.map((id) => paramRow(s, id)).filter(Boolean);
|
||
if (!rows.length) continue;
|
||
const tt = g.engine && (dev.titles[dev.dump.engine] || [])[g.pages.findIndex((x) => x[0] === title)];
|
||
if (g.pages.length > 1) div.append(el("h3", { ic: PAGE_IC[tt || title], text: tt || title }));
|
||
div.append(...rows);
|
||
}
|
||
groups[g.tab || "groups"].push(div);
|
||
}
|
||
} else {
|
||
/* unknown firmware layout: everything in id order */
|
||
const a = el("div", { class: "group" }, el("h2", { ic: HEAD_IC.INSTRUMENT, text: "INSTRUMENT" }), el("p", { class: "dim", text: t("layout") }));
|
||
const b = el("div", { class: "group" }, el("h2", { ic: HEAD_IC.EDIT, text: "EDIT" }));
|
||
const c = el("div", { class: "group" }, el("h2", { ic: HEAD_IC.GLOBAL, text: "GLOBAL" }));
|
||
for (let i = 0; i < info.pcount; i++) { const r = paramRow(0, i); if (r) (i >= info.pe0 ? b : a).append(r); }
|
||
for (let i = 0; i < info.gcount; i++) { const r = paramRow(1, i); if (r) c.append(r); }
|
||
groups.groups.push(a, b);
|
||
groups.setgroups.push(c);
|
||
}
|
||
for (const [id, divs] of Object.entries(groups)) $(id).replaceChildren(...divs);
|
||
}
|
||
|
||
function paramRow(s, id) {
|
||
const d = s ? dev.gdesc[id] : dev.pdesc[id];
|
||
if (!visible(d) || (s === 1 && G_SKIP.has(d.label))) return null;
|
||
if (!s && d.label === "PHASE" && d.min === -1 && d.fmt === F.INT) return lfoModeRows(id, d);
|
||
const k = key(s, id);
|
||
let input;
|
||
if (d.fmt === F.ENUM || d.fmt === F.NOTE || d.fmt === F.ONOFF) {
|
||
const wave = RICH_SELECT && d.fmt === F.ENUM && /^WAVE2?$/.test(d.label);
|
||
input = el("select", { class: wave ? "wave" : null });
|
||
/* the closed select shows a copy of the chosen option (icon span included), not its bare text */
|
||
if (wave) input.append(el("button", {}, el("selectedcontent")));
|
||
for (const v of enumShown(d)) { /* (note divisions longest first: #48) */
|
||
const [txt] = fmtValue(d, v);
|
||
const name = d.fmt === F.ENUM && d.names[v - d.min] == null ? String(v) : modDst(d, txt);
|
||
const alias = d.fmt === F.ENUM && aliasOf(d.names, v - d.min) !== v - d.min; /* shown when set, not offered */
|
||
input.append(el("option", { value: v, ic: wave && WAVE_IC[name], hidden: alias }, name));
|
||
}
|
||
input.addEventListener("change", () => userSet(s, id, +input.value, true));
|
||
} else {
|
||
input = el("input", { type: "range", min: d.min, max: d.max, step: 1 });
|
||
input.addEventListener("pointerdown", () => { dragging = k; });
|
||
input.addEventListener("input", () => userSet(s, id, +input.value, false));
|
||
input.addEventListener("change", () => userSet(s, id, +input.value, true));
|
||
input.addEventListener("dblclick", () => { input.value = d.def; userSet(s, id, d.def, true); });
|
||
/* fine adjust: wheel over the focused slider, Shift+arrows in steps of 10 (plain arrows are native) */
|
||
const nudge = (dv) => {
|
||
const nv = Math.max(d.min, Math.min(d.max, +input.value + dv));
|
||
if (nv !== +input.value) { input.value = String(nv); userSet(s, id, nv, true); }
|
||
};
|
||
let acc = 0;
|
||
input.addEventListener("wheel", (e) => {
|
||
if (document.activeElement !== input) return;
|
||
e.preventDefault();
|
||
acc += (e.deltaMode === 1 ? 33 : 1) * (Math.abs(e.deltaY) >= Math.abs(e.deltaX) ? -e.deltaY : e.deltaX);
|
||
const n = Math.trunc(acc / 50);
|
||
if (n) { acc -= n * 50; nudge(n * (e.shiftKey ? 10 : 1)); }
|
||
}, { passive: false });
|
||
input.addEventListener("keydown", (e) => {
|
||
const dir = { ArrowUp: 1, ArrowRight: 1, ArrowDown: -1, ArrowLeft: -1 }[e.key];
|
||
if (!dir || !e.shiftKey) return;
|
||
e.preventDefault();
|
||
nudge(dir * 10);
|
||
});
|
||
}
|
||
input.title = d.label;
|
||
const out = el("span", { class: "v" });
|
||
const row = el("div", { class: "row" }, el("span", { text: d.label }), input, out);
|
||
ctl.set(k, { input, out, desc: d, scope: s, id, row });
|
||
showValue(k, s ? dev.dump.g[id] : dev.dump.p[id], true);
|
||
return row;
|
||
}
|
||
|
||
/* (0.9.18) the LFO's PHASE as the device's pages show it: MODE TRIG / FREE (FREE is PHASE -1, as stored since 0.6.51) and
|
||
PHASE 0..127, TRIG's start (dimmed in FREE: the phase TRIG had is kept here for TRIG again) */
|
||
function lfoModeRows(id, d) {
|
||
const k = key(0, id);
|
||
const mode = el("select", {}, el("option", { value: 0 }, "TRIG"), el("option", { value: 1 }, "FREE"));
|
||
const ph = el("input", { type: "range", min: 0, max: d.max, step: 1 });
|
||
const mout = el("span", { class: "v" }), out = el("span", { class: "v" });
|
||
const c = { input: ph, out, desc: d, scope: 0, id, mem: 0 };
|
||
c.show = (v, force) => {
|
||
if (v >= 0) c.mem = v;
|
||
mode.value = v < 0 ? "1" : "0";
|
||
mout.textContent = v < 0 ? "FREE" : "TRIG";
|
||
ph.disabled = v < 0;
|
||
out.textContent = String(c.mem);
|
||
if (force || !touched(k)) ph.value = String(c.mem);
|
||
};
|
||
mode.addEventListener("change", () => userSet(0, id, +mode.value ? -1 : c.mem, true));
|
||
ph.addEventListener("pointerdown", () => { dragging = k; });
|
||
ph.addEventListener("input", () => userSet(0, id, +ph.value, false));
|
||
ph.addEventListener("change", () => userSet(0, id, +ph.value, true));
|
||
mode.title = "MODE";
|
||
ph.title = "PHASE";
|
||
const rows = [el("div", { class: "row" }, el("span", { text: "MODE" }), mode, mout),
|
||
el("div", { class: "row" }, el("span", { text: "PHASE" }), ph, out)];
|
||
c.row = rows[1];
|
||
ctl.set(k, c);
|
||
c.show(dev.dump.p[id], true);
|
||
const f = document.createDocumentFragment();
|
||
f.append(...rows);
|
||
return f;
|
||
}
|
||
|
||
function showValue(k, v, force) {
|
||
const c = ctl.get(k);
|
||
if (!c || v == null) return;
|
||
if (c.show) return c.show(v, force);
|
||
const [txt0, unit] = fmtValue(c.desc, v), txt = modDst(c.desc, txt0);
|
||
c.out.textContent = unit ? `${txt} ${unit}` : txt;
|
||
if (force || !touched(k)) c.input.value = String(v);
|
||
}
|
||
/* the user is working on this control: polling and pushes must not move it */
|
||
function touched(k) {
|
||
const c = ctl.get(k), st = sets.get(k);
|
||
if (dragging === k) return true;
|
||
if (c && c.input.tagName === "SELECT" && document.activeElement === c.input) return true;
|
||
if (st && performance.now() - st.last < 600) return true;
|
||
return !!dev && (dev.link.hasQueued(k) || (!!dev.link.cur && dev.link.cur.key === k));
|
||
}
|
||
|
||
window.addEventListener("pointerup", () => { if (dragging) { const k = dragging; dragging = null; const c = ctl.get(k); if (c) userSet(c.scope, c.id, +c.input.value, true); } });
|
||
window.addEventListener("pointercancel", () => { dragging = null; });
|
||
|
||
/* SET as fast as the device answers: one SET per control in flight and at most one queued, which
|
||
always carries the latest value (Link coalesces by key), so a drag never builds a backlog */
|
||
function userSet(s, id, v, final) {
|
||
if (!dev) return;
|
||
const k = key(s, id);
|
||
(s ? dev.dump.g : dev.dump.p)[id] = v;
|
||
showValue(k, v, false);
|
||
mixFromDump();
|
||
let st = sets.get(k);
|
||
if (!st) sets.set(k, (st = { last: 0, sent: null }));
|
||
st.last = performance.now();
|
||
if (v === st.sent) return; /* the last request already carries it */
|
||
sendSet(s, id, k);
|
||
}
|
||
async function sendSet(s, id, k) {
|
||
if (!dev) return;
|
||
const st = sets.get(k);
|
||
const v = (s ? dev.dump.g : dev.dump.p)[id];
|
||
st.sent = v;
|
||
try {
|
||
const r = parse[CMD.SET](await rq(req.set(s, id, v), { key: k }));
|
||
if (dev && dragging !== k && st.sent === v && !dev.link.hasQueued(k)) { /* the device's value after clamping */
|
||
(s ? dev.dump.g : dev.dump.p)[id] = r.value;
|
||
showValue(k, r.value, false);
|
||
mixFromDump();
|
||
}
|
||
if (!s && dev && (id === dev.info.pe0 || dev.info.hostPower && hpIds(engName())[0] === id)) { dev.dump = await getDump(); await rereadEngineDesc(); refreshAll(); } /* (ports/: SAMPLE's TRIG names AMOUNT) */ /* (V10.40) WAVE / EXCITE / MODE:
|
||
* some knobs change name and range (ANALOG SAW3's INT 3, STRING FDBK) */
|
||
} catch (e) { if (e.message !== "closed") console.warn(e); }
|
||
}
|
||
|
||
/* engine / preset browser */
|
||
$("engine").addEventListener("change", () => choosePreset(+$("engine").value, 0));
|
||
$("preset").addEventListener("change", () => { if (dev) choosePreset(dev.dump.engine, +$("preset").value); });
|
||
async function choosePreset(e, p) {
|
||
if (!dev) return;
|
||
const releaseBusy = beginBusy();
|
||
try {
|
||
selfLoad(true);
|
||
parse[CMD.PRESET](await rq(req.preset(e, p)));
|
||
await afterSoundChange();
|
||
} catch (err) { report(err); } finally { releaseBusy(); }
|
||
}
|
||
async function afterSoundChange(msg = "ready", d = dev) {
|
||
assertSession(d);
|
||
needReload = false; /* this re-reads everything a RELOAD asks for */
|
||
d.dump = await getDump(d);
|
||
await rereadEngineDesc(d);
|
||
updateBrowser();
|
||
refreshAll();
|
||
await loadSteps(d); /* (a sound load keeps them; read anyway after a RELOAD) */
|
||
roll.stale = true;
|
||
if (roll.open && hasTracks()) await rollRead(d.sel || 0);
|
||
if (hasTracks()) await readMixer(d); /* the sound names and the selected strip */
|
||
await lyricRead(d); /* (0.8.5) a VOICE track's lyric */
|
||
sayK(msg);
|
||
}
|
||
$("init").addEventListener("click", async () => {
|
||
if (!dev || !confirm(t("confirmInit"))) return;
|
||
const releaseBusy = beginBusy();
|
||
try { selfLoad(true); await rq(req.set(1, gEng(), dev.dump.engine)); await afterSoundChange(); }
|
||
catch (err) { report(err); } finally { releaseBusy(); }
|
||
});
|
||
|
||
function refreshAll() {
|
||
for (const [k, c] of ctl) showValue(k, c.scope ? dev.dump.g[c.id] : dev.dump.p[c.id], false);
|
||
renderSteps();
|
||
}
|
||
function report(err) { if (err && err.message !== "closed") { console.warn(err); sayK("error", err.message); } }
|
||
|
||
/* projects: the protocol cannot ask whether a slot is used without loading or saving it */
|
||
function renderSlots() {
|
||
renderSong();
|
||
renderBackup();
|
||
const box = $("slots");
|
||
box.replaceChildren();
|
||
for (let i = 0; i < 4; i++) {
|
||
const u = dev.slotUsed[i];
|
||
box.append(el("span", { text: String.fromCharCode(65 + i) }),
|
||
el("span", { class: "dim", text: u == null ? t("unknown") : t(u ? "used" : "empty") }),
|
||
el("button", { ic: "symbol_folder_open", onclick: () => project(0, i) }, t("load")),
|
||
el("button", { ic: "port_disk", onclick: () => project(1, i) }, t("save")));
|
||
}
|
||
}
|
||
async function project(op, slot) {
|
||
if (!dev) return;
|
||
if (!confirm(t(op ? "confirmSave" : "confirmLoad").replace("{n}", slot + 1))) return;
|
||
const releaseBusy = beginBusy();
|
||
try {
|
||
/* save writes flash: a long timeout and no retry */
|
||
if (!op) selfLoad();
|
||
const r = parse[CMD.PROJECT](await rq(req.project(op, slot), { timeout: 4000, retries: 0 }));
|
||
dev.slotUsed[slot] = r.used;
|
||
renderSlots();
|
||
if (!op && r.used) await afterSoundChange();
|
||
if (dev.info.chainRows) { dev.song = parse[CMD.SONG](await rq(req.song())); renderSong(); }
|
||
sayK(op ? "savedSlot" : r.used ? "loadedSlot" : "emptySlot", String(slot + 1));
|
||
} catch (err) { report(err); } finally { releaseBusy(); }
|
||
}
|
||
|
||
function renderSong() {
|
||
const box = $("songchain");
|
||
box.hidden = !dev || !dev.info?.chainRows || !dev.song;
|
||
if (box.hidden) return;
|
||
const s = dev.song;
|
||
$("songplay").textContent = t(s.playing ? "songStop" : "songPlay");
|
||
$("songadd").disabled = !!s.playing || s.rows.length >= 16;
|
||
$("songremove").disabled = !!s.playing || !s.rows.length;
|
||
$("songstatus").textContent = s.playing ? `${t("songPlaying")} ${s.row + 1}/${s.count} · ${s.remaining} ${t("songReps")}` : s.count ? "" : t("songEmpty");
|
||
const rows = $("songrows");
|
||
if (rows.contains(document.activeElement)) return;
|
||
rows.replaceChildren();
|
||
s.rows.forEach((r, i) => {
|
||
const line = el("div", { class: "bar", style: "margin:8px 0" });
|
||
line.append(el("span", { text: String(i + 1) }));
|
||
const sel = el("select", { disabled: !!s.playing, "aria-label": `${t("slot")} ${i + 1}` });
|
||
for (let k = 0; k < 4; k++) sel.append(el("option", { value: k, text: `${t("slot")} ${k + 1}${dev.slotUsed[k] ? "" : ` (${t("empty")})`}` }));
|
||
sel.value = String(r.slot);
|
||
sel.addEventListener("change", () => { const next = s.rows.map((x) => ({ ...x })); next[i].slot = +sel.value; op(() => changeSong(1, next)); });
|
||
const reps = el("input", { type: "number", min: 1, max: 64, value: r.repeat, disabled: !!s.playing, style: "width:64px", "aria-label": `${t("songReps")} ${i + 1}` });
|
||
reps.addEventListener("change", () => { const v = +reps.value; if (!Number.isInteger(v) || v < 1 || v > 64) { reps.value = r.repeat; return; } const next = s.rows.map((x) => ({ ...x })); next[i].repeat = v; op(() => changeSong(1, next)); });
|
||
line.append(sel, reps, el("span", { text: t("songReps") }));
|
||
rows.append(line);
|
||
});
|
||
}
|
||
async function changeSong(action, rows = []) {
|
||
const r = parse[CMD.SONG](await rq(req.song(action, rows)));
|
||
if (r.rc) throw new Error(r.rc >= 3 ? `${t("slot")} ${r.rc - 2}: ${t("empty")}` : t(r.rc === 2 ? "songBusy" : "songInvalid"));
|
||
dev.song = r;
|
||
renderSong();
|
||
if (action === 1) sayK("songSaved");
|
||
}
|
||
$("songplay").addEventListener("click", () => op(() => changeSong(dev.song?.playing ? 3 : 2)));
|
||
$("songadd").addEventListener("click", () => op(() => changeSong(1, [...dev.song.rows, { slot: dev.song.rows.at(-1)?.slot || 0, repeat: 1 }])));
|
||
$("songremove").addEventListener("click", () => op(() => changeSong(1, dev.song.rows.slice(0, -1))));
|
||
setInterval(async () => {
|
||
if (!dev?.info?.chainRows || busy || document.hidden || !dev.link.idle || tab !== "projects") return;
|
||
const releaseBusy = beginBusy();
|
||
const d = dev;
|
||
try { const r = parse[CMD.SONG](await rq(req.song())); if (d === dev) { d.song = r; renderSong(); } }
|
||
catch (err) { report(err); } finally { releaseBusy(); }
|
||
}, 1000);
|
||
|
||
/* Complete archives remain on this computer; no project is uploaded to a server. */
|
||
function renderBackup() {
|
||
const caps = dev?.info?.backupCaps || 0;
|
||
$("backup-export").disabled = !(caps & 1);
|
||
$("backup-import").disabled = !(caps & 2);
|
||
$("backup-help").textContent = t(caps & 1 ? "backupHelp" : "backupOld");
|
||
}
|
||
const backupModule = () => import("./fm1backup.js");
|
||
const backupProgress = (done, total) => sayK("backupWorking", `${Math.round(done / Math.max(1, total) * 100)}%`);
|
||
$("backup-export").addEventListener("click", () => op(async () => {
|
||
const d = dev;
|
||
if (!(d?.info?.backupCaps & 1)) return;
|
||
const { captureBackup } = await backupModule();
|
||
assertSession(d);
|
||
const file = await captureBackup((r, o) => sessionRequest(d, r, o), d.info.version, backupProgress);
|
||
assertSession(d);
|
||
download(`JIANT-backup-${new Date().toISOString().slice(0, 10)}.json`, file);
|
||
sayK("backupDone");
|
||
}));
|
||
$("backup-import").addEventListener("click", () => { if (dev?.info?.backupCaps & 2) $("backup-file").click(); });
|
||
$("backup-file").addEventListener("change", () => {
|
||
const file = $("backup-file").files[0], d = dev; $("backup-file").value = "";
|
||
if (!file || !(d?.info?.backupCaps & 2)) return;
|
||
op(async () => {
|
||
if (file.size > 600000) throw new Error("Backup file too large");
|
||
const { readBackup, restoreBackup } = await backupModule();
|
||
const archive = readBackup(await file.text()); assertSession(d);
|
||
if (!confirm(t("backupConfirm"))) return;
|
||
await restoreBackup((r, o) => sessionRequest(d, r, o), archive, backupProgress);
|
||
await load(d); sayK("backupRestored");
|
||
});
|
||
});
|
||
|
||
async function readMotion(d = dev) {
|
||
assertSession(d);
|
||
if (!d.info.motionMax) { $("motion-panel").hidden = true; return; }
|
||
const selected = d.sel ?? 0;
|
||
const m = parse[CMD.MOTION](await sessionRequest(d, req.motion(selected)));
|
||
if (m.rc || m.track !== selected) throw new Error("Invalid motion state");
|
||
d.motion = m; renderMotion();
|
||
}
|
||
function renderMotion() {
|
||
const d = dev, m = d?.motion;
|
||
$("motion-panel").hidden = !d?.info?.motionMax;
|
||
if (!m) return;
|
||
$("motion-on").checked = m.on;
|
||
$("motion-count").textContent = `${m.count} / ${m.max}`;
|
||
$("motion-clear").disabled = !m.count;
|
||
const rows = $("motion-rows");
|
||
if (rows.contains(document.activeElement)) return;
|
||
rows.replaceChildren(el("tr", {}, ...["motionStep", "motionParam", "motionValue"].map(k => el("th", {text:t(k)})), el("th")),
|
||
...m.events.map(e => {
|
||
const desc = e.param === 127 ? d.gdesc[17] : d.pdesc[e.param], label = desc?.label || `P${e.param}`; /* (0.9.1: 127 the DJ FILTER's) */
|
||
const value = el("input", {type:"number",min:desc?.min ?? -8192,max:desc?.max ?? 8191,value:e.value,"aria-label":`${e.step + 1} ${label}`});
|
||
value.addEventListener("change", () => op(async () => {
|
||
assertSession(d);
|
||
const r = parse[CMD.MOTION](await sessionRequest(d, req.motion(m.track, 3, {...e,value:+value.value})));
|
||
if (r.rc) throw new Error("Automation edit refused"); d.motion = r; renderMotion();
|
||
}));
|
||
return el("tr", {}, el("td", {text:e.step + 1}), el("td", {text:label}), el("td", {}, value),
|
||
el("td", {}, el("button", {text:t("remove"),onclick:() => op(async () => {
|
||
const r = parse[CMD.MOTION](await sessionRequest(d, req.motion(m.track, 4, e)));
|
||
if (r.rc) throw new Error("Automation edit refused"); d.motion = r; renderMotion();
|
||
})})));
|
||
}));
|
||
}
|
||
$("motion-on").addEventListener("change", () => op(async () => {
|
||
const d = dev, track = d?.sel ?? 0;
|
||
if (!d?.info?.motionMax) return;
|
||
const r = parse[CMD.MOTION](await sessionRequest(d, req.motion(track, 1, {on:$("motion-on").checked})));
|
||
if (r.rc) throw new Error("Automation edit refused"); d.motion = r; renderMotion();
|
||
}));
|
||
$("motion-clear").addEventListener("click", () => op(async () => {
|
||
const d = dev;
|
||
if (!d?.info?.motionMax || !confirm(t("motionConfirm"))) return;
|
||
const r = parse[CMD.MOTION](await sessionRequest(d, req.motion(d.sel ?? 0, 2)));
|
||
if (r.rc) throw new Error("Automation edit refused"); d.motion = r; renderMotion();
|
||
}));
|
||
setInterval(async () => {
|
||
const d = dev;
|
||
if (!d?.info?.motionMax || busy || document.hidden || tab !== "sequencer" || !d.link.idle) return;
|
||
const release = beginBusy();
|
||
try { await readMotion(d); } catch (e) { report(e); } finally { release(); }
|
||
}, 1500);
|
||
|
||
/* ---------------------------------------------------------- steps --- */
|
||
const TIMES = ["NOTE", "TIE", "REST"];
|
||
function renderStepHead() { if (dev && dev.steps.length) renderSteps(); }
|
||
const stepLen = () => Math.max(1, Math.min(dev.info.nstep, dev.dump.p[pSlen()] || 16));
|
||
/* a step's notes as text */
|
||
const stepNotes = (s) => s.notes.slice(0, s.n).map(noteName).join(" ");
|
||
const stepOn = (s) => !!s && s.time === 0 && (s.n > 0 || (s.hit | 0) > 0);
|
||
function renderSteps() {
|
||
if (!dev || !dev.steps.length) return;
|
||
const len = stepLen();
|
||
const box = $("steptables");
|
||
const shape = String(len);
|
||
$("noteshelp").textContent = t("notesHelp");
|
||
renderGrid();
|
||
/* keep the rows the user is typing in */
|
||
if (box.contains(document.activeElement) && box.dataset.len === shape) { updateStepRows(); return; }
|
||
box.dataset.len = shape;
|
||
const tables = [];
|
||
for (let b = 0; b < len; b += 16) {
|
||
const tb = el("table", {}, el("tr", {}, el("th"), el("th", { text: t("notes") }), el("th", { text: t("hits") }), el("th", { text: t("time") }),
|
||
el("th", { text: t("acc") }), el("th", { text: t("slide") }), el("th", { text: t("vel") }), ...(dev.info.chance ? [el("th", { text: t("chance") })] : []),
|
||
...(dev.info.ratchet ? [el("th", { text: t("ratchet") })] : [])));
|
||
for (let i = b; i < Math.min(len, b + 16); i++) tb.append(stepRow(i));
|
||
tables.push(tb);
|
||
}
|
||
box.replaceChildren(...tables);
|
||
}
|
||
function stepRow(i) {
|
||
const notes = el("input", { type: "text", placeholder: "—", spellcheck: "false" });
|
||
const hits = el("input", { type: "text", placeholder: "—", spellcheck: "false", class: "hits" });
|
||
const time = el("select", {}, ...TIMES.map((n, k) => el("option", { value: k, text: n })));
|
||
const acc = el("input", { type: "checkbox" });
|
||
const sl = el("input", { type: "checkbox" });
|
||
const vel = el("input", { type: "number", min: 0, max: 127 });
|
||
const chance = dev.info.chance ? el("input", { type: "number", min: 0, max: 100, "aria-label": `${t("chance")} ${i + 1}` }) : null;
|
||
const ratchet = dev.info.ratchet ? el("select", { "aria-label": `${t("ratchet")} ${i + 1}` },
|
||
...Array.from({ length: dev.info.ratchet }, (_, k) => el("option", { value: k + 1, text: `x${k + 1}` }))) : null;
|
||
const tr = el("tr", { "data-i": i }, el("td", { class: "i", text: String(i + 1) }),
|
||
el("td", {}, notes), el("td", {}, hits), el("td", {}, time), el("td", {}, acc), el("td", {}, sl), el("td", {}, vel), ...(chance ? [el("td", {}, chance)] : []),
|
||
...(ratchet ? [el("td", {}, ratchet)] : []));
|
||
tr._c = { notes, hits, time, acc, sl, vel, chance, ratchet };
|
||
fillStep(tr, dev.steps[i]);
|
||
const send = () => writeStep(i, tr);
|
||
notes.addEventListener("change", send);
|
||
hits.addEventListener("change", send);
|
||
time.addEventListener("change", send);
|
||
acc.addEventListener("change", send);
|
||
sl.addEventListener("change", send);
|
||
vel.addEventListener("change", send);
|
||
if (chance) chance.addEventListener("change", send);
|
||
if (ratchet) ratchet.addEventListener("change", send);
|
||
return tr;
|
||
}
|
||
function fillStep(tr, s) {
|
||
const c = tr._c;
|
||
if (!s) return;
|
||
c.notes.value = stepNotes(s);
|
||
c.notes.classList.remove("bad");
|
||
c.hits.value = hitsText(s.hit | 0, s.acc | 0);
|
||
c.hits.classList.remove("bad");
|
||
c.time.value = String(s.time);
|
||
c.acc.checked = !!(s.flags & 1);
|
||
c.sl.checked = !!(s.flags & 2);
|
||
c.vel.value = String(s.vel);
|
||
if (c.chance) c.chance.value = String(s.chance ?? 100);
|
||
if (c.ratchet) c.ratchet.value = String(s.ratchet ?? 1);
|
||
tr.classList.toggle("off", !stepOn(s));
|
||
}
|
||
function updateStepRows() {
|
||
for (const tr of $("steptables").querySelectorAll("tr[data-i]")) {
|
||
if (tr.contains(document.activeElement)) continue;
|
||
fillStep(tr, dev.steps[+tr.dataset.i]);
|
||
}
|
||
renderGrid();
|
||
}
|
||
/* the step grid: one cell per step up to LEN; a cell jumps to its row in the table */
|
||
function renderGrid() {
|
||
const box = $("stepgrid");
|
||
if (!dev || !dev.steps.length) { box.replaceChildren(); return; }
|
||
const len = stepLen();
|
||
if (box.children.length !== len) {
|
||
box.replaceChildren(...Array.from({ length: len }, (_, i) => el("button", { type: "button", "data-i": i, onclick: () => focusStep(i) })));
|
||
}
|
||
for (const b of box.children) {
|
||
const i = +b.dataset.i, s = dev.steps[i];
|
||
const on = stepOn(s), tie = !!s && s.time === 1;
|
||
const txt = on ? [stepNotes(s), hitsText(s.hit | 0, s.acc | 0)].filter(Boolean).join(" ") : tie ? "—" : "";
|
||
const marks = s && on ? (s.flags & 1 ? " >" : "") + (s.flags & 2 ? " ~" : "") + (s.ratchet > 1 ? " x" + s.ratchet : "") : "";
|
||
b.className = [on && "on", tie && "tie", on && s.flags & 1 && "acc", i % 4 === 0 && "beat"].filter(Boolean).join(" ");
|
||
b.title = `${i + 1}: ${on ? txt : tie ? "TIE" : "REST"}${marks}`;
|
||
b.replaceChildren(el("span", { class: "n", text: String(i + 1) + marks }), el("span", { class: "x", text: txt }));
|
||
}
|
||
}
|
||
function focusStep(i) {
|
||
const tr = $("steptables").querySelector(`tr[data-i="${i}"]`);
|
||
if (!tr) return;
|
||
tr.scrollIntoView({ block: "center", behavior: "smooth" });
|
||
tr._c.notes.focus({ preventScroll: true });
|
||
tr.classList.add("hl");
|
||
setTimeout(() => tr.classList.remove("hl"), 1200);
|
||
}
|
||
async function writeStep(i, tr) {
|
||
const c = tr._c;
|
||
const notes = parseNotes(c.notes.value), hits = parseHits(c.hits.value);
|
||
c.notes.classList.toggle("bad", !notes);
|
||
c.hits.classList.toggle("bad", !hits);
|
||
if (!notes || !hits) return;
|
||
const old = dev.steps[i];
|
||
const all = notes.concat(old.notes.slice(notes.length)).slice(0, 4);
|
||
let time = +c.time.value;
|
||
if ((notes.length || hits.hit) && !old.n && !old.hit && time === 2) time = 0; /* typing notes / hits into an empty step makes it play */
|
||
const s = { n: notes.length, notes: all, time, flags: (c.acc.checked ? 1 : 0) | (c.sl.checked ? 2 : 0),
|
||
vel: Math.max(0, Math.min(127, +c.vel.value || 0)), hit: hits.hit, acc: hits.acc };
|
||
if (c.chance) s.chance = Math.max(0, Math.min(100, Math.round(+c.chance.value || 0)));
|
||
if (c.ratchet && c.chance) s.ratchet = Math.max(1, Math.min(4, +c.ratchet.value || 1));
|
||
if ((s.n || s.hit) && !s.vel) s.vel = 96;
|
||
stepEdit.set(i, performance.now());
|
||
try {
|
||
dev.steps[i] = parse[CMD.STEP_SET](await rq(req.stepSet(i, s)));
|
||
if (!tr.contains(document.activeElement) || document.activeElement === c.notes) fillStep(tr, dev.steps[i]);
|
||
} catch (err) { report(err); }
|
||
}
|
||
$("reloadsteps").addEventListener("click", async () => {
|
||
if (!dev) return;
|
||
const releaseBusy = beginBusy();
|
||
try { await loadSteps(); sayK("ready"); } catch (err) { report(err); } finally { releaseBusy(); }
|
||
});
|
||
$("clearseq").addEventListener("click", async () => {
|
||
if (!dev || !confirm(t("confirmClear"))) return;
|
||
const releaseBusy = beginBusy();
|
||
try {
|
||
for (let i = 0; i < dev.info.nstep; i++) {
|
||
if (i % 8 === 0) sayK("applying", `${i}/${dev.info.nstep}`);
|
||
dev.steps[i] = parse[CMD.STEP_SET](await rq(req.stepSet(i, { n: 0, notes: [0, 0, 0, 0], time: 2, flags: 0, vel: 0, hit: 0, acc: 0, ...(dev.info.chance ? {chance:100} : {}), ...(dev.info.ratchet ? {ratchet:1} : {}) })));
|
||
}
|
||
if (dev.info.motionMax) { dev.motion = parse[CMD.MOTION](await rq(req.motion(dev.sel ?? 0, 2))); renderMotion(); }
|
||
$("steptables").dataset.len = "";
|
||
renderSteps();
|
||
sayK("ready");
|
||
} catch (err) { report(err); } finally { releaseBusy(); }
|
||
});
|
||
|
||
/* ---------------------------------------------------------- mixer (v3) --- */
|
||
/* dev.mix = TRACK reply + pan per track ({sel, ntrk, tracks: [{engine, preset, level, mute, armed, pan}]}).
|
||
Read on connect, after every RELOAD / sound change, with the slow safety DUMP and when the tab opens.
|
||
The selected track's level / pan / mute are also Sound parameters: both views follow each other. */
|
||
let mixDrag = null; /* "lv:i" / "pan:i" while a strip control is dragged */
|
||
const mixEdit = new Map(); /* "lv:i" / "pan:i" -> time of the user's last change */
|
||
const mixCtl = []; /* per track: the strip's elements */
|
||
let panning = false; /* v3 firmware: another track is selected for a moment (pan of a track that is not selected) */
|
||
const mixTouched = (kind, i) => mixDrag === `${kind}:${i}` || performance.now() - (mixEdit.get(`${kind}:${i}`) || 0) < 600
|
||
|| (!!dev && kind === "lv" && dev.link.hasQueued("mix:" + i))
|
||
|| (kind === "pan" && (panWant.has(i) || (!!dev && dev.link.hasQueued("pan:" + i))));
|
||
function trackName(x) {
|
||
return [dev.info.engines[x.engine], (dev.names[x.engine] || [])[x.preset]].filter(Boolean).join(" ");
|
||
}
|
||
|
||
async function readMixer(d = dev) {
|
||
assertSession(d);
|
||
if (!d || !hasTracks()) return;
|
||
const m = await mixer.read((r, o) => sessionRequest(d, r, o), d.info, { pan: pPan() });
|
||
if (d !== dev) return;
|
||
if (d.mix) m.tracks.forEach((x, i) => { /* what the user is moving stays */
|
||
const o = d.mix.tracks[i];
|
||
if (!o) return;
|
||
if (mixTouched("lv", i)) { x.level = o.level; x.mute = o.mute; }
|
||
if (mixTouched("pan", i)) x.pan = o.pan;
|
||
});
|
||
d.mix = m;
|
||
if (m.sel !== d.sel && !panning) { d.sel = m.sel; needReload = true; } /* selected on the device, push missed */
|
||
renderMixer();
|
||
}
|
||
|
||
/* the Sound view's values of the selected track -> the strips */
|
||
function mixFromDump() {
|
||
if (!dev || !dev.mix || !dev.dump || panning) return;
|
||
const m = dev.mix, x = m.tracks[dev.sel];
|
||
if (x) {
|
||
if (!mixTouched("lv", dev.sel)) {
|
||
x.level = dev.dump.p[P.LEVEL];
|
||
x.mute = dev.dump.p[pMute()] ? 1 : 0;
|
||
}
|
||
if (!mixTouched("pan", dev.sel)) x.pan = dev.dump.p[pPan()];
|
||
}
|
||
if (mixCtl.length === m.ntrk) m.tracks.forEach((_, i) => updateStrip(i));
|
||
}
|
||
/* a strip's values -> the Sound view (the selected track) */
|
||
function mixToSound(i) {
|
||
const x = dev.mix.tracks[i];
|
||
const put = (s, id, v) => { if (v == null) return; (s ? dev.dump.g : dev.dump.p)[id] = v; showValue(key(s, id), v, false); };
|
||
if (i !== dev.sel) return;
|
||
put(0, P.LEVEL, x.level);
|
||
put(0, pMute(), x.mute ? 1 : 0);
|
||
put(0, pPan(), x.pan);
|
||
}
|
||
|
||
function renderMixer() {
|
||
const box = $("mixer");
|
||
if (!dev || !dev.mix) { box.replaceChildren(); mixCtl.length = 0; return; }
|
||
const m = dev.mix;
|
||
if (mixCtl.length !== m.ntrk || box.dataset.lang !== lang) {
|
||
box.dataset.lang = lang;
|
||
mixCtl.length = 0;
|
||
box.replaceChildren(...m.tracks.map((_, i) => buildStrip(i)));
|
||
}
|
||
m.tracks.forEach((_, i) => updateStrip(i));
|
||
}
|
||
function buildStrip(i) {
|
||
const lvDesc = dev.pdesc[P.LEVEL] || { fmt: F.INT, min: 0, max: 127, def: 100 };
|
||
const pDesc = dev.pdesc[pPan()] || { fmt: F.BIPCT, min: -64, max: 63, def: 0 };
|
||
const fader = el("input", { type: "range", class: "fader", min: 0, max: 127, step: 1, "aria-label": `${t("level")} ${i + 1}` });
|
||
fader.addEventListener("pointerdown", () => { mixDrag = "lv:" + i; });
|
||
fader.addEventListener("input", () => setLevel(i, +fader.value));
|
||
fader.addEventListener("change", () => setLevel(i, +fader.value));
|
||
fader.addEventListener("dblclick", () => setLevel(i, Math.max(0, Math.min(127, lvDesc.def))));
|
||
const pan = el("input", { type: "range", class: "pan", min: pDesc.min, max: pDesc.max, step: 1, "aria-label": `${t("pan")} ${i + 1}` });
|
||
pan.addEventListener("pointerdown", () => { mixDrag = "pan:" + i; });
|
||
pan.addEventListener("input", () => setPan(i, +pan.value, false));
|
||
pan.addEventListener("change", () => setPan(i, +pan.value, true));
|
||
pan.addEventListener("dblclick", () => setPan(i, pDesc.def, true));
|
||
const c = {
|
||
lvDesc, pDesc, fader, pan,
|
||
num: el("button", { type: "button", class: "tog num", title: t("selectTrack"), onclick: () => selectTrack(i) }, String(i + 1)),
|
||
snd: el("div", { class: "snd" }),
|
||
rec: el("span", { class: "rec", ic: "control_rec_f", title: t("rec") }, t("rec")),
|
||
lvOut: el("span", { class: "v lv" }),
|
||
mute: el("button", { type: "button", class: "tog", ic: "control_speaker_mute", onclick: () => setMute(i, !dev.mix.tracks[i].mute) }, t("mute")),
|
||
panOut: el("span", { class: "v" }),
|
||
selb: el("button", { type: "button", class: "selb", onclick: () => selectTrack(i) }),
|
||
};
|
||
c.strip = el("div", { class: "strip", role: "group", "aria-label": `${t("track")} ${i + 1}` },
|
||
c.num, c.snd, c.rec, fader, c.lvOut, c.mute, el("span", { class: "v dim", ic: "symbol_pan" }, t("pan")), pan, c.panOut, c.selb);
|
||
mixCtl[i] = c;
|
||
return c.strip;
|
||
}
|
||
function updateStrip(i) {
|
||
const c = mixCtl[i], x = dev && dev.mix && dev.mix.tracks[i];
|
||
if (!c || !x) return;
|
||
const sel = i === dev.sel;
|
||
c.strip.classList.toggle("sel", sel);
|
||
c.num.setAttribute("aria-pressed", sel ? "true" : "false");
|
||
const nm = trackName(x);
|
||
c.snd.textContent = nm;
|
||
c.snd.title = nm;
|
||
if (!mixTouched("lv", i)) c.fader.value = String(x.level);
|
||
const [lt, lu] = fmtValue(c.lvDesc, x.level);
|
||
c.lvOut.textContent = lu ? `${lt} ${lu}` : lt;
|
||
c.mute.setAttribute("aria-pressed", x.mute ? "true" : "false");
|
||
c.strip.classList.toggle("muted", !!x.mute || !x.level);
|
||
c.pan.disabled = x.pan == null;
|
||
if (x.pan != null) {
|
||
if (!mixTouched("pan", i)) c.pan.value = String(x.pan);
|
||
const [pt, pu] = fmtValue(c.pDesc, x.pan);
|
||
c.panOut.textContent = pu ? `${pt} ${pu}` : pt;
|
||
}
|
||
c.rec.classList.toggle("on", !!x.armed);
|
||
c.selb.disabled = sel;
|
||
c.selb.textContent = t(sel ? "selectedTrack" : "selectTrack");
|
||
}
|
||
window.addEventListener("pointerup", () => { mixDrag = null; });
|
||
window.addEventListener("pointercancel", () => { mixDrag = null; });
|
||
|
||
/* level and mute: TRACK_MIX, one in flight per track and one queued with the latest values (as SET) */
|
||
function setLevel(i, v) {
|
||
if (!dev || !dev.mix) return;
|
||
dev.mix.tracks[i].level = v;
|
||
mixEdit.set("lv:" + i, performance.now());
|
||
updateStrip(i);
|
||
mixToSound(i);
|
||
sendMix(i);
|
||
}
|
||
function setMute(i, on) {
|
||
if (!dev || !dev.mix) return;
|
||
dev.mix.tracks[i].mute = on ? 1 : 0;
|
||
mixEdit.set("lv:" + i, performance.now());
|
||
updateStrip(i);
|
||
mixToSound(i);
|
||
sendMix(i);
|
||
}
|
||
async function sendMix(i) {
|
||
const d = dev, x = d.mix.tracks[i];
|
||
try {
|
||
const r = await mixer.setMix(rq, i, x.level, x.mute, { key: "mix:" + i });
|
||
if (d !== dev || !d.mix || mixDrag === "lv:" + i || d.link.hasQueued("mix:" + i)) return;
|
||
const y = d.mix.tracks[i]; /* the device's values after clamping */
|
||
y.level = r.level; y.mute = r.mute;
|
||
updateStrip(i);
|
||
mixToSound(i);
|
||
} catch (e) { report(e); }
|
||
}
|
||
/* pan: the selected track as any Sound parameter; another track with TRACK_PARAM (v4: while dragging, one in
|
||
flight and one queued with the latest value), or with v3 firmware on release (it is selected for a moment) */
|
||
const panWant = new Map();
|
||
function setPan(i, v, final) {
|
||
if (!dev || !dev.mix) return;
|
||
dev.mix.tracks[i].pan = v;
|
||
mixEdit.set("pan:" + i, performance.now());
|
||
updateStrip(i);
|
||
if (i === dev.sel) { userSet(0, pPan(), v, final); return; }
|
||
if (dev.v4) panTrack(i, v);
|
||
else if (final) panOther(i, v);
|
||
}
|
||
async function panTrack(i, v) {
|
||
const d = dev;
|
||
try {
|
||
const r = await mixer.setPan(rq, i, d.sel, pPan(), v, true);
|
||
if (d !== dev || !d.mix || mixDrag === "pan:" + i || d.link.hasQueued("pan:" + i)) return;
|
||
d.mix.tracks[i].pan = r; /* the device's value after clamping */
|
||
updateStrip(i);
|
||
if (i === d.sel) mixToSound(i);
|
||
} catch (e) { report(e); }
|
||
}
|
||
async function panOther(i, v) {
|
||
panWant.set(i, v);
|
||
if (panOther.run) return;
|
||
panOther.run = true;
|
||
const d = dev;
|
||
try {
|
||
while (busy && d === dev) await sleep(20); /* not in the middle of another multi-request operation */
|
||
assertSession(d);
|
||
const releaseBusy = beginBusy();
|
||
panning = true;
|
||
try {
|
||
while (panWant.size && d === dev) {
|
||
const [tr, val] = panWant.entries().next().value;
|
||
panWant.delete(tr);
|
||
const r = await mixer.setPan(rq, tr, d.sel, pPan(), val);
|
||
if (d.mix && !panWant.has(tr)) { d.mix.tracks[tr].pan = r; updateStrip(tr); }
|
||
}
|
||
} finally { panning = false; releaseBusy(); }
|
||
} catch (e) { report(e); } finally { panOther.run = false; panWant.clear(); }
|
||
}
|
||
|
||
/* ------------------------------------------------- live sync / polling --- */
|
||
/* With WATCH (protocol v2) the device pushes CHANGED / RELOAD / STEP_CHANGED; the editor PINGs about
|
||
once a second so the watch stays on (it ends 3 s after the last request), and DUMPs every 5 s as a
|
||
safety net. Older firmware: DUMP every 400 ms and two steps per round. */
|
||
function onPush(f) {
|
||
const d = dev;
|
||
if (f.cmd === CMD.SCREEN_DATA) { onScreenData(f); return; }
|
||
if (!d || !d.dump || !d.info) return;
|
||
try {
|
||
if (f.cmd === CMD.CHANGED) {
|
||
const c = parse[CMD.CHANGED](f.a);
|
||
if (panning && !c.scope) return; /* about the track selected for a moment, not ours */
|
||
const arr = c.scope ? d.dump.g : d.dump.p;
|
||
if (c.id >= arr.length) return;
|
||
const k = key(c.scope, c.id);
|
||
if (touched(k)) return; /* the user's value wins; their SET follows */
|
||
const old = arr[c.id];
|
||
arr[c.id] = c.value;
|
||
showValue(k, c.value, false);
|
||
blink(k);
|
||
mixFromDump();
|
||
if (!c.scope && c.id === pSlen() && old !== c.value) { $("steptables").dataset.len = ""; renderSteps(); }
|
||
} else if (f.cmd === CMD.RELOAD) {
|
||
d.sel = parse[CMD.RELOAD](f.a).track; /* v3: another track may be selected on the device */
|
||
if (selfReload.n > 0 && Date.now() < selfReload.until) { selfReload.n--; return; }
|
||
needReload = true;
|
||
maybeReload();
|
||
} else if (f.cmd === CMD.STEP_CHANGED) {
|
||
const { index } = parse[CMD.STEP_CHANGED](f.a);
|
||
if (index < d.info.nstep) refreshStep(index);
|
||
if (roll.open && roll.track === (d.sel || 0) && index < d.info.nstep) rollRefreshStep(index);
|
||
} else if (f.cmd === CMD.TRACK_CHANGED) { /* v4: level / pan / mute of a track that is not selected */
|
||
const c = parse[CMD.TRACK_CHANGED](f.a), x = d.mix && d.mix.tracks[c.track];
|
||
if (!x || c.track === d.sel) return;
|
||
if (c.id === pPan()) { if (!mixTouched("pan", c.track)) x.pan = c.value; }
|
||
else if (c.id === pMute()) { if (!mixTouched("lv", c.track)) x.mute = c.value ? 1 : 0; }
|
||
else if (c.id === P.LEVEL) { if (!mixTouched("lv", c.track)) x.level = c.value; }
|
||
else return;
|
||
updateStrip(c.track);
|
||
}
|
||
} catch (e) { console.warn("bad push", f, e); }
|
||
}
|
||
function blink(k) {
|
||
const c = ctl.get(k);
|
||
if (!c || !c.row) return;
|
||
c.row.classList.add("pushed");
|
||
clearTimeout(c.blink);
|
||
c.blink = setTimeout(() => c.row.classList.remove("pushed"), 400);
|
||
}
|
||
async function refreshStep(i) {
|
||
const d = dev;
|
||
try {
|
||
const s = parse[CMD.STEP_GET](await rq(req.stepGet(i), { key: "step:" + i }));
|
||
if (d !== dev || s.index !== i) return;
|
||
d.steps[i] = s;
|
||
updateStepRows();
|
||
} catch (err) { report(err); }
|
||
}
|
||
function maybeReload() {
|
||
if (!dev || busy || !needReload || !dev.dump) return;
|
||
op(() => afterSoundChange("reloaded"));
|
||
}
|
||
/* one multi-request operation; polling waits for it */
|
||
async function op(fn) {
|
||
if (!dev) return;
|
||
const releaseBusy = beginBusy();
|
||
try { await fn(); } catch (err) { report(err); } finally { releaseBusy(); }
|
||
}
|
||
function renderLive() {
|
||
$("live").textContent = !dev || !dev.dump ? "" : t(dev.watch ? "live" : "polling");
|
||
}
|
||
|
||
/* keep-alive: PING when nothing else went out for ~1 s; after a longer gap (hidden tab, a long flash
|
||
write: Link.onGap) the watch may have ended: WATCH again and re-read what may have been missed */
|
||
let rewatch = false;
|
||
async function keepAlive() {
|
||
const d = dev;
|
||
if (!d || !d.watch || !d.dump || document.hidden) return;
|
||
const gap = Date.now() - d.link.lastSent;
|
||
if (rewatch || gap > 2500) {
|
||
if (keepAlive.run) return;
|
||
keepAlive.run = true;
|
||
try {
|
||
const on = await startWatch((r, o) => sessionRequest(d, r, o));
|
||
assertSession(d);
|
||
rewatch = false; /* (this WATCH itself may have flagged the gap) */
|
||
if (on) { d.v4 = on === 3; needReload = true; maybeReload(); }
|
||
else if (d === dev) { d.watch = false; renderLive(); }
|
||
} catch (e) { /* closed */ } finally { keepAlive.run = false; }
|
||
} else if (gap > 850 && d.link.idle) {
|
||
d.link.request(req.ping(), { key: "ping", quiet: true, retries: 0 }).catch(() => {});
|
||
}
|
||
}
|
||
setInterval(keepAlive, 1000);
|
||
|
||
/* ------------------------------------------------------- screen mirror --- */
|
||
/* SCREEN 1 turns it on: the device redraws its whole screen and sends every fill and strip it draws (SCREEN_DATA,
|
||
scrDecode) into mirror.fb, painted once per animation frame. SCREEN 2 every second keeps it on (the device stops
|
||
by itself 4 s after the editor's last request: a closed tab, a phone gone to sleep); back in view, SCREEN 1 again. */
|
||
const mirror = { on: false, fb: new Uint16Array(SCR.W * SCR.H), ctx: null, img: null, lut: null, dirty: null, raf: 0,
|
||
timer: 0, bytes: 0, rateT: 0, rate: 0, got: false, lock: null };
|
||
function mirrorLut() {
|
||
const lut = new Uint32Array(65536);
|
||
for (let c = 0; c < 65536; c++) {
|
||
const r = ((c >> 11) & 31) * 255 / 31 | 0, g = ((c >> 5) & 63) * 255 / 63 | 0, b = (c & 31) * 255 / 31 | 0;
|
||
lut[c] = 0xFF000000 | b << 16 | g << 8 | r; /* (ImageData's bytes R G B A, little-endian) */
|
||
}
|
||
return lut;
|
||
}
|
||
function onScreenData(f) {
|
||
if (!mirror.on) return;
|
||
const box = scrDecode(f.a, mirror.fb);
|
||
if (!box) return;
|
||
mirror.bytes += f.a.length + 6;
|
||
mirror.got = true;
|
||
const d = mirror.dirty;
|
||
mirror.dirty = !d ? box : { x: Math.min(d.x, box.x), y: Math.min(d.y, box.y),
|
||
w: Math.max(d.x + d.w, box.x + box.w) - Math.min(d.x, box.x), h: Math.max(d.y + d.h, box.y + box.h) - Math.min(d.y, box.y) };
|
||
if (!mirror.raf) mirror.raf = requestAnimationFrame(mirrorPaint);
|
||
}
|
||
function mirrorPaint() {
|
||
mirror.raf = 0;
|
||
const d = mirror.dirty;
|
||
if (!d || !mirror.ctx) return;
|
||
mirror.dirty = null;
|
||
const px = new Uint32Array(mirror.img.data.buffer), fb = mirror.fb, lut = mirror.lut;
|
||
for (let y = d.y; y < d.y + d.h; y++)
|
||
for (let i = y * SCR.W + d.x, e = i + d.w; i < e; i++) px[i] = lut[fb[i]];
|
||
mirror.ctx.putImageData(mirror.img, 0, 0, d.x, d.y, d.w, d.h);
|
||
}
|
||
function mirrorStatus() {
|
||
const now = Date.now(), dt = now - mirror.rateT;
|
||
if (dt >= 1000) { mirror.rate = mirror.bytes * 1000 / dt; mirror.bytes = 0; mirror.rateT = now; }
|
||
$("mirrorstat").textContent = !mirror.got ? t("screenWait") : (mirror.rate / 1024).toFixed(1) + t("screenRate");
|
||
}
|
||
async function screenSupported(d) {
|
||
try { return parse[CMD.SCREEN](await sessionRequest(d, req.screen(0), { timeout: 500, retries: 1, quiet: true })).rc === 0; }
|
||
catch (e) { return false; }
|
||
}
|
||
function renderScreenBtn() { $("screenbtn").hidden = !(dev && dev.screen); $("screenbtn").title = t("screenHelp"); }
|
||
async function mirrorWake() {
|
||
try { if (mirror.on && !mirror.lock && navigator.wakeLock && !document.hidden) {
|
||
mirror.lock = await navigator.wakeLock.request("screen"); /* (the phone stays awake while it shows the screen) */
|
||
mirror.lock.addEventListener("release", () => { mirror.lock = null; });
|
||
} } catch (e) { /* not offered */ }
|
||
}
|
||
async function openMirror() {
|
||
const d = dev;
|
||
if (!d || !d.screen || mirror.on) return;
|
||
if (!mirror.ctx) {
|
||
const cv = $("mirrorcv");
|
||
mirror.ctx = cv.getContext("2d");
|
||
mirror.img = mirror.ctx.createImageData(SCR.W, SCR.H);
|
||
mirror.lut = mirrorLut();
|
||
}
|
||
mirror.fb.fill(0);
|
||
mirror.dirty = { x: 0, y: 0, w: SCR.W, h: SCR.H };
|
||
mirrorPaint();
|
||
mirror.on = true; mirror.got = false; mirror.bytes = 0; mirror.rateT = Date.now();
|
||
$("mirrorcv").setAttribute("aria-label", t("screenTitle") + " " + deviceName(d.info, d.input.name));
|
||
$("mirror").hidden = false;
|
||
document.body.classList.add("mirroring");
|
||
mirrorStatus();
|
||
mirrorWake();
|
||
$("mirrorclose").focus();
|
||
try {
|
||
const r = parse[CMD.SCREEN](await sessionRequest(d, req.screen(1), { timeout: 600, retries: 1 }));
|
||
if (r.rc || !r.on) { closeMirror(false); sayK("screenNo"); return; }
|
||
} catch (e) { closeMirror(false); report(e); return; }
|
||
clearInterval(mirror.timer);
|
||
mirror.timer = setInterval(async () => {
|
||
if (!mirror.on) return;
|
||
if (!dev || dev !== d) { closeMirror(false); return; }
|
||
mirrorStatus();
|
||
if (document.hidden || d.link.hasQueued("screen")) return;
|
||
try {
|
||
const r = parse[CMD.SCREEN](await sessionRequest(d, req.screen(2), { key: "screen", quiet: true, retries: 0 }));
|
||
if (mirror.on && !r.on) await sessionRequest(d, req.screen(1), { key: "screen", quiet: true }); /* it stopped: again */
|
||
} catch (e) { /* the next one */ }
|
||
}, 1000);
|
||
}
|
||
function closeMirror(tell = true) {
|
||
if (!mirror.on && $("mirror").hidden) return;
|
||
mirror.on = false;
|
||
clearInterval(mirror.timer); mirror.timer = 0;
|
||
$("mirror").hidden = true;
|
||
document.body.classList.remove("mirroring");
|
||
if (mirror.lock) { mirror.lock.release().catch(() => {}); mirror.lock = null; }
|
||
const fs = document.fullscreenElement || document.webkitFullscreenElement;
|
||
if (fs === $("mirror")) (document.exitFullscreen || document.webkitExitFullscreen).call(document)?.catch?.(() => {});
|
||
if (tell && dev) dev.link.request(req.screen(4), { quiet: true, retries: 0 }).catch(() => {});
|
||
$("screenbtn").focus?.();
|
||
}
|
||
/* the screen on: full screen at once (the same click; a phone shows the FM-1's screen as big as it gets), Close or Esc
|
||
leave it */
|
||
$("screenbtn").addEventListener("click", () => {
|
||
const m = $("mirror");
|
||
if (document.fullscreenEnabled || document.webkitFullscreenEnabled) {
|
||
m.hidden = false; /* (it must show to go full screen; openMirror fills it) */
|
||
(m.requestFullscreen || m.webkitRequestFullscreen)?.call(m)?.catch?.(() => {});
|
||
}
|
||
openMirror();
|
||
});
|
||
$("mirrorclose").addEventListener("click", () => closeMirror());
|
||
$("mirrorsharp").addEventListener("click", (e) => {
|
||
const sharp = $("mirror").classList.toggle("smooth") === false;
|
||
e.currentTarget.setAttribute("aria-pressed", String(sharp));
|
||
try { localStorage.setItem("jiant.screen.smooth", sharp ? "0" : "1"); } catch (err) { /* private mode */ }
|
||
});
|
||
try { if (localStorage.getItem("jiant.screen.smooth") === "1") { $("mirror").classList.add("smooth"); $("mirrorsharp").setAttribute("aria-pressed", "false"); } }
|
||
catch (e) { /* private mode */ }
|
||
$("mirrorfull").addEventListener("click", () => {
|
||
const m = $("mirror"), fs = document.fullscreenElement || document.webkitFullscreenElement;
|
||
if (fs) (document.exitFullscreen || document.webkitExitFullscreen).call(document)?.catch?.(() => {});
|
||
else (m.requestFullscreen || m.webkitRequestFullscreen)?.call(m)?.catch?.(() => {});
|
||
});
|
||
$("mirrorfull").hidden = !(document.fullscreenEnabled || document.webkitFullscreenEnabled);
|
||
document.addEventListener("keydown", (e) => { if (e.key === "Escape" && mirror.on && !document.fullscreenElement) closeMirror(); });
|
||
document.addEventListener("visibilitychange", () => {
|
||
if (document.hidden || !mirror.on || !dev) return;
|
||
mirrorWake();
|
||
sessionRequest(dev, req.screen(1), { key: "screen", quiet: true }).catch(() => {}); /* (it may have stopped meanwhile) */
|
||
});
|
||
document.addEventListener("visibilitychange", () => { if (!document.hidden && dev && dev.watch) { rewatch = true; keepAlive(); } });
|
||
|
||
let stepRR = 0;
|
||
setInterval(async () => {
|
||
if (!dev || busy || dragging || document.hidden || !dev.dump || !dev.link.idle) return;
|
||
if (needReload) { maybeReload(); return; }
|
||
if (dev.watch && Date.now() - lastDump < 5000) return;
|
||
const releaseBusy = beginBusy();
|
||
const d = dev;
|
||
try {
|
||
const dump = await getDump();
|
||
if (d !== dev) return;
|
||
const soundChanged = dump.engine !== d.dump.engine || dump.preset !== d.dump.preset;
|
||
const engineChanged = dump.engine !== d.dump.engine || dump.p[d.info.pe0] !== d.dump.p[d.info.pe0]; /* (V10.40: or its
|
||
* WAVE / MODE, whose knobs can change: rereadEngineDesc rebuilds only if they did) */
|
||
const oldLen = d.dump.p[pSlen()];
|
||
for (const [k, c] of ctl) {
|
||
const v = c.scope ? dump.g[c.id] : dump.p[c.id];
|
||
if (touched(k)) { (c.scope ? dump.g : dump.p)[c.id] = c.scope ? d.dump.g[c.id] : d.dump.p[c.id]; continue; }
|
||
showValue(k, v, false);
|
||
}
|
||
d.dump = dump;
|
||
if (engineChanged) await rereadEngineDesc();
|
||
if (hasTracks()) await readMixer(); /* the strips (other tracks push nothing) */
|
||
if (soundChanged) { updateBrowser(); await loadSteps(); sayK("ready"); return; }
|
||
if (dump.p[pSlen()] !== oldLen) { $("steptables").dataset.len = ""; renderSteps(); }
|
||
if (d.watch) return; /* steps come as STEP_CHANGED */
|
||
/* steps are not in DUMP: follow them two at a time */
|
||
const len = Math.max(1, Math.min(d.info.nstep, dump.p[pSlen()] || 16));
|
||
for (let n = 0; n < 2; n++) {
|
||
stepRR = (stepRR + 1) % len;
|
||
if (performance.now() - (stepEdit.get(stepRR) || 0) < 1500) continue;
|
||
const s = await getStep(stepRR);
|
||
const o = d.steps[stepRR];
|
||
d.steps[stepRR] = s;
|
||
if (JSON.stringify(o) !== JSON.stringify(s)) updateStepRows();
|
||
}
|
||
} catch (err) { report(err); } finally { releaseBusy(); }
|
||
}, 400);
|
||
|
||
/* ------------------------------------------------ device preferences --- */
|
||
async function syncPreferences(d) {
|
||
if (!d || !d.info || !d.info.uiCaps) { renderPreferences(); return; }
|
||
const preferences = await readDevicePreferences((r, o) => sessionRequest(d, r, o), d.info, d.names, d.preferences);
|
||
if (dev !== d) return;
|
||
d.preferences = preferences;
|
||
if (preferences.slots) { d.bank = preferences.slots; renderBank(); }
|
||
renderPreferences();
|
||
}
|
||
function preferenceResult(rc) {
|
||
if (rc === 4) sayK("devicePending");
|
||
else if (rc === 3) sayK("deviceUnsaved");
|
||
else if (rc) throw new Error(t("deviceRejected"));
|
||
}
|
||
async function changePreference(id, value) {
|
||
const d = dev;
|
||
if (!d) return;
|
||
while (busy && d === dev) await sleep(20);
|
||
if (d !== dev) return;
|
||
await op(async () => {
|
||
const result = parse[CMD.UI_SET](await sessionRequest(d, req.uiSet(id, value), FLASH_OPT));
|
||
if (d !== dev) return;
|
||
await syncPreferences(d); preferenceResult(result.rc);
|
||
});
|
||
}
|
||
async function changeFavorite(row) {
|
||
const d = dev;
|
||
if (!d) return;
|
||
while (busy && d === dev) await sleep(20);
|
||
if (d !== dev) return;
|
||
await op(async () => {
|
||
const result = parse[CMD.FAV_SET](await sessionRequest(d, req.favSet(row.engine, row.preset, !row.favorite), FLASH_OPT));
|
||
if (d !== dev) return;
|
||
await syncPreferences(d); preferenceResult(result.rc);
|
||
});
|
||
}
|
||
function renderPreferences(force = false) {
|
||
const d = dev, p = d && d.preferences;
|
||
$("device-display").hidden = !p || !(p.state.caps & 7);
|
||
$("device-presets").hidden = !p || !(p.state.caps & 8);
|
||
if (!p) { renderPreferences.sig = null; return; }
|
||
const sig = JSON.stringify([p.state, p.palettes, lang, d.dump && d.dump.engine]);
|
||
if (!force && sig === renderPreferences.sig) return;
|
||
renderPreferences.sig = sig;
|
||
const defs = [
|
||
[0, "deviceTheme", p.palettes, p.state.palette],
|
||
[1, "deviceFont", [t("deviceRegular"), t("deviceBold")], p.state.font],
|
||
[2, "deviceMonitor", [t("deviceOff"), t("deviceEvents"), t("deviceNotes")], p.state.monitor],
|
||
];
|
||
const controls = [];
|
||
for (const [id, key, options, value] of defs) {
|
||
if (!(p.state.caps & (1 << id))) continue;
|
||
const select = el("select", { "aria-label": t(key) });
|
||
select.replaceChildren(...options.map((text, i) => el("option", { value: i, text })));
|
||
select.value = value;
|
||
select.addEventListener("change", () => changePreference(id, +select.value));
|
||
controls.push(el("label", { class: "bar" }, el("span", { text: t(key) }), select));
|
||
}
|
||
$("device-display-controls").replaceChildren(...controls);
|
||
if (!(p.state.caps & 8)) return;
|
||
const filter = $("device-filter");
|
||
filter.setAttribute("aria-label", t("deviceList"));
|
||
filter.replaceChildren(el("option", { value: 0, text: t("deviceAll") }), el("option", { value: 1, text: t("deviceFavorites") }));
|
||
filter.value = p.state.filter;
|
||
const rows = devicePresetRows(d.info, d.names, p);
|
||
const table = el("table");
|
||
table.append(el("colgroup", {}, el("col", { style: "width:40px" }), el("col"), el("col", { style: "width:110px" })));
|
||
for (const row of rows) {
|
||
const name = row.user ? slotName(row.preset) + " " + row.name : row.name;
|
||
const star = el("button", { text: row.favorite ? "\u2605" : "\u2606", "aria-label": t(row.favorite ? "deviceUnstar" : "deviceStar") + ": " + name, "aria-pressed": String(row.favorite) });
|
||
star.addEventListener("click", () => changeFavorite(row));
|
||
const load = el("button", { text: name });
|
||
load.addEventListener("click", () => { if (!dev || busy) return; row.user ? bankLoad(row.preset) : choosePreset(row.engine, row.preset); });
|
||
table.append(el("tr", {}, el("td", {}, star), el("td", {}, load), el("td", { text: row.user ? t("bank") : d.info.engines[row.engine] })));
|
||
}
|
||
$("device-preset-list").replaceChildren(rows.length ? table : el("p", { class: "dim", text: t("deviceEmpty") }));
|
||
}
|
||
$("device-filter").addEventListener("change", () => changePreference(3, +$("device-filter").value));
|
||
setInterval(() => {
|
||
if (!dev || !dev.preferences || busy || document.hidden || !["settings", "library"].includes(tab)) return;
|
||
const d = dev;
|
||
op(() => syncPreferences(d));
|
||
}, 1000);
|
||
|
||
/* ------------------------------------------------------------ files --- */
|
||
$("savefile").addEventListener("click", () => {
|
||
if (!dev) return;
|
||
const engine = dev.dump.engine, preset = dev.dump.preset;
|
||
const data = { format: "felucca-patch", version: 1, firmware: dev.info.version,
|
||
engineName: dev.info.engines[engine], presetName: (dev.names[engine] || [])[preset],
|
||
engine, preset, p: dev.dump.p.slice(), g: dev.dump.g.slice(),
|
||
steps: dev.steps.map((s) => ({ n: s.n, notes: s.notes.slice(), time: s.time, flags: s.flags, vel: s.vel })) };
|
||
download(`felucca-${fileSlug(data.engineName || "patch")}-${fileSlug(data.presetName || preset)}.json`, data);
|
||
});
|
||
$("loadfile").addEventListener("click", () => { $("file").value = ""; $("file").click(); });
|
||
$("file").addEventListener("change", async () => {
|
||
const f = $("file").files[0];
|
||
if (!f || !dev) return;
|
||
const session = dev;
|
||
let data;
|
||
try {
|
||
data = JSON.parse(await f.text());
|
||
assertSession(session);
|
||
if (!Number.isInteger(data.engine) || !Number.isInteger(data.preset) || !Array.isArray(data.p)) throw new Error("engine / preset / p");
|
||
if (data.engine < 0 || data.engine >= dev.info.nengines) throw new Error("engine " + data.engine);
|
||
} catch (e) { if (e.message !== "closed") sayK("badfile", e.message); return; }
|
||
const releaseBusy = beginBusy();
|
||
try {
|
||
selfLoad(true);
|
||
await rq(req.preset(data.engine, data.preset));
|
||
dev.dump = await getDump();
|
||
await rereadEngineDesc();
|
||
const n = Math.min(data.p.length, dev.info.pcount);
|
||
for (let i = 0; i < n; i++) {
|
||
const d = dev.pdesc[i];
|
||
if (!visible(d) || !Number.isFinite(data.p[i])) continue;
|
||
if (i % 8 === 0) sayK("applying", `${i}/${n}`);
|
||
await rq(req.set(0, i, data.p[i]));
|
||
}
|
||
if (Array.isArray(data.steps)) {
|
||
const m = Math.min(data.steps.length, dev.info.nstep);
|
||
for (let i = 0; i < m; i++) {
|
||
const s = data.steps[i] || {};
|
||
if (i % 8 === 0) sayK("applying", `steps ${i}/${m}`);
|
||
dev.steps[i] = parse[CMD.STEP_SET](await rq(req.stepSet(i, {
|
||
n: s.n | 0, notes: Array.isArray(s.notes) ? s.notes : [0, 0, 0, 0], time: s.time ?? 2, flags: s.flags | 0, vel: s.vel | 0 })));
|
||
}
|
||
}
|
||
dev.dump = await getDump();
|
||
updateBrowser();
|
||
$("steptables").dataset.len = "";
|
||
refreshAll();
|
||
sayK("applied");
|
||
} catch (err) { report(err); } finally { releaseBusy(); }
|
||
});
|
||
|
||
/* ----------------------------------------------------------- library --- */
|
||
/* Patches live in IndexedDB "felucca-editor": store "patches" (by id), store "meta" ("layout": the
|
||
parameter keys / engine names the stored values are in). Without IndexedDB (some private windows)
|
||
the library is kept in memory only. */
|
||
const store = (() => {
|
||
let dbp = null;
|
||
const open = () => dbp || (dbp = new Promise((res) => {
|
||
try {
|
||
const r = indexedDB.open("felucca-editor", 1);
|
||
r.onupgradeneeded = () => { r.result.createObjectStore("patches", { keyPath: "id" }); r.result.createObjectStore("meta"); };
|
||
r.onsuccess = () => res(r.result);
|
||
r.onerror = r.onblocked = () => res(null);
|
||
} catch (e) { res(null); }
|
||
}));
|
||
const tx = async (name, mode, fn) => {
|
||
const db = await open();
|
||
if (!db) return undefined;
|
||
return new Promise((res, rej) => {
|
||
const x = db.transaction(name, mode);
|
||
let out;
|
||
const r = fn(x.objectStore(name));
|
||
if (r) r.onsuccess = () => { out = r.result; };
|
||
x.oncomplete = () => res(out);
|
||
x.onerror = x.onabort = () => rej(x.error || new Error("IndexedDB"));
|
||
});
|
||
};
|
||
return {
|
||
ok: async () => !!(await open()),
|
||
all: () => tx("patches", "readonly", (os) => os.getAll()),
|
||
putMany: (ps) => tx("patches", "readwrite", (os) => { ps.forEach((p) => os.put(p)); }),
|
||
del: (id) => tx("patches", "readwrite", (os) => os.delete(id)),
|
||
getMeta: (k) => tx("meta", "readonly", (os) => os.get(k)),
|
||
setMeta: (k, v) => tx("meta", "readwrite", (os) => os.put(v, k)),
|
||
};
|
||
})();
|
||
|
||
let lib = []; /* patches (cleanPatch + id) */
|
||
let libMeta = { keys: null, engines: null, pe0: null };
|
||
let libPersistent = false;
|
||
let libSel = null, bankSel = null;
|
||
let libBusy = false; /* a library / bank operation is running */
|
||
const newId = () => (self.crypto && crypto.randomUUID ? crypto.randomUUID() : Date.now().toString(36) + Math.random().toString(36).slice(2));
|
||
const nowIso = () => new Date().toISOString();
|
||
const slotName = (i) => "U" + String(i + 1).padStart(2, "0");
|
||
const libCtx = () => (dev && dev.keys ? { keys: dev.keys, engines: dev.info.engines, firmware: dev.info.version, pe0: dev.info.pe0 }
|
||
: { keys: libMeta.keys, engines: libMeta.engines, firmware: "", pe0: libMeta.pe0 });
|
||
|
||
async function libInit() {
|
||
try {
|
||
libPersistent = await store.ok();
|
||
if (libPersistent) {
|
||
lib = ((await store.all()) || []).filter((p) => p && p.id);
|
||
libMeta = (await store.getMeta("layout")) || libMeta;
|
||
}
|
||
} catch (e) { console.warn(e); libPersistent = false; }
|
||
renderLib();
|
||
}
|
||
async function libWrite(ps) {
|
||
try { await store.putMany(ps); } catch (e) { console.warn(e); sayK("error", "IndexedDB: " + e.message); }
|
||
}
|
||
async function libAdd(patches) {
|
||
const add = patches.map((p) => ({ ...cleanPatch(p), id: newId() }));
|
||
lib.push(...add);
|
||
if (add.length) libSel = add[add.length - 1].id;
|
||
await libWrite(add);
|
||
renderLib();
|
||
return add;
|
||
}
|
||
async function libUpdate(p) {
|
||
p.modified = nowIso();
|
||
await libWrite([p]);
|
||
renderLib();
|
||
}
|
||
/* the device's parameter layout becomes the library's; patches stored with another layout are mapped by key.
|
||
A device without DIGITAL (engine 1 "-", retired in 1.0): the library's DIGITAL sounds become FM6 (fromDigital,
|
||
as readLibraryFile does), also when the layout itself is unchanged; so do its SAMPLE PERC sounds (the set retired
|
||
after 1.0.2): DRUM's kit (fromPerc) */
|
||
async function libAdopt(d) {
|
||
const keys = d.keys, engines = d.info.engines, changed = [];
|
||
const relayout = (libMeta.keys && !sameKeys(libMeta.keys, keys)) || (libMeta.engines && !sameKeys(libMeta.engines, engines));
|
||
const noFm4 = (engines || [])[1] === "-";
|
||
for (const p of lib) {
|
||
const name = p.engineName || (libMeta.engines || [])[p.engine];
|
||
const digital = noFm4 && !p.fm6 && (name === "DIGITAL" || ((!name || name === "-") && p.engine === 1));
|
||
const pe0 = () => (keys && p.p.length === keys.length ? d.info.pe0 : p.p.length - 8); /* (E1..E8: the last 8) */
|
||
const perc = !digital && !!fromPerc({ ...p, engineName: name }, engines, p.p.length - 8);
|
||
if (!relayout && !digital && !perc) continue;
|
||
if (relayout) p.p = remapParams(p.p, libMeta.keys, keys);
|
||
const pt = digital ? fromDigital(p, engines, pe0()) : perc ? fromPerc({ ...p, engineName: name }, engines, pe0()) : null;
|
||
if (pt) Object.assign(p, cleanPatch(pt));
|
||
else {
|
||
const e = name ? engines.indexOf(name) : p.engine;
|
||
if (e >= 0) { p.engine = e; p.engineName = engines[e]; }
|
||
}
|
||
changed.push(p);
|
||
}
|
||
libMeta = { keys, engines, pe0: d.info.pe0 };
|
||
if (changed.length) await libWrite(changed);
|
||
try { await store.setMeta("layout", libMeta); } catch (e) { console.warn(e); }
|
||
renderLib();
|
||
}
|
||
const engineOk = (p) => !!dev && p.engine < dev.info.nengines && (!p.engineName || dev.info.engines[p.engine] === p.engineName);
|
||
/* a full parameter set for UP_PUT: unknown values get the DESC default where it is known, else 0 */
|
||
function fullParams(p) {
|
||
const out = [];
|
||
for (let i = 0; i < dev.info.pcount; i++) {
|
||
let v = p.p[i];
|
||
if (v == null) {
|
||
const d = dev.pdesc[i];
|
||
v = d && (i < dev.info.pe0 || p.engine === dev.dump.engine) ? d.def : 0;
|
||
}
|
||
out.push(v);
|
||
}
|
||
return out;
|
||
}
|
||
|
||
const engRank = (n) => { const k = ENGINE_ORDER.indexOf(n); return k < 0 ? ENGINE_ORDER.length : k; };
|
||
function libView() {
|
||
const q = $("libq").value.trim().toLowerCase(), fe = $("libeng").value, ft = $("libtag").value;
|
||
const by = {
|
||
name: (a, b) => a.name.localeCompare(b.name),
|
||
engine: (a, b) => engRank(a.engineName) - engRank(b.engineName) || (a.engineName || "").localeCompare(b.engineName || "") ||
|
||
a.name.localeCompare(b.name), /* (the device's order: ENGINE_ORDER) */
|
||
created: (a, b) => b.created.localeCompare(a.created),
|
||
modified: (a, b) => b.modified.localeCompare(a.modified),
|
||
}[$("libsort").value] || ((a, b) => b.modified.localeCompare(a.modified));
|
||
return lib.filter((p) => (!q || p.name.toLowerCase().includes(q) || p.tags.some((x) => x.toLowerCase().includes(q)))
|
||
&& (!fe || p.engineName === fe) && (!ft || p.tags.includes(ft))).sort(by);
|
||
}
|
||
function fillSelect(sel, opts) {
|
||
const v = sel.value;
|
||
sel.replaceChildren(...opts.map(([val, txt]) => el("option", { value: val, text: txt })));
|
||
if (opts.some(([val]) => val === v)) sel.value = v;
|
||
}
|
||
function renderLib() {
|
||
const all = [...new Set([...(dev ? dev.info.engines : libMeta.engines || []), ...lib.map((p) => p.engineName).filter(Boolean)])];
|
||
const engs = engineOrder(all).map((i) => all[i]);
|
||
fillSelect($("libeng"), [["", t("allEngines")], ...engs.map((e) => [e, e])]);
|
||
const tags = [...new Set(lib.flatMap((p) => p.tags))].sort();
|
||
fillSelect($("libtag"), [["", t("allTags")], ...tags.map((x) => [x, x])]);
|
||
fillSelect($("libsort"), [["modified", t("sortModified")], ["created", t("sortCreated")], ["name", t("sortName")], ["engine", t("sortEngine")]]);
|
||
const v = libView();
|
||
if (libSel && !lib.some((p) => p.id === libSel)) libSel = null;
|
||
const box = $("liblist");
|
||
if (!lib.length) box.replaceChildren(el("div", { class: "none", text: t("libEmpty") }));
|
||
else {
|
||
const tb = el("table", {}, el("colgroup", {}, el("col"), el("col", { class: "e" }), el("col"), el("col", { class: "d" })),
|
||
el("tr", {}, el("th", { text: t("name") }), el("th", { text: t("engine") }), el("th", { text: t("tagsCol") }), el("th", { text: t("date") })));
|
||
for (const p of v) {
|
||
const tr = el("tr", { "data-id": p.id, class: p.id === libSel ? "sel" : null, draggable: "true", title: p.name },
|
||
el("td", {}, p.pattern || p.grid ? icon("note_eight") : "", p.name),
|
||
el("td", { text: p.engineName || String(p.engine) }),
|
||
el("td", { text: p.tags.join(", ") }),
|
||
el("td", { text: new Date(p.modified).toLocaleDateString(lang) }));
|
||
tr.addEventListener("click", () => { libSel = p.id; renderLib(); });
|
||
tr.addEventListener("dblclick", () => libAudition(p.id));
|
||
tr.addEventListener("dragstart", (e) => { libSel = p.id; e.dataTransfer.setData("text/x-felucca-lib", p.id); e.dataTransfer.effectAllowed = "copy"; });
|
||
tb.append(tr);
|
||
}
|
||
box.replaceChildren(tb, ...(v.length ? [] : [el("div", { class: "none", text: t("noMatch") })]));
|
||
}
|
||
$("libcount").textContent = `${v.length} / ${lib.length}` + (libPersistent ? "" : " " + t("noLibDB"));
|
||
const sel = lib.find((p) => p.id === libSel);
|
||
for (const id of ["libren", "libtags", "libdup", "libdel", "libexp1"]) $(id).disabled = !sel;
|
||
$("libaud").disabled = !sel || !dev || libBusy;
|
||
$("libput").disabled = !sel || !dev || !dev.bank || bankSel == null || libBusy;
|
||
$("libsave").disabled = !dev || libBusy;
|
||
$("libexport").disabled = !lib.length;
|
||
}
|
||
["libq", "libeng", "libtag", "libsort"].forEach((id) => $(id).addEventListener(id === "libq" ? "input" : "change", renderLib));
|
||
|
||
function renderBank() {
|
||
const pane = $("bankpane");
|
||
$("bankhint").hidden = !!(dev && dev.bank);
|
||
$("bankhint").textContent = t(!dev || !dev.dump ? "bankConnect" : "bankNone");
|
||
if (!dev || !dev.bank) { pane.hidden = true; return; }
|
||
pane.hidden = false;
|
||
const b = dev.bank, used = b.slots.filter((x) => x.used).length;
|
||
$("bankhead").textContent = `${used} / ${b.total} ${t("used")}`;
|
||
const tb = el("table", {}, el("colgroup", {}, el("col", { class: "n" }), el("col"), el("col", { class: "e" })),
|
||
el("tr", {}, el("th", { text: "#" }), el("th", { text: t("name") }), el("th", { text: t("engine") })));
|
||
for (const x of b.slots) {
|
||
const tr = el("tr", { "data-slot": x.slot, class: [x.slot === bankSel ? "sel" : "", x.used ? "" : "empty"].join(" ").trim() || null,
|
||
draggable: x.used ? "true" : null },
|
||
el("td", { text: slotName(x.slot) }), el("td", { text: x.used ? x.name : t("empty") }),
|
||
el("td", { text: x.used ? engineLabel(dev.info.engines, x.engine) : "" }));
|
||
tr.addEventListener("click", () => { bankSel = x.slot; renderBank(); renderLib(); });
|
||
tr.addEventListener("dblclick", () => { if (x.used) bankLoad(x.slot); });
|
||
tr.addEventListener("dragstart", (e) => { e.dataTransfer.setData("text/x-felucca-slot", String(x.slot)); e.dataTransfer.effectAllowed = "copy"; });
|
||
tr.addEventListener("dragover", (e) => { if (e.dataTransfer.types.includes("text/x-felucca-lib")) { e.preventDefault(); tr.classList.add("over"); } });
|
||
tr.addEventListener("dragleave", () => tr.classList.remove("over"));
|
||
tr.addEventListener("drop", (e) => {
|
||
e.preventDefault();
|
||
tr.classList.remove("over");
|
||
const id = e.dataTransfer.getData("text/x-felucca-lib");
|
||
if (id) { bankSel = x.slot; libPut(id, x.slot); }
|
||
});
|
||
tb.append(tr);
|
||
}
|
||
$("banklist").replaceChildren(tb);
|
||
const s = bankSel == null ? null : b.slots[bankSel];
|
||
const idle = !libBusy;
|
||
$("bkload").disabled = !s || !s.used || !idle;
|
||
$("bkstore").disabled = !s || !idle;
|
||
$("bkget").disabled = !s || !s.used || !idle;
|
||
$("bkerase").disabled = !s || !s.used || !idle;
|
||
$("bkrefresh").disabled = !idle;
|
||
$("bkexport").disabled = !used || !idle;
|
||
}
|
||
/* a slot dropped on the library: copy it there */
|
||
$("liblist").addEventListener("dragover", (e) => { if (e.dataTransfer.types.includes("text/x-felucca-slot")) { e.preventDefault(); $("liblist").classList.add("over"); } });
|
||
$("liblist").addEventListener("dragleave", () => $("liblist").classList.remove("over"));
|
||
$("liblist").addEventListener("drop", (e) => {
|
||
e.preventDefault();
|
||
$("liblist").classList.remove("over");
|
||
const s = e.dataTransfer.getData("text/x-felucca-slot");
|
||
if (s !== "") bankGet(+s);
|
||
});
|
||
|
||
/* library operations that talk to the device: one at a time, buttons off meanwhile */
|
||
async function libOp(fn) {
|
||
if (!dev || libBusy) return;
|
||
const d = dev;
|
||
libBusy = true;
|
||
const releaseBusy = beginBusy();
|
||
renderLib(); renderBank();
|
||
try { await fn(d, (r, o) => sessionRequest(d, r, o)); } catch (err) { report(err); } finally { releaseBusy(); libBusy = false; renderLib(); renderBank(); }
|
||
}
|
||
const checkRc = (rc) => { if (rc) throw new Error(t("flashFail").replace("{rc}", rc)); };
|
||
async function refreshSlot(slot, d = dev) {
|
||
const r = parse[CMD.UP_LIST](await sessionRequest(d, req.upList(slot, 1)));
|
||
if (d.bank && r.slots[0]) d.bank.slots[slot] = r.slots[0];
|
||
}
|
||
|
||
function libAudition(id) {
|
||
const p = lib.find((x) => x.id === id);
|
||
if (!p || !dev || libBusy) return;
|
||
libOp(async (d, rqf) => {
|
||
if (!engineOk(p)) throw new Error(t("badEngine") + (p.engineName || p.engine));
|
||
sayK("auditioning", p.name);
|
||
selfLoad(true);
|
||
await auditionPatch(rqf, dev.info, p, { gEng: gEng(), track: dev.sel ?? 0,
|
||
progress: (i, n) => { if (i % 8 === 0) sayK("auditioning", `${p.name} ${i}/${n}`); } });
|
||
await afterSoundChange("ready", d);
|
||
sayK("auditioned", p.name);
|
||
});
|
||
}
|
||
$("libaud").addEventListener("click", () => libAudition(libSel));
|
||
|
||
$("libsave").addEventListener("click", () => libOp(async (d, rqf) => {
|
||
const def = upName((dev.names[dev.dump.engine] || [])[dev.dump.preset] || dev.info.engines[dev.dump.engine]);
|
||
const name = prompt(t("promptName"), def);
|
||
if (name == null) return;
|
||
const { patch } = await capturePatch(rqf, dev.info, name.trim() || def);
|
||
await libAdd([patch]);
|
||
sayK("savedLib", patch.name);
|
||
}));
|
||
|
||
/* factory preset -> library: PRESET (the sound only), then DUMP; no pattern (the steps are the track's,
|
||
not the preset's) */
|
||
$("factlib").addEventListener("click", () => libOp(async (d, rqf) => {
|
||
const e = dev.dump.engine, pi = $("preset").value === "" ? dev.dump.preset : +$("preset").value;
|
||
const name = (dev.names[e] || [])[pi] || "PRESET";
|
||
selfLoad(true);
|
||
await rqf(req.preset(e, pi));
|
||
const { patch } = await capturePatch(rqf, dev.info, name);
|
||
patch.pattern = null;
|
||
patch.grid = null;
|
||
patch.tags = ["factory"];
|
||
await libAdd([patch]);
|
||
await afterSoundChange("ready", d);
|
||
sayK("copiedLib", `${dev.info.engines[e]} ${name}`);
|
||
}));
|
||
|
||
function libPut(id, slot) {
|
||
const p = lib.find((x) => x.id === id);
|
||
if (!p || !dev || !dev.bank || slot == null || libBusy) return;
|
||
const s = dev.bank.slots[slot];
|
||
if (!engineOk(p)) { sayK("badEngine", p.engineName || p.engine); return; }
|
||
if (s.used && !confirm(t("confirmOverwrite").replace("{n}", slotName(slot)).replace("{name}", s.name))) return;
|
||
libOp(async (d, rqf) => {
|
||
const keep4 = p.fm4 && dev.info.engines[1] === "-" && p.fm4.length === dev.info.pcount; /* a converted DIGITAL sound:
|
||
its DIGITAL values as engine 1 (the device converts them on load) */
|
||
checkRc(await bank.put(rqf, slot, keep4 ? { ...p, engine: 1, name: upName(p.name), p: fullParams({ ...p, p: p.fm4 }) }
|
||
: { ...p, name: upName(p.name), p: fullParams(p) }, dev.info));
|
||
await refreshSlot(slot, d);
|
||
sayK("putDone", `${slotName(slot)} ${upName(p.name)}`);
|
||
});
|
||
}
|
||
$("libput").addEventListener("click", () => libPut(libSel, bankSel));
|
||
|
||
$("libren").addEventListener("click", () => {
|
||
const p = lib.find((x) => x.id === libSel);
|
||
if (!p) return;
|
||
const v = prompt(t("promptName"), p.name);
|
||
if (v == null || !v.trim()) return;
|
||
p.name = v.trim().slice(0, 32);
|
||
libUpdate(p);
|
||
});
|
||
$("libtags").addEventListener("click", () => {
|
||
const p = lib.find((x) => x.id === libSel);
|
||
if (!p) return;
|
||
const v = prompt(t("promptTags"), p.tags.join(", "));
|
||
if (v == null) return;
|
||
p.tags = [...new Set(v.split(",").map((x) => x.trim()).filter(Boolean))];
|
||
libUpdate(p);
|
||
});
|
||
$("libdup").addEventListener("click", () => {
|
||
const p = lib.find((x) => x.id === libSel);
|
||
if (p) libAdd([{ ...p, name: (p.name + " 2").slice(0, 32), created: nowIso(), modified: nowIso() }]);
|
||
});
|
||
$("libdel").addEventListener("click", async () => {
|
||
const p = lib.find((x) => x.id === libSel);
|
||
if (!p || !confirm(t("confirmDelete").replace("{name}", p.name))) return;
|
||
lib = lib.filter((x) => x !== p);
|
||
libSel = null;
|
||
try { await store.del(p.id); } catch (e) { console.warn(e); }
|
||
renderLib();
|
||
});
|
||
|
||
function download(name, obj) {
|
||
const blob = new Blob([JSON.stringify(obj, null, 1)], { type: "application/json" });
|
||
const a = el("a", { href: URL.createObjectURL(blob), download: name });
|
||
document.body.append(a);
|
||
a.click();
|
||
a.remove();
|
||
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
|
||
}
|
||
const fileSlug = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "patch";
|
||
const today = () => new Date().toISOString().slice(0, 10);
|
||
$("libexp1").addEventListener("click", () => {
|
||
const p = lib.find((x) => x.id === libSel);
|
||
if (p) download(`felucca-patch-${fileSlug(p.name)}.json`, libraryFile("patch", [p], libCtx()));
|
||
});
|
||
$("libexport").addEventListener("click", () => download(`felucca-library-${today()}.json`, libraryFile("library", lib, libCtx())));
|
||
$("libimport").addEventListener("click", () => { $("libfile").value = ""; $("libfile").click(); });
|
||
$("libfile").addEventListener("change", async () => {
|
||
let n = 0, skipped = 0;
|
||
for (const f of [...$("libfile").files]) {
|
||
try {
|
||
const obj = JSON.parse(await f.text());
|
||
const ctx = libCtx();
|
||
const r = readLibraryFile(obj, ctx);
|
||
if (!ctx.keys && r.keys) { /* no layout yet: the file's becomes the library's */
|
||
libMeta = { keys: r.keys, engines: Array.isArray(obj.engines) ? obj.engines : null, pe0: obj.pE0 ?? null };
|
||
try { await store.setMeta("layout", libMeta); } catch (e) { console.warn(e); }
|
||
}
|
||
if (obj.kind === "bank") r.patches.forEach((p) => { if (!p.tags.includes("bank")) p.tags.push("bank"); });
|
||
await libAdd(r.patches);
|
||
n += r.patches.length;
|
||
skipped += r.skipped;
|
||
} catch (e) { sayK("badfile", `${f.name}: ${e.message}`); return; }
|
||
}
|
||
sayK("imported", n + (skipped ? t("skippedN").replace("{n}", skipped) : t("patchesN")));
|
||
});
|
||
|
||
/* device bank */
|
||
function bankLoad(slot) {
|
||
if (!dev || !dev.bank || slot == null || libBusy) return;
|
||
const s = dev.bank.slots[slot];
|
||
libOp(async (d, rqf) => {
|
||
selfLoad();
|
||
const rc = await bank.load(rqf, slot);
|
||
if (rc) { sayK("emptySlot", slotName(slot)); return; }
|
||
await afterSoundChange("ready", d);
|
||
sayK("loadedUser", `${slotName(slot)} ${s.name}`);
|
||
});
|
||
}
|
||
$("bkload").addEventListener("click", () => bankLoad(bankSel));
|
||
$("bkstore").addEventListener("click", () => {
|
||
const slot = bankSel;
|
||
if (!dev || !dev.bank || slot == null) return;
|
||
const s = dev.bank.slots[slot];
|
||
const name = prompt(t("promptNameAuto"), s.used ? s.name : "");
|
||
if (name == null) return;
|
||
if (s.used && !confirm(t("confirmOverwrite").replace("{n}", slotName(slot)).replace("{name}", s.name))) return;
|
||
libOp(async (d, rqf) => {
|
||
checkRc(await bank.store(rqf, slot, name.trim()));
|
||
await refreshSlot(slot, d);
|
||
sayK("storedSlot", `${slotName(slot)} ${dev.bank.slots[slot].name}`);
|
||
});
|
||
});
|
||
function bankGet(slot) {
|
||
if (!dev || !dev.bank || slot == null || libBusy) return;
|
||
libOp(async (d, rqf) => {
|
||
const u = await bank.get(rqf, dev.info, slot);
|
||
if (!u.used) { sayK("emptySlot", slotName(slot)); return; }
|
||
const pt = { name: u.name, engine: u.engine, engineName: dev.info.engines[u.engine], p: u.p, pattern: u.pattern, grid: u.grid, tags: ["device"],
|
||
fm6: u.fm6 };
|
||
await libAdd([reservedFm4(dev.info.engines, u.engine) ? fromDigital(pt, dev.info.engines, dev.info.pe0) : pt]);
|
||
sayK("copiedLib", u.name);
|
||
});
|
||
}
|
||
$("bkget").addEventListener("click", () => bankGet(bankSel));
|
||
$("bkerase").addEventListener("click", () => {
|
||
const slot = bankSel;
|
||
if (!dev || !dev.bank || slot == null) return;
|
||
const s = dev.bank.slots[slot];
|
||
if (!s.used || !confirm(t("confirmEraseSlot").replace("{n}", slotName(slot)).replace("{name}", s.name))) return;
|
||
libOp(async (d, rqf) => {
|
||
checkRc(await bank.erase(rqf, slot));
|
||
await refreshSlot(slot, d);
|
||
sayK("erasedSlot", slotName(slot));
|
||
});
|
||
});
|
||
$("bkrefresh").addEventListener("click", () => libOp(async (d, rqf) => {
|
||
sayK("readingBank");
|
||
dev.bank = await bank.list(rqf);
|
||
sayK("ready");
|
||
}));
|
||
$("bkexport").addEventListener("click", () => libOp(async (d, rqf) => {
|
||
const out = [];
|
||
for (const x of dev.bank.slots) {
|
||
if (!x.used) continue;
|
||
sayK("readingBank", ` ${slotName(x.slot)}`);
|
||
const u = await bank.get(rqf, dev.info, x.slot);
|
||
if (u.used) out.push({ name: u.name, engine: u.engine, p: u.p, pattern: u.pattern, grid: u.grid, slot: x.slot, fm6: u.fm6,
|
||
engineName: reservedFm4(dev.info.engines, u.engine) ? "DIGITAL" : dev.info.engines[u.engine] }); /* (DIGITAL's values) */
|
||
}
|
||
download(`felucca-bank-${today()}.json`, libraryFile("bank", out, libCtx()));
|
||
sayK("ready");
|
||
}));
|
||
|
||
/* ------------------------------------------------------------------ FM6 --- */
|
||
/* The 6-OP FM tab (firmware with FM6: INFO's fm6 tag): the whole patch of an FM6 track, which the device
|
||
only reaches through its macros. Import the generic 155-byte single-voice and 4096-byte 32-voice SysEx files,
|
||
pick a voice, edit it, send it to a track (live while editing); read a track's patch or a factory one; export a
|
||
voice. The track keeps it (SLOT OWN); a user preset (SAVE) or a project on the device keeps it after that.
|
||
The patch bank of 1.0..1.0.2 (B1..B27) is not offered, whatever the firmware (retired in 1.0.3). */
|
||
let fm6v = FM6.init(); /* the patch being edited (155 bytes) */
|
||
let fm6Imported = []; /* voices of the last imported file: [{name, v}] */
|
||
let fm6Picked = -1; /* the imported voice last clicked (now in fm6v) */
|
||
let fm6List = null; /* FM6_LIST of the device */
|
||
let fm6Listing = false; /* FM6_LIST on its way */
|
||
let fm6Asked = false; /* FM6_LIST asked once for this connection (renderPanels) */
|
||
let fm6Timer = null;
|
||
const fm6Ok = () => !!dev && !!dev.info && !!dev.info.fm6;
|
||
const fm6Track = () => +$("fm6trk").value || 0;
|
||
const fm6SlotName = (i) => "F" + (i + 1); /* the factory patches */
|
||
const FM6_WAVES = ["TRI", "SAW-", "SAW+", "SQR", "SIN", "S&H"];
|
||
const FM6_CURVES = ["-LIN", "-EXP", "+EXP", "+LIN"];
|
||
function fm6Set(i, val) {
|
||
fm6v[i] = Math.max(0, Math.min(FM6.max(i), Math.round(+val || 0)));
|
||
if ($("fm6live").checked && fm6Ok()) {
|
||
clearTimeout(fm6Timer);
|
||
fm6Timer = setTimeout(() => op(() => fm6Send(true)), 150);
|
||
}
|
||
}
|
||
function fm6Num(i, title) {
|
||
return el("input", { type: "number", min: 0, max: FM6.max(i), value: fm6v[i], title, class: "fm6n",
|
||
onchange: (e) => { fm6Set(i, e.target.value); e.target.value = fm6v[i]; renderFm6Ops(); } });
|
||
}
|
||
function fm6Sel(i, names, title) {
|
||
const s = el("select", { title, onchange: (e) => { fm6Set(i, e.target.value); renderFm6(); } },
|
||
...names.map((n, k) => el("option", { value: k, text: n })));
|
||
s.value = fm6v[i];
|
||
return s;
|
||
}
|
||
function renderFm6Voice() {
|
||
const V = FM6.VI, alg = fm6v[V.ALG], fb = FM6.feedbackOp(alg);
|
||
const nm = el("input", { type: "text", maxlength: 10, value: FM6.name(fm6v), size: 11,
|
||
onchange: (e) => { FM6.setName(fm6v, e.target.value); fm6Set(0, fm6v[0]); e.target.value = FM6.name(fm6v); } });
|
||
const row = (label, ...kids) => el("tr", {}, el("th", { text: label }), el("td", {}, ...kids));
|
||
$("fm6voice").replaceChildren(el("table", {},
|
||
row(t("name"), nm),
|
||
row("ALG", fm6Sel(V.ALG, Array.from({ length: 32 }, (_, k) => String(k + 1)), "ALG"),
|
||
el("span", { class: "dim", text: ` ${t("fm6Carriers")} ${FM6.carriers(alg).join(" ")}, ${t("fm6Feedback")} OP${fb}` })),
|
||
row("FB", fm6Num(V.FB, "FB"), " OKS ", fm6Num(V.OKS, "OKS"), " TRNSP ", fm6Num(V.TRNSP, "TRNSP")),
|
||
row("LFO", fm6Sel(V.LFW, FM6_WAVES, "WAVE"), " SPD ", fm6Num(V.LFS, "SPEED"), " DLY ", fm6Num(V.LFD, "DELAY"),
|
||
" PMD ", fm6Num(V.LPMD, "PMD"), " AMD ", fm6Num(V.LAMD, "AMD"), " PMS ", fm6Num(V.LPMS, "PMS"), " SYNC ", fm6Num(V.LKS, "SYNC")),
|
||
row(t("fm6PitchEg"), "R ", ...[0, 1, 2, 3].map((k) => fm6Num(V.PR1 + k, "R" + (k + 1))),
|
||
" L ", ...[0, 1, 2, 3].map((k) => fm6Num(V.PL1 + k, "L" + (k + 1))))));
|
||
}
|
||
function renderFm6Ops() {
|
||
const car = FM6.carriers(fm6v[FM6.VI.ALG]);
|
||
const head = el("tr", {}, el("th", { text: "OP" }), ...FM6.OP.map(([n]) => el("th", { text: n })), el("th", { text: t("fm6Freq") }));
|
||
const rows = [1, 2, 3, 4, 5, 6].map((n) => el("tr", {},
|
||
el("th", { text: (car.includes(n) ? "● " : "") + n }),
|
||
...FM6.OP.map(([f]) => el("td", {}, f === "LC" || f === "RC" ? fm6Sel(FM6.at(n, f), FM6_CURVES, f)
|
||
: f === "MODE" ? fm6Sel(FM6.at(n, f), ["RATIO", "FIXED"], f) : fm6Num(FM6.at(n, f), `OP${n} ${f}`))),
|
||
el("td", { class: "dim", text: FM6.freqText(fm6v, n) })));
|
||
$("fm6ops").replaceChildren(el("div", { class: "fm6ops" }, el("table", {}, head, ...rows)), el("p", { class: "dim", text: t("fm6Legend") }));
|
||
}
|
||
function renderFm6Imported() {
|
||
const box = $("fm6imported");
|
||
if (!fm6Ok()) { box.replaceChildren(); return; }
|
||
/* (JIANT 0.6.11) the device's voice bank (SLOT B1..B32): its name, and the imported file sent to it whole */
|
||
const bankRow = dev.info.fm6Bank ? [el("p", { class: "dim",
|
||
text: `${t("fm6BankNow")} ${fm6BankList ? (fm6BankList.valid ? `${fm6BankList.name || "-"} (${fm6BankList.voices.filter((v) => v.used).length})` : t("fm6BankNone")) : "…"}` })] : [];
|
||
if (dev.info.fm6Bank && fm6Imported.length > 1)
|
||
bankRow.push(el("p", { class: "bar" }, el("button", { text: t("fm6BankSend"), onclick: () => op(fm6BankSend) })));
|
||
if (!fm6Imported.length) { box.replaceChildren(...bankRow); return; }
|
||
box.replaceChildren(el("p", { class: "dim", text: t("fm6Pick") }),
|
||
el("p", { class: "bar" }, ...fm6Imported.map((x, k) => el("button", { text: `${k + 1} ${x.name}`,
|
||
"aria-pressed": k === fm6Picked ? "true" : "false",
|
||
onclick: () => { fm6v = Uint8Array.from(x.v); fm6Picked = k; renderFm6(); sayK("fm6Picked", ` ${x.name}`); } }))), ...bankRow);
|
||
}
|
||
let fm6BankList = null, fm6ImportName = ""; /* (0.6.11) the device's voice bank (FM6B_LIST), the file imported last */
|
||
async function fm6BankRefresh(d = dev) {
|
||
if (!d || !d.info.fm6Bank) return;
|
||
fm6BankList = await fm6Bank.list((r, o) => sessionRequest(d, r, o));
|
||
renderFm6Imported();
|
||
}
|
||
async function fm6BankSend() {
|
||
const name = fm6Bank.nameOf(fm6ImportName) || "BANK";
|
||
const rc = await fm6Bank.send((r, o) => sessionRequest(dev, r, o), fm6Bank.fromVoices(fm6Imported), name);
|
||
if (rc) { sayK("fm6BankFail", `${rc})`); return; }
|
||
await fm6BankRefresh();
|
||
sayK("fm6BankSent", ` ${name} (${Math.min(32, fm6Imported.length)})`);
|
||
}
|
||
function renderFm6() {
|
||
if (!fm6Ok()) return;
|
||
const ts = $("fm6trk"), keepT = ts.value, ss = $("fm6slot"), keepS = ss.value;
|
||
ts.replaceChildren(...Array.from({ length: dev.info.ntrk || 1 }, (_, i) => el("option", { value: i, text: String(i + 1) })));
|
||
ts.value = keepT || (dev.sel ?? 0);
|
||
const nf = dev.info.fm6.factory; /* the factory patches only (names once FM6_LIST is in) */
|
||
ss.replaceChildren(...Array.from({ length: nf }, (_, i) => {
|
||
const x = fm6List && fm6List.slots[i];
|
||
return el("option", { value: i, text: `${fm6SlotName(i)} ${x && x.used ? x.name : ""}`.trim() });
|
||
}));
|
||
ss.value = keepS !== "" && +keepS < nf ? keepS : "0";
|
||
renderFm6Voice();
|
||
renderFm6Ops();
|
||
renderFm6Imported();
|
||
}
|
||
async function fm6Refresh(d = dev) {
|
||
fm6Listing = true;
|
||
try { fm6List = parse[CMD.FM6_LIST](await sessionRequest(d, req.fm6List())); } finally { fm6Listing = false; }
|
||
renderFm6();
|
||
await fm6BankRefresh(d);
|
||
}
|
||
async function fm6Send(quiet) {
|
||
const r = parse[CMD.FM6_PUT](await sessionRequest(dev, req.fm6Put(FM6.TARGET.TRACK, fm6Track(), FM6.pack(fm6v))));
|
||
checkRc(r.rc);
|
||
if (!quiet) sayK("fm6Sent", ` ${fm6Track() + 1}`);
|
||
}
|
||
$("fm6read").addEventListener("click", () => op(async () => {
|
||
const r = parse[CMD.FM6_GET](await sessionRequest(dev, req.fm6Get(FM6.TARGET.TRACK, fm6Track())));
|
||
checkRc(r.rc);
|
||
fm6v = FM6.unpack(r.packed);
|
||
renderFm6();
|
||
sayK("fm6Read", ` ${fm6Track() + 1}: ${FM6.name(fm6v)}`);
|
||
}));
|
||
$("fm6send").addEventListener("click", () => op(() => fm6Send(false)));
|
||
$("fm6load").addEventListener("click", () => op(async () => { /* a factory patch into the editor */
|
||
const i = +$("fm6slot").value;
|
||
const r = parse[CMD.FM6_GET](await sessionRequest(dev, req.fm6Get(FM6.TARGET.FACTORY, i)));
|
||
checkRc(r.rc);
|
||
fm6v = FM6.unpack(r.packed);
|
||
fm6Picked = -1;
|
||
renderFm6();
|
||
sayK("fm6Loaded", ` ${fm6SlotName(i)}: ${FM6.name(fm6v)}`);
|
||
}));
|
||
$("fm6init").addEventListener("click", () => { fm6v = FM6.init(); renderFm6(); });
|
||
$("fm6import").addEventListener("click", () => $("fm6file").click());
|
||
$("fm6file").addEventListener("change", async (e) => {
|
||
const f = e.target.files[0];
|
||
e.target.value = "";
|
||
if (!f) return;
|
||
const r = FM6.parseSysex(new Uint8Array(await f.arrayBuffer()));
|
||
if (!r.voices.length) { const [k, x] = fm6Why(r); sayK(k, `${x}: ${f.name}`); return; }
|
||
fm6Imported = r.voices;
|
||
fm6ImportName = f.name;
|
||
fm6Picked = r.voices.length === 1 ? 0 : -1;
|
||
if (r.voices.length === 1) fm6v = Uint8Array.from(r.voices[0].v);
|
||
renderFm6();
|
||
const notes = [r.badSum && t("fm6BadSum"), r.short && t("fm6Short"), r.skipped && t("fm6Skipped").replace("{x}", r.skipped)].filter(Boolean);
|
||
sayK("imported", `${f.name}: ${r.voices.length}` + (notes.length ? ` (${notes.join(", ")})` : ""));
|
||
});
|
||
/* why a file had no 6-operator voice: [message key, what to add before the file name] */
|
||
function fm6Why(r) {
|
||
const mk = r.kinds.find((k) => k.startsWith("maker:"));
|
||
if (r.kinds.includes("fm4")) return ["fm6Is4op", ""];
|
||
if (r.kinds.includes("other43")) return ["fm6OtherBlocks", ""];
|
||
if (mk) return ["fm6OtherMaker", ` (ID ${mk.slice(6)})`];
|
||
if (r.kinds.includes("universal")) return ["fm6Universal", ""];
|
||
return [r.sysex ? "fm6NoVoice" : "fm6NotSysex", ""];
|
||
}
|
||
function downloadBytes(name, bytes) {
|
||
const a = el("a", { href: URL.createObjectURL(new Blob([bytes], { type: "application/octet-stream" })), download: name });
|
||
document.body.append(a);
|
||
a.click();
|
||
a.remove();
|
||
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
|
||
}
|
||
$("fm6export").addEventListener("click", () => downloadBytes(`${fileSlug(FM6.name(fm6v))}.syx`, FM6.singleSysex(fm6v)));
|
||
|
||
/* ============================================================ ROLL (piano roll) === */
|
||
/* Every sequencer of the device, drawn as the FM-1 draws it (firmware ui_graph.c graph_roll / graph_grid / bar_cell, the
|
||
JIANT palette of tools/gen_ui_palettes.py, heat_col, note_col, lz_note), edited through the editor protocol only:
|
||
TRACK_STEP (30) a step of any track, TRACK_PARAM (31) its LEN DIV SWING GATE OFS PIT and the modulation sequence,
|
||
MOTION (64; ops 5..7 the locks, INFO 4C 01) the automation and the locks, GET / SET (2, 3) scope 1 the SLICER's steps.
|
||
What the protocol does not carry (a step's MICRO and components, EUCLID's own settings) is said on the page; the
|
||
proposal for it is in EDITOR_PROTOCOL.md ("Proposal: the rest of a step"). Nothing runs while the tab is closed:
|
||
no timer, no drawing; the canvas draws on a change only (one frame). */
|
||
const RPAL = (() => {
|
||
/* the JIANT palette as the firmware holds it (RGB565, build/gen/ui_palettes.h): bg surf text theme accent mid dim line
|
||
sel tint rec raise; lane and grid derived as gfx.c palette_set does */
|
||
const mix = (a, b, pct) => { /* gfx.c ux_mix: per channel, rounded half away from zero */
|
||
const SH = [11, 5, 0], MK = [31, 63, 31];
|
||
let out = 0;
|
||
for (let k = 0; k < 3; k++) {
|
||
const x = (a >> SH[k]) & MK[k], d = (((b >> SH[k]) & MK[k]) - x) * pct;
|
||
out |= (x + Math.trunc((d + (d >= 0 ? 50 : -50)) / 100)) << SH[k];
|
||
}
|
||
return out;
|
||
};
|
||
const css = (v) => `rgb(${(v >> 11) * 255 / 31 | 0},${((v >> 5) & 63) * 255 / 63 | 0},${(v & 31) * 255 / 31 | 0})`;
|
||
const U = { bg: 0x0000, surf: 0x0841, text: 0xf79d, theme: 0xbb9f, accent: 0xfbc0, mid: 0xad54, dim: 0x6b2c, line: 0x2965,
|
||
sel: 0x92d9, tint: 0x1864, rec: 0xfa49, raise: 0x1082 };
|
||
U.lane = mix(U.surf, U.theme, 10); U.grid = mix(U.surf, U.text, 6);
|
||
const H = [0x3955, 0x82DF, 0xFA09, 0xFBA3, 0xFDEB, 0xFF99, 0xFFFF];
|
||
const heat565 = (v) => { v = Math.max(0, Math.min(256, v | 0)); const k = Math.floor(v * 6 / 257); return mix(H[k], H[k + 1], Math.floor((v * 6 - k * 256) * 100 / 256)); };
|
||
const note565 = (n) => heat565(40 + Math.floor((n % 12) * 200 / 11)); /* ui_lzpage.c note_col */
|
||
const C = Object.fromEntries(Object.entries(U).map(([k, v]) => [k, css(v)]));
|
||
return { U, C, mix, css, heat: (v) => css(heat565(v)), note: (n) => css(note565(n)),
|
||
/* ui_graph.c lz_note: a note its pitch class's heat (an accent toward white), a kit's hit 115 (a chord's 146, an
|
||
accent 243) */
|
||
lz: (st, acc, n) => n >= 0 ? css(mix(note565(n), U.text, acc ? 55 : 0)) : css(heat565(acc ? 243 : st.n > 1 ? 146 : 115)),
|
||
card: (ratio, bip) => { let r = Math.max(0, Math.min(1000, ratio)); if (bip) r = Math.abs(r - 500) * 2; return css(heat565(Math.floor(r * 256 / 1000))); } };
|
||
})();
|
||
const RP = { SLEN: 29, SDIV: 30, SSWING: 31, SGATE: 32, ROOT: 25, SCALE: 26, SOFS: 81, SPOFS: 82,
|
||
MSLEN: 93, MSDIV: 94, MSSLW: 95, MS0: 96 }; /* core.h P_* (P_COUNT 123) */
|
||
const R_SCALE = [0xFFF, 0xAB5, 0x5AD, 0x6AD, 0x6B5, 0x295, 0x4A9, 0x9AD, 0x5AB, 0xAD5, 0x56B, 0xAAD, 0x4E9, 0x555, 0x6DB, 0xB6D]; /* seq.c SCALE_MASK */
|
||
const R_KB = [0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0];
|
||
const R_ABBR = ["BD", "SD", "CP", "CH", "OH", "TM", "RS", "CB"]; /* ui_graph.c drum_lane_abbr (the DRUM-X kit) */
|
||
const R_LM = ["--", "x2", "x4", "x8", "SHORT", "GHOST", "FLAM"]; /* core.h LM_*: SEQ > STEP's HIT */
|
||
const R_LM1 = ["", "2", "4", "8", "S", "G", "F"];
|
||
/* motion.c motion_param: the ids a lock or an automation event can hold (P_COUNT 123; 127 the DJ FILTER, automation only) */
|
||
const rLockable = (id, pe0, pc) => id < pc && (id <= 4 || (id >= 5 && id <= 16) || (id >= 33 && id <= 36) || id === 38 || id === 39 ||
|
||
id === 44 || (id >= 61 && id <= 80) || (id >= 81 && id <= 90) || id === 92 || id === 95 || (id >= 96 && id <= 111) ||
|
||
id === 113 || id === 114 || id >= pe0);
|
||
/* ui_euclid.c eu_hit: lane l's hit at step i (HITS h over STEPS n, ROTATE r) */
|
||
const euHit = (i, h, n, r) => { n = n || 1; const j = (i + n - r % n) % n; return h > 0 && (j * h) % n < h; };
|
||
/* ui_euclid.c eu_kit: ALL, the kit a DENSITY 1..8 makes over STEPS n, ROTATE r turning the kick and the percussion */
|
||
function euKit(dens, n, r) {
|
||
const KT = [[2, 0, 0, 4, 0, 0, 0, 0], [3, 2, 0, 4, 0, 0, 0, 0], [4, 2, 0, 8, 0, 0, 0, 0], [4, 2, 1, 8, 2, 0, 0, 0],
|
||
[5, 2, 1, 8, 2, 0, 3, 0], [5, 2, 1, 12, 2, 2, 3, 0], [6, 3, 1, 12, 3, 2, 5, 2], [7, 4, 2, 16, 4, 3, 5, 3]];
|
||
const KR = [0, 4, 12, 0, 6, 10, 3, 7];
|
||
n = n || 16; const d = (dens ? dens - 1 : 0) & 7;
|
||
return KR.map((kr, i) => {
|
||
let h = dens ? Math.floor((KT[d][i] * n + 8) / 16) : 0;
|
||
h = h > n ? n : KT[d][i] && !h && dens ? 1 : h;
|
||
return { h, n, r: (Math.floor((kr * n + 8) / 16) + ((0xE1 >> i) & 1 ? r : 0)) % n };
|
||
});
|
||
}
|
||
|
||
const roll = {
|
||
open: false, track: 0, steps: [], p: null, engine: 0, motion: null, loading: null, sel: null, lane: 0,
|
||
view: { sx: 0, cw: 0, top: 84, rh: 0 }, vlane: "vel", undo: [], dirty: true, raf: 0, cv: null, euPrev: null,
|
||
};
|
||
const rollTouch = () => matchMedia("(pointer: coarse)").matches;
|
||
const rollDrum = () => !!dev && dev.info.engines[roll.engine] === "DRUM";
|
||
const rollLen = () => Math.max(1, Math.min(dev.info.nstep, roll.p ? roll.p[RP.SLEN] || 16 : 16));
|
||
const rollEmpty = () => ({ n: 0, notes: [0, 0, 0, 0], time: 2, flags: 0, vel: 0, hit: 0, acc: 0, chance: 100, ratchet: 1, lanes: [0, 0, 0, 0, 0, 0, 0, 0] });
|
||
const rollCopy = (s) => ({ ...s, notes: s.notes.slice(), lanes: (s.lanes || [0, 0, 0, 0, 0, 0, 0, 0]).slice() });
|
||
/* the step a column shows: itself (a NOTE), the NOTE a TIE carries (ui_graph.c pr_src), or none */
|
||
function rollSrc(i) {
|
||
const len = rollLen();
|
||
for (let k = 0, j = i; k < len; k++, j = (j + len - 1) % len) {
|
||
const s = roll.steps[j];
|
||
if (!s) return -1;
|
||
if (s.time === 0) return s.n || s.hit ? j : -1;
|
||
if (s.time === 2) return -1;
|
||
if (j === 0 && i !== 0) return -1; /* (a TIE at step 1 carries nothing back round the loop on the screen) */
|
||
}
|
||
return -1;
|
||
}
|
||
function rollInvalidate() {
|
||
roll.dirty = true;
|
||
if (!roll.open || roll.raf) return;
|
||
roll.raf = requestAnimationFrame(() => { roll.raf = 0; rollDraw(); });
|
||
}
|
||
|
||
/* ---------------------------------------------------------- reading --- */
|
||
async function rollRead(track = dev ? dev.sel || 0 : 0) {
|
||
const d = dev;
|
||
if (!d || !d.info.ntrk) return;
|
||
const n = d.info.nstep, lanes = !!d.info.laneModes;
|
||
roll.track = track;
|
||
roll.loading = 0;
|
||
rollStatus();
|
||
const td = parse[CMD.TRACK_DUMP](await sessionRequest(d, req.trackDump(track)), d.info);
|
||
roll.engine = td.engine; roll.p = td.p;
|
||
const steps = [];
|
||
for (let i = 0; i < n; i++) {
|
||
const r = parse[CMD.TRACK_STEP](await sessionRequest(d, req.trackStep(track, i, null, lanes)));
|
||
steps.push(rollNorm(r));
|
||
if (i % 8 === 7) { roll.loading = i + 1; rollStatus(); }
|
||
}
|
||
assertSession(d);
|
||
roll.steps = steps;
|
||
if (track === (d.sel || 0)) for (let i = 0; i < n; i++) d.steps[i] = { ...steps[i], index: i };
|
||
await rollReadMotion(d);
|
||
roll.loading = null;
|
||
roll.fit = true;
|
||
rollStatus(); rollHud(); rollInspector(); rollInvalidate();
|
||
}
|
||
const rollNorm = (r) => ({ n: r.n, notes: r.notes.slice(), time: r.time, flags: r.flags, vel: r.vel, hit: r.hit | 0, acc: r.acc | 0,
|
||
chance: r.chance ?? 100, ratchet: r.ratchet ?? 1, lanes: r.lanes ? r.lanes.slice() : [0, 0, 0, 0, 0, 0, 0, 0] });
|
||
/* MOTION op 7 (1.1): the records with their kinds; firmware without locks: the query (every record automation) */
|
||
function rollParseMotion(a, kinds) {
|
||
const r = new Reader(a), o = { track: r.b(), rc: r.b(), on: !!r.b(), count: r.b(), max: r.b(), events: [] };
|
||
for (let i = 0; i < o.count; i++) o.events.push({ step: r.b(), param: r.b(), value: r.v(), kind: 0 });
|
||
if (kinds) for (const e of o.events) e.kind = r.b();
|
||
return o;
|
||
}
|
||
async function rollReadMotion(d = dev) {
|
||
if (!d.info.motionMax) { roll.motion = null; return; }
|
||
const k = !!d.info.locks;
|
||
roll.motion = rollParseMotion(await sessionRequest(d, [CMD.MOTION, k ? [roll.track, 7] : [roll.track]]), k);
|
||
}
|
||
async function rollMotionOp(op, step, param, value) {
|
||
const k = !!dev.info.locks, args = [roll.track, op];
|
||
if (op === 3 || op === 5) args.push(step & 63, param & 127, ...v14enc(value));
|
||
else if (op === 4) args.push(step & 63, param & 127);
|
||
else if (op === 6) args.push(step);
|
||
const m = rollParseMotion(await rq([CMD.MOTION, args]), k && op >= 5);
|
||
if (m.rc) throw new Error(t(m.rc === 2 ? "rollFull" : m.rc === 3 ? "songBusy" : "rollRefused"));
|
||
if (op < 5 && k) await rollReadMotion(); else roll.motion = m;
|
||
}
|
||
|
||
/* ---------------------------------------------------------- writing --- */
|
||
/* steps written as a batch (one UNDO point); the device answers each with the step as it took it */
|
||
async function rollWrite(changes, undoable = true) {
|
||
const d = dev, tr = roll.track, lanes = !!d.info.laneModes;
|
||
if (!changes.length) return;
|
||
if (undoable) { roll.undo.push({ track: tr, steps: changes.map(([i]) => [i, rollCopy(roll.steps[i])]) }); if (roll.undo.length > 40) roll.undo.shift(); }
|
||
for (const [i, s] of changes) roll.steps[i] = rollCopy(s);
|
||
rollInvalidate(); rollInspector();
|
||
for (const [i, s] of changes) {
|
||
const st = { ...s, chance: d.info.chance ? s.chance : undefined, ratchet: d.info.ratchet ? s.ratchet : undefined, lanes: lanes ? s.lanes : null };
|
||
if (st.chance == null) delete st.chance;
|
||
if (st.ratchet == null) delete st.ratchet;
|
||
const r = rollNorm(parse[CMD.TRACK_STEP](await sessionRequest(d, req.trackStep(tr, i, st), { key: `rstep:${tr}:${i}` })));
|
||
if (d !== dev || roll.track !== tr) return;
|
||
roll.steps[i] = r;
|
||
if (tr === (d.sel || 0)) { d.steps[i] = { ...r, index: i }; stepEdit.set(i, performance.now()); }
|
||
}
|
||
if (tr === (d.sel || 0) && typeof updateStepRows === "function" && d.steps.length) updateStepRows();
|
||
rollInvalidate(); rollInspector();
|
||
}
|
||
/* the roll's operations one after another (a read never between a batch's writes) */
|
||
let rollChain = Promise.resolve();
|
||
function rollSerial(fn) { rollChain = rollChain.then(() => op(fn)); return rollChain; }
|
||
function rollDo(changes) { return rollSerial(() => rollWrite(changes)); }
|
||
async function rollParam(id, v) {
|
||
const d = dev, tr = roll.track;
|
||
const r = parse[CMD.TRACK_PARAM](await sessionRequest(d, req.trackParam(tr, id, v), { key: `rpar:${tr}:${id}` }));
|
||
if (d !== dev || roll.track !== tr) return;
|
||
roll.p[id] = r.value;
|
||
if (tr === (d.sel || 0) && d.dump) { d.dump.p[id] = r.value; showValue(key(0, id), r.value, false); }
|
||
rollHud(); rollInvalidate();
|
||
}
|
||
|
||
/* ---------------------------------------------------------- geometry --- */
|
||
const RG = { STRIP: 30, RULER: 18, LOCK: 8, LANE: 68 };
|
||
function rollGeom() {
|
||
const cv = roll.cv, w = cv.clientWidth, h = cv.clientHeight, touch = rollTouch();
|
||
const kw = touch ? 46 : 40, gy = RG.STRIP + RG.RULER, gh = h - gy - RG.LOCK - RG.LANE;
|
||
return { w, h, kw, gx: kw, gw: w - kw, gy, gh, ly: gy + gh + RG.LOCK, touch };
|
||
}
|
||
function rollFit() {
|
||
const g = rollGeom(), touch = g.touch;
|
||
const len = rollLen();
|
||
roll.view.cw = Math.max(touch ? 40 : 24, Math.min(64, g.gw / Math.min(len, touch ? 8 : 16)));
|
||
roll.view.rh = rollDrum() ? g.gh / 8 : touch ? 40 : 18;
|
||
roll.view.sx = 0;
|
||
/* the notes in view: the pattern's range centred (ui_graph.c pat_range) */
|
||
let lo = 127, hi = -1;
|
||
for (const s of roll.steps.slice(0, len)) if (s.time === 0) for (const n of s.notes.slice(0, s.n)) { lo = Math.min(lo, n); hi = Math.max(hi, n); }
|
||
if (hi < lo) lo = hi = 60;
|
||
const rows = g.gh / roll.view.rh;
|
||
roll.view.top = Math.max(rows - 1, Math.min(127, (lo + hi) / 2 + rows / 2));
|
||
rollClamp();
|
||
}
|
||
function rollClamp() {
|
||
const g = rollGeom(), v = roll.view, ns = dev ? dev.info.nstep : 64;
|
||
v.cw = Math.max(g.touch ? 14 : 8, Math.min(120, v.cw));
|
||
v.sx = Math.max(0, Math.min(Math.max(0, ns - g.gw / v.cw), v.sx));
|
||
if (rollDrum()) { v.rh = g.gh / 8; v.top = 0; return; }
|
||
v.rh = Math.max(g.touch ? 14 : 8, Math.min(60, v.rh));
|
||
const rows = g.gh / v.rh;
|
||
v.top = Math.max(Math.min(127, rows - 1), Math.min(127, v.top));
|
||
}
|
||
/* a canvas point -> {area, step, note | lane} */
|
||
function rollHit(x, y) {
|
||
const g = rollGeom(), v = roll.view;
|
||
const step = Math.floor(v.sx + (x - g.gx) / v.cw);
|
||
if (y < RG.STRIP) return { area: "strip", bar: Math.floor((x - g.gx) / (g.gw / 4)) };
|
||
if (y < g.gy) return { area: "ruler", step };
|
||
if (y < g.gy + g.gh) {
|
||
if (x < g.gx) return { area: "keys", note: Math.round(v.top - (y - g.gy) / v.rh + 0.5 - 0.5), lane: Math.floor((y - g.gy) / v.rh) };
|
||
if (rollDrum()) return { area: "grid", step, lane: Math.floor((y - g.gy) / v.rh) };
|
||
return { area: "grid", step, note: Math.ceil(v.top - (y - g.gy) / v.rh) };
|
||
}
|
||
if (y < g.ly) return { area: "locks", step };
|
||
return { area: "lane", step, value: 1 - (y - g.ly - 6) / (RG.LANE - 12) };
|
||
}
|
||
|
||
/* ---------------------------------------------------------- drawing --- */
|
||
function rollDraw() {
|
||
const cv = roll.cv;
|
||
if (!cv || !roll.open || !dev || !roll.p || !cv.clientWidth) return;
|
||
if (roll.fit) { roll.fit = false; rollFit(); }
|
||
const dpr = devicePixelRatio || 1, g = rollGeom();
|
||
if (cv.width !== Math.round(g.w * dpr) || cv.height !== Math.round(g.h * dpr)) { cv.width = Math.round(g.w * dpr); cv.height = Math.round(g.h * dpr); }
|
||
const c = cv.getContext("2d"), C = RPAL.C, v = roll.view, len = rollLen(), ns = dev.info.nstep, drum = rollDrum();
|
||
c.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||
c.fillStyle = C.bg; c.fillRect(0, 0, g.w, g.h);
|
||
const colX = (i) => g.gx + (i - v.sx) * v.cw;
|
||
const first = Math.max(0, Math.floor(v.sx)), last = Math.min(ns - 1, Math.ceil(v.sx + g.gw / v.cw));
|
||
const sel = roll.sel, locks = new Map(), autos = new Map();
|
||
for (const e of roll.motion ? roll.motion.events : []) (e.kind ? locks : autos).set(e.step, ((e.kind ? locks : autos).get(e.step) || 0) + 1);
|
||
const fS = (px) => `500 ${px}px "Chakra Petch", "IBM Plex Mono", ui-monospace, monospace`;
|
||
const fM = (px) => `600 ${px}px "Inter Tight", "Instrument Sans", system-ui, sans-serif`;
|
||
/* LENTE's BAR (ui_graph.c bar_cell): the four bars as cells, each a tiny roll, the bars in view framed THEME */
|
||
{
|
||
let lo = 127, hi = -1;
|
||
for (const s of roll.steps.slice(0, len)) if (s.time === 0) for (const n of s.notes.slice(0, s.n)) { lo = Math.min(lo, n); hi = Math.max(hi, n); }
|
||
if (hi < lo) lo = hi = 60;
|
||
if (hi - lo < 29) { lo -= Math.floor((29 - (hi - lo)) / 2); hi = lo + 29; }
|
||
const bw = g.gw / 4;
|
||
for (let b = 0; b < 4; b++) {
|
||
const x = g.gx + b * bw + 1, y = 2, w = bw - 2, h = RG.STRIP - 6, inView = b * 16 < v.sx + g.gw / v.cw && (b + 1) * 16 > v.sx;
|
||
if (b * 16 >= len) { c.fillStyle = C.bg; c.fillRect(x, y, w, h); c.strokeStyle = C.line; c.strokeRect(x + .5, y + .5, w - 1, h - 1); continue; }
|
||
rrect(c, x, y, w, h, 3, C.raise);
|
||
if (inView) { c.strokeStyle = C.theme; c.lineWidth = 1; c.beginPath(); c.roundRect(x + .5, y + .5, w - 1, h - 1, 3); c.stroke(); }
|
||
const sw = w - 4, top = y + 3, nh = h - 5;
|
||
for (let i = 0; i < 16 && b * 16 + i < len; i++) {
|
||
const s = roll.steps[b * 16 + i], sx = x + 2 + i * sw / 16, mw = Math.max(1, sw / 16 - 1);
|
||
if (!s || s.time !== 0 || !(s.n || s.hit)) continue;
|
||
if (drum) { const ln = stepLanes(s); for (let l = 0; l < 8; l++) if (ln >> l & 1) { c.fillStyle = RPAL.lz(s, stepAccents(s) >> l & 1, -1); c.fillRect(sx, top + l * nh / 8, mw, Math.max(1, Math.min(2, nh / 8))); } continue; }
|
||
if (!s.n) continue;
|
||
c.fillStyle = RPAL.lz(s, s.flags & 1, s.notes[0]);
|
||
c.fillRect(sx, top + nh - 2 - (s.notes[0] - lo) * (nh - 2) / (hi - lo), mw, 2);
|
||
}
|
||
c.fillStyle = inView ? C.theme : C.mid; c.font = fS(10); c.textBaseline = "top"; c.fillText(String(b + 1), x + 3, y + 2);
|
||
}
|
||
c.fillStyle = C.mid; c.font = fS(10); c.textBaseline = "middle"; c.fillText(drum ? "GRID" : "ROLL", 4, RG.STRIP / 2);
|
||
}
|
||
c.save(); c.beginPath(); c.rect(g.gx, RG.STRIP, g.gw, g.h - RG.STRIP); c.clip();
|
||
/* the ruler: the step numbers, the beats brighter, LEN's end THEME */
|
||
for (let i = first; i <= last; i++) {
|
||
const x = colX(i);
|
||
c.fillStyle = i % 4 === 0 ? C.text : C.dim; c.font = fS(v.cw < 18 ? 9 : 11); c.textBaseline = "middle";
|
||
if (i % 4 === 0 || v.cw >= 22) c.fillText(String(i + 1), x + 3, RG.STRIP + RG.RULER / 2);
|
||
}
|
||
/* rows: the scale's tinted (ui_graph.c graph_roll), or the lanes (graph_grid) */
|
||
const gy = g.gy, gb = gy + g.gh;
|
||
if (drum) {
|
||
for (let l = 0; l < 8; l++) { const y = gy + l * v.rh; c.fillStyle = l === roll.lane ? C.raise : C.surf; c.fillRect(g.gx, y, g.gw, v.rh - 1); }
|
||
} else {
|
||
const mask = R_SCALE[Math.max(0, Math.min(15, roll.p[RP.SCALE] | 0))], root = roll.p[RP.ROOT] | 0;
|
||
const rows = Math.ceil(g.gh / v.rh) + 1;
|
||
for (let r = 0; r < rows; r++) {
|
||
const n = Math.floor(v.top) - r; if (n < 0) break;
|
||
const pc = n % 12;
|
||
const inS = mask === 0xFFF ? !R_KB[pc] : (mask >> ((n - root + 120) % 12)) & 1;
|
||
if (inS) { c.fillStyle = C.lane; c.fillRect(g.gx, rowY(n), g.gw, v.rh); }
|
||
if (pc === 0) { c.fillStyle = C.raise; c.fillRect(g.gx, rowY(n) + v.rh - 1, g.gw, 1); }
|
||
}
|
||
}
|
||
/* the step lines, the beats brighter; past LEN dark */
|
||
for (let i = first; i <= last + 1; i++) { c.fillStyle = i % 4 ? C.grid : C.line; c.fillRect(Math.round(colX(i)), gy, 1, g.gh); }
|
||
if (len < ns) {
|
||
const x = colX(len);
|
||
c.fillStyle = "rgba(0,0,0,.62)"; c.fillRect(x, gy, g.gw + g.gx - x, g.gh);
|
||
c.fillStyle = C.theme; c.fillRect(Math.round(x) - 1, RG.STRIP, 2, g.h - RG.STRIP);
|
||
}
|
||
/* EUCLID's preview: the steps it would write, outlined */
|
||
if (roll.euPrev) for (let i = first; i <= last; i++) {
|
||
const s = roll.euPrev[i]; if (!s || i >= len) continue;
|
||
c.strokeStyle = C.accent; c.lineWidth = 1;
|
||
if (drum) { const ln = stepLanes(s); for (let l = 0; l < 8; l++) if (ln >> l & 1) c.strokeRect(colX(i) + 2.5, gy + l * v.rh + 2.5, v.cw - 5, v.rh - 6); }
|
||
else if (s.time === 0) for (const n of s.notes.slice(0, s.n)) c.strokeRect(colX(i) + 1.5, rowY(n) + .5, v.cw - 3, v.rh - 2);
|
||
}
|
||
/* the notes / the hits */
|
||
for (let i = first; i <= last; i++) {
|
||
const s0 = roll.steps[i]; if (!s0) continue;
|
||
const x = colX(i), w = v.cw;
|
||
if (drum) {
|
||
const ln = s0.time === 0 ? stepLanes(s0) : 0, ac = stepAccents(s0), z = Math.min(w, v.rh) - 6;
|
||
for (let l = 0; l < 8; l++) {
|
||
const cx = x + w / 2, cy = gy + l * v.rh + (v.rh - 1) / 2;
|
||
if (ln >> l & 1) {
|
||
const col = RPAL.lz(s0, ac >> l & 1, -1), rat = s0.ratchet || 1, lm = s0.lanes ? s0.lanes[l] : 0;
|
||
splitRect(c, cx - z / 2, cy - z / 2, z, z, col, rat, 3);
|
||
if (lm) { c.fillStyle = "#000"; c.font = fM(Math.max(9, Math.min(14, z * .42))); c.textAlign = "center"; c.textBaseline = "middle"; c.fillText(R_LM1[lm], cx, cy + 1); c.textAlign = "start"; }
|
||
if (sel && sel.step === i && sel.lane === l) { c.strokeStyle = C.theme; c.lineWidth = 2; c.strokeRect(cx - z / 2 - 2, cy - z / 2 - 2, z + 4, z + 4); }
|
||
} else { c.fillStyle = i % 4 === 0 || l === roll.lane ? C.mid : C.dim; c.fillRect(cx - 1, cy - 1, 2, 2); }
|
||
}
|
||
continue;
|
||
}
|
||
const src = rollSrc(i); if (src < 0) continue;
|
||
const s = roll.steps[src], nx = roll.steps[(i + 1) % len], tieIn = src !== i;
|
||
const slide = !!(s.flags & 2) && (s.ratchet || 1) === 1 && nx && nx.time === 0 && nx.n;
|
||
for (let k = 0; k < s.n; k++) {
|
||
const n = s.notes[k], y = rowY(n), hsel = sel && sel.step === src && sel.note === n;
|
||
const col = hsel ? C.accent : RPAL.lz(s, s.flags & 1, n);
|
||
const bx = tieIn ? x - 1 : x + 1, bw = tieIn ? w + 1 : w - 2 + (slide && !tieIn ? 2 : 0);
|
||
if (y + v.rh < gy || y > gb) { /* out of view: a 1 px mark at the edge */
|
||
c.fillStyle = col; c.fillRect(bx, y < gy ? gy : gb - 1, bw, 1); continue;
|
||
}
|
||
splitRect(c, bx, y + 1, bw, v.rh - 2, col, tieIn ? 1 : s.ratchet || 1, 0);
|
||
if (!tieIn && v.rh >= 16 && w >= 26) { c.fillStyle = "#000"; c.font = fS(Math.min(11, v.rh - 6)); c.textBaseline = "middle"; c.fillText(noteName(n), bx + 3, y + v.rh / 2); }
|
||
}
|
||
if (s.hit && !tieIn) { /* a melodic track's hits: a small chip at the column's top */
|
||
c.fillStyle = RPAL.lz(s, 0, -1); c.fillRect(x + 3, gy + 2, w - 6, 3);
|
||
}
|
||
}
|
||
/* the selected step: a frame round its column (TEXT) */
|
||
if (sel && sel.step >= first && sel.step <= last) { c.strokeStyle = C.text; c.lineWidth = 1; c.strokeRect(Math.round(colX(sel.step)) + .5, gy + .5, Math.round(v.cw), g.gh - 1); }
|
||
/* the locks (ACCENT) and the automation (THEME): marks at the columns' foot */
|
||
for (let i = first; i <= last; i++) {
|
||
const x = colX(i), y = g.ly - RG.LOCK;
|
||
if (locks.get(i)) { c.fillStyle = C.accent; c.fillRect(x + 3, y + 2, v.cw - 6, 3); }
|
||
if (autos.get(i)) { c.fillStyle = C.theme; c.fillRect(x + 3, y + 6, Math.max(2, (v.cw - 6) / 2), 2); }
|
||
}
|
||
/* the value lane: VEL / CHANCE / RATCH, each value as heat */
|
||
c.fillStyle = C.surf; c.fillRect(g.gx, g.ly, g.gw, RG.LANE);
|
||
for (let i = first; i <= last; i++) {
|
||
const s = roll.steps[i]; if (!s) continue;
|
||
const on = s.time === 0 && (s.n || s.hit), x = colX(i), lh = RG.LANE - 12;
|
||
const val = roll.vlane === "vel" ? (s.vel || 96) / 127 : roll.vlane === "chance" ? (s.chance ?? 100) / 100 : ((s.ratchet || 1) - 1) / 3;
|
||
c.fillStyle = on ? RPAL.heat(Math.round(val * 232) + 24) : C.line;
|
||
const bh = Math.max(2, val * lh);
|
||
c.fillRect(x + Math.max(2, v.cw * .2), g.ly + 6 + lh - bh, Math.max(2, v.cw * .6), on ? bh : 2);
|
||
}
|
||
c.restore();
|
||
/* the keys at the left (ui_graph.c pr_keys), or the lanes' names (graph_grid) */
|
||
c.fillStyle = C.bg; c.fillRect(0, gy, g.kw, g.h - gy);
|
||
if (drum) {
|
||
for (let l = 0; l < 8; l++) {
|
||
const y = gy + l * v.rh;
|
||
c.fillStyle = l === roll.lane ? C.raise : C.surf; c.fillRect(0, y, g.kw - 2, v.rh - 1);
|
||
c.fillStyle = l === roll.lane ? C.accent : C.mid; c.font = fS(12); c.textBaseline = "middle"; c.fillText(R_ABBR[l], 8, y + v.rh / 2);
|
||
}
|
||
} else {
|
||
const lit = new Set(), root = roll.p[RP.ROOT] | 0;
|
||
if (sel) { const sr = rollSrc(sel.step); if (sr >= 0) roll.steps[sr].notes.slice(0, roll.steps[sr].n).forEach((n) => lit.add(n)); }
|
||
c.save(); c.beginPath(); c.rect(0, gy, g.kw, g.gh); c.clip();
|
||
for (let n = Math.floor(v.top); n >= 0 && rowY(n) < gb; n--) {
|
||
const y = rowY(n), pc = n % 12;
|
||
c.fillStyle = lit.has(n) ? C.text : R_KB[pc] ? C.bg : C.mid;
|
||
c.fillRect(6, y, g.kw - 8, v.rh - 1);
|
||
if ((n - root + 120) % 12 === 0) { c.fillStyle = C.theme; c.fillRect(1, y, 3, v.rh - 1); }
|
||
if (pc === 0 && v.rh >= 11) { c.fillStyle = lit.has(n) || !R_KB[pc] ? "#000" : C.mid; c.font = fS(Math.min(11, v.rh - 3)); c.textBaseline = "middle"; c.fillText(noteName(n), 9, y + v.rh / 2); }
|
||
}
|
||
c.restore();
|
||
}
|
||
c.fillStyle = C.mid; c.font = fS(10); c.textBaseline = "middle";
|
||
c.fillText(roll.vlane === "vel" ? "VEL" : roll.vlane === "chance" ? "CHNC" : "RATCH", 4, g.ly + RG.LANE / 2);
|
||
c.fillText("LOCK", 4, g.ly - RG.LOCK / 2);
|
||
roll.dirty = false;
|
||
function rowY(n) { return gy + (v.top - n) * v.rh; }
|
||
}
|
||
function rrect(c, x, y, w, h, r, fill) { c.fillStyle = fill; c.beginPath(); c.roundRect(x, y, w, h, r); c.fill(); }
|
||
/* ui_graph.c pr_split: a box in its RATCH parts, 1 px apart */
|
||
function splitRect(c, x, y, w, h, col, parts, r) {
|
||
c.fillStyle = col;
|
||
if (parts < 2) { if (r) { c.beginPath(); c.roundRect(x, y, w, h, r); c.fill(); } else c.fillRect(x, y, w, h); return; }
|
||
const pw = (w - parts + 1) / parts;
|
||
for (let k = 0; k < parts; k++) c.fillRect(x + k * (pw + 1), y, pw, h);
|
||
}
|
||
|
||
/* ---------------------------------------------------------- the pointer --- */
|
||
/* one finger / the mouse: a tap adds (an empty cell), selects (a note, a hit) or removes (the selected one); a drag
|
||
on a note moves it (up / down: its pitch) or draws its length (right: TIE steps after it); a drag elsewhere scrolls;
|
||
two fingers pinch (across: the steps, up and down: the notes). The wheel scrolls, with Ctrl / ⌘ it zooms */
|
||
const rptr = new Map();
|
||
let rgest = null;
|
||
function rollPointerDown(e) {
|
||
const cv = roll.cv;
|
||
cv.setPointerCapture(e.pointerId);
|
||
const pt = rollPt(e);
|
||
rptr.set(e.pointerId, pt);
|
||
if (rptr.size === 2) { /* a pinch */
|
||
const [a, b] = [...rptr.values()];
|
||
rgest = { kind: "pinch", dx: Math.abs(a.x - b.x) || 1, dy: Math.abs(a.y - b.y) || 1, cw: roll.view.cw, rh: roll.view.rh,
|
||
cx: (a.x + b.x) / 2, cy: (a.y + b.y) / 2, sx: roll.view.sx, top: roll.view.top };
|
||
return;
|
||
}
|
||
if (rptr.size > 2) return;
|
||
const h = rollHit(pt.x, pt.y);
|
||
rgest = { kind: "press", x0: pt.x, y0: pt.y, hit: h, sx: roll.view.sx, top: roll.view.top, moved: false, t0: performance.now() };
|
||
if (h.area === "grid" && !rollDrum()) {
|
||
const src = rollSrc(h.step);
|
||
if (src >= 0 && roll.steps[src].notes.slice(0, roll.steps[src].n).includes(h.note)) rgest.note = { src, n: h.note };
|
||
}
|
||
if (h.area === "lane") { rgest.kind = "lane"; rgest.changes = new Map(); rollLaneAt(h, rgest); }
|
||
}
|
||
function rollPt(e) { const r = roll.cv.getBoundingClientRect(); return { x: e.clientX - r.left, y: e.clientY - r.top }; }
|
||
function rollPointerMove(e) {
|
||
if (!rptr.has(e.pointerId)) return;
|
||
const pt = rollPt(e); rptr.set(e.pointerId, pt);
|
||
const gs = rgest; if (!gs) return;
|
||
const v = roll.view, g = rollGeom();
|
||
if (gs.kind === "pinch" && rptr.size >= 2) {
|
||
const [a, b] = [...rptr.values()];
|
||
const dx = Math.abs(a.x - b.x) || 1, dy = Math.abs(a.y - b.y) || 1;
|
||
const sAtC = gs.sx + (gs.cx - g.gx) / gs.cw, nAtC = gs.top - (gs.cy - g.gy) / gs.rh;
|
||
if (gs.dx > 30) v.cw = gs.cw * dx / gs.dx;
|
||
if (gs.dy > 30 && !rollDrum()) v.rh = gs.rh * dy / gs.dy;
|
||
rollClamp();
|
||
const cx = (a.x + b.x) / 2, cy = (a.y + b.y) / 2;
|
||
v.sx = sAtC - (cx - g.gx) / v.cw; if (!rollDrum()) v.top = nAtC + (cy - g.gy) / v.rh;
|
||
rollClamp(); rollInvalidate(); return;
|
||
}
|
||
if (gs.kind === "lane") { rollLaneAt(rollHit(pt.x, pt.y), gs); return; }
|
||
const ddx = pt.x - gs.x0, ddy = pt.y - gs.y0;
|
||
if (!gs.moved && Math.hypot(ddx, ddy) < (g.touch ? 10 : 5)) return;
|
||
if (!gs.moved) {
|
||
gs.moved = true;
|
||
if (gs.note) gs.kind = Math.abs(ddy) > Math.abs(ddx) ? "pitch" : "length";
|
||
else if (gs.hit.area === "strip") gs.kind = "none";
|
||
else gs.kind = "pan";
|
||
}
|
||
if (gs.kind === "pan") {
|
||
v.sx = gs.sx - ddx / v.cw;
|
||
if (!rollDrum()) v.top = gs.top + ddy / v.rh;
|
||
rollClamp(); rollInvalidate();
|
||
} else if (gs.kind === "pitch") {
|
||
const d = Math.round(-ddy / v.rh), n = Math.max(0, Math.min(127, gs.note.n + d)), s = roll.steps[gs.note.src];
|
||
if (!gs.base) gs.base = rollCopy(s);
|
||
const k = gs.base.notes.indexOf(gs.note.n), nn = gs.base.notes.slice();
|
||
if (k >= 0 && (!gs.base.notes.slice(0, gs.base.n).includes(n) || n === gs.note.n)) { nn[k] = n; roll.steps[gs.note.src] = { ...gs.base, notes: nn }; roll.sel = { step: gs.note.src, note: n }; }
|
||
rollInvalidate();
|
||
} else if (gs.kind === "length") {
|
||
const h = rollHit(pt.x, pt.y), len = dev.info.nstep; /* (past LEN too: the steps are there) */
|
||
gs.to = Math.max(gs.note.src, Math.min(len - 1, h.step));
|
||
if (!gs.base) { gs.base = roll.steps.map(rollCopy); }
|
||
for (let i = gs.note.src + 1; i < len; i++) {
|
||
const b = gs.base[i];
|
||
if (i <= gs.to) roll.steps[i] = { ...rollEmpty(), time: 1 };
|
||
else if (b.time === 1 && rollSrcIn(gs.base, i) === gs.note.src) roll.steps[i] = { ...rollEmpty() };
|
||
else roll.steps[i] = rollCopy(b);
|
||
}
|
||
rollInvalidate();
|
||
}
|
||
}
|
||
function rollSrcIn(steps, i) { for (let j = i; j >= 0; j--) { if (steps[j].time === 0) return j; if (steps[j].time === 2) return -1; } return -1; }
|
||
function rollPointerUp(e) {
|
||
if (!rptr.has(e.pointerId)) return;
|
||
rptr.delete(e.pointerId);
|
||
const gs = rgest;
|
||
if (rptr.size) { if (gs && gs.kind === "pinch") rgest = { kind: "none" }; return; }
|
||
rgest = null;
|
||
if (!gs || e.type === "pointercancel") { if (gs && gs.base && gs.kind === "pitch") { roll.steps[gs.note.src] = gs.base; rollInvalidate(); } return; }
|
||
if (gs.kind === "lane") { const ch = [...gs.changes].map(([i, s]) => [i, s]); if (ch.length) rollDo(ch); return; }
|
||
if (gs.kind === "pitch" && gs.base) {
|
||
const after = rollCopy(roll.steps[gs.note.src]); roll.steps[gs.note.src] = gs.base;
|
||
if (after.notes.join() !== gs.base.notes.join()) rollDo([[gs.note.src, after]]);
|
||
return;
|
||
}
|
||
if (gs.kind === "length" && gs.base) {
|
||
const ch = [];
|
||
for (let i = 0; i < dev.info.nstep; i++) if (JSON.stringify(roll.steps[i]) !== JSON.stringify(gs.base[i])) ch.push([i, rollCopy(roll.steps[i])]);
|
||
gs.base.forEach((s, i) => { roll.steps[i] = s; });
|
||
rollDo(ch); return;
|
||
}
|
||
if (gs.moved) return;
|
||
rollTap(gs.hit);
|
||
}
|
||
function rollTap(h) {
|
||
const len = rollLen();
|
||
if (h.area === "strip") { if (h.bar >= 0 && h.bar < 4) { roll.view.sx = h.bar * 16; rollClamp(); rollInvalidate(); } return; }
|
||
if (h.area === "ruler" || h.area === "locks" || h.area === "keys") {
|
||
if (h.area === "keys" && rollDrum() && h.lane >= 0 && h.lane < 8) { roll.lane = h.lane; rollInvalidate(); rollInspector(); return; }
|
||
if (h.step >= 0 && h.step < dev.info.nstep && h.area !== "keys") { roll.sel = { step: h.step }; rollInvalidate(); rollInspector(); }
|
||
return;
|
||
}
|
||
if (h.area !== "grid" || h.step < 0 || h.step >= dev.info.nstep) return;
|
||
const i = h.step, s = rollCopy(roll.steps[i]);
|
||
if (rollDrum()) {
|
||
if (h.lane < 0 || h.lane > 7) return;
|
||
roll.lane = h.lane;
|
||
const b = 1 << h.lane, on = s.time === 0 && stepLanes(s) & b;
|
||
if (on && roll.sel && roll.sel.step === i && roll.sel.lane === h.lane) { /* the selected hit, tapped again: off */
|
||
s.hit &= ~b; s.acc &= ~b; s.lanes[h.lane] = 0;
|
||
const keep = s.notes.slice(0, s.n).filter((n) => drumLane(n) !== h.lane);
|
||
s.n = keep.length; s.notes = keep.concat([0, 0, 0, 0]).slice(0, 4);
|
||
if (!s.n && !s.hit) s.time = 2;
|
||
roll.sel = { step: i, lane: h.lane };
|
||
rollDo([[i, s]]);
|
||
} else if (on) { roll.sel = { step: i, lane: h.lane }; rollInvalidate(); rollInspector(); }
|
||
else {
|
||
if (s.time !== 0) { Object.assign(s, rollEmpty(), { time: 0 }); }
|
||
s.hit |= b; if (!s.vel) s.vel = 100;
|
||
roll.sel = { step: i, lane: h.lane };
|
||
rollDo([[i, s]]);
|
||
}
|
||
return;
|
||
}
|
||
if (h.note < 0 || h.note > 127) return;
|
||
const src = rollSrc(i);
|
||
if (src >= 0 && roll.steps[src].notes.slice(0, roll.steps[src].n).includes(h.note)) {
|
||
if (roll.sel && roll.sel.step === src && roll.sel.note === h.note) { /* tapped again: removed */
|
||
const x = rollCopy(roll.steps[src]), keep = x.notes.slice(0, x.n).filter((n) => n !== h.note);
|
||
x.n = keep.length; x.notes = keep.concat([0, 0, 0, 0]).slice(0, 4);
|
||
const ch = [[src, x]];
|
||
if (!x.n && !x.hit) { /* the last note: the step and its TIEs rest */
|
||
x.time = 2;
|
||
for (let j = src + 1; j < len && roll.steps[j].time === 1; j++) ch.push([j, rollEmpty()]);
|
||
}
|
||
roll.sel = { step: src };
|
||
rollDo(ch);
|
||
} else { roll.sel = { step: src, note: h.note }; rollInvalidate(); rollInspector(); }
|
||
return;
|
||
}
|
||
if (s.time !== 0) { Object.assign(s, rollEmpty(), { time: 0, vel: roll.lastVel || 100, chance: s.chance, ratchet: s.ratchet }); }
|
||
if (s.n >= 4) { sayK("rollChordFull"); return; }
|
||
s.notes[s.n++] = h.note; if (!s.vel) s.vel = roll.lastVel || 100;
|
||
roll.sel = { step: i, note: h.note };
|
||
rollDo([[i, s]]);
|
||
}
|
||
function rollLaneAt(h, gs) {
|
||
if (h.step < 0 || h.step >= dev.info.nstep) return;
|
||
const base = gs.changes.get(h.step) || rollCopy(roll.steps[h.step]);
|
||
const v = Math.max(0, Math.min(1, h.value));
|
||
if (roll.vlane === "vel") base.vel = Math.max(1, Math.round(v * 127));
|
||
else if (roll.vlane === "chance") base.chance = Math.round(v * 100);
|
||
else base.ratchet = 1 + Math.round(v * 3);
|
||
gs.changes.set(h.step, base);
|
||
roll.steps[h.step] = base; rollInvalidate();
|
||
}
|
||
function rollWheel(e) {
|
||
e.preventDefault();
|
||
const v = roll.view, g = rollGeom(), pt = rollPt(e);
|
||
if (e.ctrlKey || e.metaKey) {
|
||
const k = Math.exp(-e.deltaY * 0.0025), s = v.sx + (pt.x - g.gx) / v.cw;
|
||
if (e.shiftKey && !rollDrum()) v.rh *= k; else v.cw *= k;
|
||
rollClamp(); v.sx = s - (pt.x - g.gx) / v.cw;
|
||
} else if (e.shiftKey || Math.abs(e.deltaX) > Math.abs(e.deltaY)) v.sx += (e.deltaX || e.deltaY) / v.cw;
|
||
else if (!rollDrum()) v.top -= e.deltaY / v.rh;
|
||
rollClamp(); rollInvalidate();
|
||
}
|
||
function rollKey(e) {
|
||
const s = roll.sel; if (!s || !dev) return;
|
||
const i = s.step, st = rollCopy(roll.steps[i]);
|
||
if (e.key === "ArrowLeft" || e.key === "ArrowRight") { roll.sel = { step: Math.max(0, Math.min(dev.info.nstep - 1, i + (e.key === "ArrowRight" ? 1 : -1))) }; rollInvalidate(); rollInspector(); e.preventDefault(); return; }
|
||
if ((e.key === "ArrowUp" || e.key === "ArrowDown") && s.note != null && !rollDrum()) {
|
||
const k = st.notes.indexOf(s.note), n = Math.max(0, Math.min(127, s.note + (e.key === "ArrowUp" ? 1 : -1) * (e.shiftKey ? 12 : 1)));
|
||
if (k >= 0 && !st.notes.slice(0, st.n).includes(n)) { st.notes[k] = n; roll.sel = { step: i, note: n }; rollDo([[i, st]]); }
|
||
e.preventDefault(); return;
|
||
}
|
||
if (e.key === "Delete" || e.key === "Backspace") { rollClearStep(i); e.preventDefault(); }
|
||
if (e.key === "a" || e.key === "A") { st.flags ^= 1; rollDo([[i, st]]); }
|
||
if ((e.key === "s" || e.key === "S") && !rollDrum()) { st.flags ^= 2; rollDo([[i, st]]); }
|
||
if ((e.key === "z" || e.key === "Z") && (e.ctrlKey || e.metaKey)) { rollUndo(); e.preventDefault(); }
|
||
}
|
||
function rollClearStep(i) {
|
||
const ch = [[i, { ...rollEmpty(), chance: roll.steps[i].chance, ratchet: 1 }]];
|
||
for (let j = i + 1; j < rollLen() && roll.steps[j].time === 1; j++) ch.push([j, rollEmpty()]);
|
||
roll.sel = { step: i };
|
||
rollDo(ch);
|
||
}
|
||
function rollUndo() {
|
||
const u = roll.undo.pop();
|
||
if (!u || u.track !== roll.track) { sayK("rollNoUndo"); return; }
|
||
rollSerial(() => rollWrite(u.steps, false));
|
||
}
|
||
|
||
/* ---------------------------------------------------------- the HUD and the inspector --- */
|
||
/* LEN DIV SWING GATE OFS PIT as the device's cards: the name small, the value large in its heat, a bar of how much;
|
||
- / + (40 px) and a drag across the card */
|
||
const R_CARDS = [[RP.SLEN, "LEN"], [RP.SDIV, "DIV"], [RP.SSWING, "SWING"], [RP.SGATE, "GATE"], [RP.SOFS, "OFS"], [RP.SPOFS, "PIT"]];
|
||
function rollDesc(id) { return dev && dev.pdesc[id]; }
|
||
function rollHud() {
|
||
const box = $("rollhud");
|
||
if (!box || !roll.p) return;
|
||
if (!box.children.length) box.replaceChildren(...R_CARDS.map(([id, lb]) => rollCard(id, lb)));
|
||
for (const c of box.children) {
|
||
const id = +c.dataset.id, d = rollDesc(id), v = roll.p[id] ?? 0;
|
||
const lo = d ? d.min : 0, hi = d ? d.max : 127, ratio = Math.round((v - lo) * 1000 / ((hi - lo) || 1));
|
||
c.querySelector(".rv").textContent = d ? (([a, u]) => u && u !== "STEP" && u !== "ST" ? `${a} ${u}` : a)(fmtValue(d, v)) : String(v);
|
||
c.querySelector(".rv").style.color = RPAL.card(ratio, lo < 0);
|
||
c.querySelector(".rb i").style.width = `${ratio / 10}%`;
|
||
c.querySelector(".rb i").style.background = RPAL.card(ratio, lo < 0);
|
||
c.querySelector(".rl").textContent = d && d.label && d.label !== "-" ? d.label : c.dataset.lb;
|
||
}
|
||
}
|
||
function rollCard(id, lb) {
|
||
const step = (dir) => { const d = rollDesc(id); if (!d) return; const v = Math.max(d.min, Math.min(d.max, (roll.p[id] ?? 0) + dir)); if (v !== roll.p[id]) { roll.p[id] = v; rollHud(); op(() => rollParam(id, v)); } };
|
||
const card = el("div", { class: "rcard", "data-id": id, "data-lb": lb },
|
||
el("span", { class: "rl", text: lb }), el("span", { class: "rv" }), el("span", { class: "rb" }, el("i")),
|
||
el("span", { class: "rpm" }, el("button", { type: "button", "aria-label": `${lb} −`, text: "−", onclick: () => step(-1) }),
|
||
el("button", { type: "button", "aria-label": `${lb} +`, text: "+", onclick: () => step(1) })));
|
||
let drag = null;
|
||
card.addEventListener("pointerdown", (e) => { if (e.target.closest("button")) return; card.setPointerCapture(e.pointerId); drag = { x: e.clientX, v: roll.p[id] ?? 0 }; });
|
||
card.addEventListener("pointermove", (e) => {
|
||
if (!drag) return;
|
||
const d = rollDesc(id); if (!d) return;
|
||
const span = d.max - d.min, v = Math.max(d.min, Math.min(d.max, Math.round(drag.v + (e.clientX - drag.x) * span / 220)));
|
||
if (v !== roll.p[id]) { roll.p[id] = v; rollHud(); }
|
||
});
|
||
const end = () => { if (!drag) return; const v = roll.p[id]; if (v !== drag.v) op(() => rollParam(id, v)); drag = null; };
|
||
card.addEventListener("pointerup", end); card.addEventListener("pointercancel", end);
|
||
return card;
|
||
}
|
||
function rollStatus() {
|
||
const s = $("rollstat"); if (!s) return;
|
||
const eng = dev && dev.info.engines[roll.engine];
|
||
s.textContent = roll.loading != null ? `${t("rollReading")} ${roll.loading}/${dev ? dev.info.nstep : 64}` :
|
||
`T${roll.track + 1} · ${eng || ""} · ${rollDrum() ? t("rollGrid") : t("rollNotes")}`;
|
||
}
|
||
/* the selected step: its time, notes, velocity, accent, slide, chance, ratchet; a DRUM lane's accent and mode; its locks */
|
||
function rollInspector() {
|
||
const box = $("rollinsp");
|
||
if (!box || !dev) return;
|
||
const s = roll.sel;
|
||
if (!s || !roll.steps[s.step]) { box.replaceChildren(el("p", { class: "dim", text: t("rollPick") })); return; }
|
||
if (box.contains(document.activeElement) && document.activeElement.tagName === "INPUT" && document.activeElement.type !== "range") return;
|
||
const i = s.step, st = roll.steps[i], drum = rollDrum();
|
||
const put = (f) => { const x = rollCopy(roll.steps[i]); f(x); rollDo([[i, x]]); };
|
||
const seg = (vals, cur, on, lbl) => el("span", { class: "seg rseg", role: "group", "aria-label": lbl }, ...vals.map(([v, txt]) =>
|
||
el("button", { type: "button", "aria-pressed": v === cur ? "true" : "false", text: txt, onclick: () => on(v) })));
|
||
const range = (lbl, v, lo, hi, on) => {
|
||
const r = el("input", { type: "range", min: lo, max: hi, value: v, "aria-label": lbl });
|
||
const o = el("span", { class: "v", text: String(v) });
|
||
r.addEventListener("input", () => { o.textContent = r.value; });
|
||
r.addEventListener("change", () => on(+r.value));
|
||
return el("label", { class: "rrow" }, el("span", { text: lbl }), r, o);
|
||
};
|
||
const rows = [el("h3", { text: `${t("rollStep")} ${i + 1}${i >= rollLen() ? " · " + t("rollPastLen") : ""}` })];
|
||
rows.push(seg([[0, "NOTE"], [1, "TIE"], [2, "REST"]], st.time, (v) => put((x) => { x.time = v; if (v === 0 && !x.vel) x.vel = 100; }), t("time")));
|
||
if (!drum) {
|
||
const notes = st.notes.slice(0, st.n);
|
||
rows.push(el("div", { class: "rnotes" }, ...notes.map((n) => el("span", { class: "rchip", style: `--nc:${RPAL.note(n)}` },
|
||
el("button", { type: "button", text: "−", "aria-label": `${noteName(n)} −1`, onclick: () => put((x) => { const k = x.notes.indexOf(n); if (k >= 0 && n > 0 && !notes.includes(n - 1)) { x.notes[k] = n - 1; roll.sel = { step: i, note: n - 1 }; } }) }),
|
||
el("b", { text: noteName(n) }),
|
||
el("button", { type: "button", text: "+", "aria-label": `${noteName(n)} +1`, onclick: () => put((x) => { const k = x.notes.indexOf(n); if (k >= 0 && n < 127 && !notes.includes(n + 1)) { x.notes[k] = n + 1; roll.sel = { step: i, note: n + 1 }; } }) }),
|
||
el("button", { type: "button", text: "×", "aria-label": `${t("remove")} ${noteName(n)}`, onclick: () => put((x) => { const k = x.notes.slice(0, x.n).filter((m) => m !== n); x.n = k.length; x.notes = k.concat([0, 0, 0, 0]).slice(0, 4); if (!x.n && !x.hit) x.time = 2; }) }))),
|
||
notes.length ? "" : el("span", { class: "dim", text: t("rollTapToAdd") })));
|
||
}
|
||
rows.push(range("VEL", st.vel, 0, 127, (v) => { roll.lastVel = v; put((x) => { x.vel = v; }); }));
|
||
const tg = (lbl, on, f) => el("button", { type: "button", class: "tog", "aria-pressed": on ? "true" : "false", text: lbl, onclick: f });
|
||
rows.push(el("div", { class: "bar" },
|
||
tg("ACCENT", st.flags & 1, () => put((x) => { x.flags ^= 1; })),
|
||
drum ? "" : tg("SLIDE", st.flags & 2, () => put((x) => { x.flags ^= 2; })),
|
||
el("button", { type: "button", text: t("rollClear"), onclick: () => rollClearStep(i) })));
|
||
if (dev.info.chance) rows.push(range(t("chance").toUpperCase(), st.chance ?? 100, 0, 100, (v) => put((x) => { x.chance = v; })));
|
||
if (dev.info.ratchet) rows.push(el("div", { class: "rrow" }, el("span", { text: "RATCH" }), seg([1, 2, 3, 4].slice(0, dev.info.ratchet).map((k) => [k, "x" + k]), st.ratchet || 1, (v) => put((x) => { x.ratchet = v; }), "RATCH")));
|
||
if (drum) {
|
||
const l = s.lane ?? roll.lane, b = 1 << l, on = st.time === 0 && stepLanes(st) & b;
|
||
rows.push(el("h3", { text: `${LANES[l]}${on ? "" : " · " + t("rollNoHit")}` }));
|
||
if (on) {
|
||
rows.push(el("div", { class: "bar" }, tg(`${R_ABBR[l]} ACC`, st.acc & b, () => put((x) => { x.acc ^= b; x.acc &= x.hit; }))));
|
||
if (dev.info.laneModes) rows.push(el("div", { class: "rrow" }, el("span", { text: "HIT" }), seg(R_LM.map((n, k) => [k, n]), st.lanes[l] || 0, (v) => put((x) => { x.lanes[l] = v; }), "HIT")));
|
||
}
|
||
}
|
||
rows.push(el("p", { class: "dim rmiss", text: t("rollMicroMissing") }));
|
||
rows.push(rollLocksBox(i));
|
||
box.replaceChildren(...rows);
|
||
}
|
||
/* the step's locks and automation events (MOTION): each its value, removable; a lock added (op 5) */
|
||
function rollLocksBox(i) {
|
||
const d = dev, m = roll.motion;
|
||
if (!d.info.motionMax || !m) return el("span");
|
||
const evs = m.events.filter((e) => e.step === i), pe0 = d.info.pe0, pc = d.info.pcount;
|
||
const label = (id) => id === 127 ? "DJ FILT" : id >= pe0 && roll.track !== (d.sel || 0) ? `E${id - pe0 + 1}` : (d.pdesc[id] && d.pdesc[id].label) || `P${id}`;
|
||
const box = el("div", { class: "rlocks" }, el("h3", { text: `${t("rollLocks")} · ${m.count}/${m.max}` }));
|
||
for (const e of evs) {
|
||
const desc = d.pdesc[e.param], val = el("input", { type: "number", min: desc ? desc.min : -64, max: desc ? desc.max : 127, value: e.value, "aria-label": label(e.param) });
|
||
val.addEventListener("change", () => op(async () => { await rollMotionOp(e.kind ? 5 : 3, i, e.param, +val.value); rollInspector(); rollInvalidate(); }));
|
||
box.append(el("div", { class: "rrow" }, el("span", { class: e.kind ? "rk lock" : "rk auto", text: e.kind ? "LOCK" : "AUTO" }),
|
||
el("span", { text: label(e.param) }), val,
|
||
el("button", { type: "button", text: "×", "aria-label": `${t("remove")} ${label(e.param)}`, onclick: () => op(async () => { await rollMotionOp(4, i, e.param); rollInspector(); rollInvalidate(); }) })));
|
||
}
|
||
if (d.info.locks) {
|
||
const ids = [];
|
||
for (let id = 0; id < pc; id++) if (rLockable(id, pe0, pc) && d.pdesc[id] && d.pdesc[id].label !== "-" && d.pdesc[id].max > d.pdesc[id].min) ids.push(id);
|
||
const pick = el("select", { "aria-label": t("rollLockParam") }, ...ids.map((id) => el("option", { value: id, text: label(id) })));
|
||
const val = el("input", { type: "number", "aria-label": t("motionValue") });
|
||
const fill = () => { const ds = d.pdesc[+pick.value]; if (ds) { val.min = ds.min; val.max = ds.max; val.value = roll.p[+pick.value] ?? ds.def; } };
|
||
pick.addEventListener("change", fill); fill();
|
||
box.append(el("div", { class: "bar" }, pick, val, el("button", { type: "button", text: t("rollAddLock"),
|
||
onclick: () => op(async () => { const ds = d.pdesc[+pick.value]; await rollMotionOp(5, i, +pick.value, Math.max(ds.min, Math.min(ds.max, +val.value))); rollInspector(); rollInvalidate(); }) })));
|
||
} else box.append(el("p", { class: "dim", text: t("rollNoLocks") }));
|
||
return box;
|
||
}
|
||
|
||
/* ---------------------------------------------------------- EUCLID, the modulation sequence, the SLICER --- */
|
||
/* EUCLID (ui_euclid.c eu_hit / eu_kit): HITS STEPS ROTATE over the track's LEN; a DRUM track ALL (a DENSITY: the kit) or
|
||
one lane, a melodic one its note. The device's own EUCLID settings and MODES live in its RAM, out of the protocol's
|
||
reach: this writes the steps it makes, previewed first */
|
||
function rollEuclidSteps() {
|
||
const f = $("rolleu"), len = rollLen(), drum = rollDrum();
|
||
const h = +f.hits.value, n = +f.steps.value, r = +f.rot.value, lane = +f.lane.value, note = +f.note.value;
|
||
const out = [];
|
||
const kit = drum && lane < 0 ? euKit(Math.min(8, h), n, r) : null;
|
||
for (let i = 0; i < len; i++) {
|
||
const s = rollCopy(roll.steps[i]);
|
||
if (drum) {
|
||
let hit = lane < 0 ? 0 : s.time === 0 ? stepLanes(s) & ~(1 << lane) : 0;
|
||
if (lane < 0) kit.forEach((k, l) => { if (euHit(i % k.n, k.h, k.n, k.r)) hit |= 1 << l; });
|
||
else if (euHit(i % n, h, n, r)) hit |= 1 << lane;
|
||
const keepN = lane < 0 ? [] : s.time === 0 ? s.notes.slice(0, s.n).filter((x) => drumLane(x) !== lane) : [];
|
||
Object.assign(s, { time: hit || keepN.length ? 0 : 2, hit, acc: s.acc & hit, n: keepN.length, notes: keepN.concat([0, 0, 0, 0]).slice(0, 4), vel: s.vel || 100 });
|
||
} else if (euHit(i % n, h, n, r)) Object.assign(s, { time: 0, n: 1, notes: [note, 0, 0, 0], vel: s.vel || 100, hit: 0, acc: 0 });
|
||
else Object.assign(s, { time: 2, n: 0, notes: [0, 0, 0, 0], hit: 0, acc: 0 });
|
||
out.push(s);
|
||
}
|
||
return out;
|
||
}
|
||
function rollEuclidUi() {
|
||
const f = $("rolleu"), drum = rollDrum();
|
||
f.lane.closest("label").hidden = !drum; f.note.closest("label").hidden = drum;
|
||
if (!f.lane.options.length) f.lane.append(el("option", { value: -1, text: "ALL" }), ...LANES.map((n, l) => el("option", { value: l, text: n })));
|
||
const all = drum && +f.lane.value < 0;
|
||
f.querySelector("[data-hits]").textContent = all ? "DENSITY" : "HITS";
|
||
f.hits.max = all ? 8 : +f.steps.value;
|
||
if (+f.hits.value > +f.hits.max) f.hits.value = f.hits.max;
|
||
f.rot.max = Math.max(0, +f.steps.value - 1);
|
||
for (const k of ["hits", "steps", "rot"]) f.querySelector(`[data-o="${k}"]`).textContent = f[k].value;
|
||
f.querySelector("[data-o=note]").textContent = noteName(+f.note.value);
|
||
if (roll.euPrev) { roll.euPrev = rollEuclidSteps(); rollInvalidate(); }
|
||
}
|
||
/* the 16-step lanes: the modulation sequence (MOD > SEQ: LEN DIV SLEW and its levels, TRACK_PARAM) and the SLICER's
|
||
pitch steps (global 50..65, LEN 48; SET scope 1) */
|
||
function rollStrip(box, kind) {
|
||
const d = dev, ms = kind === "ms";
|
||
if (!d || !d.dump) return;
|
||
const val = (k) => ms ? roll.p[RP.MS0 + k] : d.dump.g[50 + k];
|
||
const len = ms ? roll.p[RP.MSLEN] : d.dump.g[48];
|
||
const desc = ms ? d.pdesc[RP.MS0] : d.gdesc[50];
|
||
const lo = desc ? desc.min : ms ? 0 : -24, hi = desc ? desc.max : ms ? 127 : 24;
|
||
let cv = box.querySelector("canvas");
|
||
if (!cv) {
|
||
cv = el("canvas", { class: "rstrip", "aria-label": ms ? "MOD SEQ" : "SLICER" });
|
||
box.prepend(cv);
|
||
let dn = null;
|
||
const at = (e) => { const r = cv.getBoundingClientRect(); return { k: Math.max(0, Math.min(15, Math.floor((e.clientX - r.left) / r.width * 16))), v: Math.round(lo + (1 - (e.clientY - r.top) / r.height) * (hi - lo)) }; };
|
||
const setv = (p) => { const v = Math.max(lo, Math.min(hi, p.v)); if (ms) roll.p[RP.MS0 + p.k] = v; else d.dump.g[50 + p.k] = v; dn.ch.set(p.k, v); rollStrip(box, kind); };
|
||
cv.addEventListener("pointerdown", (e) => { cv.setPointerCapture(e.pointerId); dn = { ch: new Map() }; setv(at(e)); });
|
||
cv.addEventListener("pointermove", (e) => { if (dn) setv(at(e)); });
|
||
const up = () => { if (!dn) return; const ch = dn.ch; dn = null;
|
||
op(async () => { for (const [k, v] of ch) { if (ms) await rollParam(RP.MS0 + k, v); else { const r = parse[CMD.SET](await rq(req.set(1, 50 + k, v), { key: "slc:" + k })); d.dump.g[50 + k] = r.value; } } rollStrip(box, kind); }); };
|
||
cv.addEventListener("pointerup", up); cv.addEventListener("pointercancel", up);
|
||
}
|
||
const dpr = devicePixelRatio || 1, w = cv.clientWidth || 300, h = cv.clientHeight || 120;
|
||
cv.width = Math.round(w * dpr); cv.height = Math.round(h * dpr);
|
||
const c = cv.getContext("2d"), C = RPAL.C;
|
||
c.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||
c.fillStyle = C.surf; c.fillRect(0, 0, w, h);
|
||
const zero = lo < 0 ? h * hi / (hi - lo) : h;
|
||
for (let k = 0; k < 16; k++) {
|
||
const x = k * w / 16, bw = w / 16 - 3, v = val(k) ?? 0, ratio = Math.round((v - lo) * 1000 / ((hi - lo) || 1));
|
||
c.fillStyle = k % 4 ? C.grid : C.line; c.fillRect(Math.round(x), 0, 1, h);
|
||
const y = h - (v - lo) / (hi - lo) * h;
|
||
c.fillStyle = k < len ? RPAL.card(ratio, lo < 0) : C.dim;
|
||
c.fillRect(x + 2, Math.min(y, zero), bw, Math.max(2, Math.abs(zero - y)));
|
||
}
|
||
if (lo < 0) { c.fillStyle = C.mid; c.fillRect(0, Math.round(zero), w, 1); }
|
||
}
|
||
|
||
/* ---------------------------------------------------------- open / close --- */
|
||
function rollShow(on) {
|
||
roll.open = on;
|
||
if (!on) { if (roll.raf) cancelAnimationFrame(roll.raf); roll.raf = 0; roll.euPrev = null; return; }
|
||
if (!roll.cv) rollBuild();
|
||
if (!dev || !dev.dump) return;
|
||
const want = dev.sel || 0;
|
||
if (!roll.steps.length || roll.track !== want || roll.stale) { roll.stale = false; roll.sel = null; rollSerial(() => rollRead(want)); }
|
||
else { rollHud(); rollInspector(); rollInvalidate(); }
|
||
}
|
||
function rollBuild() {
|
||
const cv = roll.cv = $("rollcv");
|
||
cv.addEventListener("pointerdown", rollPointerDown);
|
||
cv.addEventListener("pointermove", rollPointerMove);
|
||
cv.addEventListener("pointerup", rollPointerUp);
|
||
cv.addEventListener("pointercancel", rollPointerUp);
|
||
cv.addEventListener("wheel", rollWheel, { passive: false });
|
||
cv.addEventListener("keydown", rollKey);
|
||
new ResizeObserver(() => { if (roll.open) { rollClamp(); rollInvalidate(); } }).observe(cv);
|
||
if (document.fonts) document.fonts.ready.then(() => rollInvalidate());
|
||
$("rollvl").addEventListener("click", (e) => { const b = e.target.closest("button[data-v]"); if (!b) return; roll.vlane = b.dataset.v;
|
||
for (const x of $("rollvl").children) x.setAttribute("aria-pressed", x === b ? "true" : "false"); rollInvalidate(); });
|
||
$("rollfit").addEventListener("click", () => { rollFit(); rollInvalidate(); });
|
||
$("rollzin").addEventListener("click", () => { roll.view.cw *= 1.4; if (!rollDrum()) roll.view.rh *= 1.25; rollClamp(); rollInvalidate(); });
|
||
$("rollzout").addEventListener("click", () => { roll.view.cw /= 1.4; if (!rollDrum()) roll.view.rh /= 1.25; rollClamp(); rollInvalidate(); });
|
||
$("rollundo").addEventListener("click", rollUndo);
|
||
$("rollreload").addEventListener("click", () => rollSerial(() => rollRead(dev.sel || 0)));
|
||
const f = $("rolleu");
|
||
f.addEventListener("input", rollEuclidUi);
|
||
$("rolleuprev").addEventListener("click", () => { roll.euPrev = roll.euPrev ? null : rollEuclidSteps(); rollInvalidate(); });
|
||
$("rolleuwrite").addEventListener("click", () => {
|
||
const want = rollEuclidSteps(), ch = [];
|
||
want.forEach((s, i) => { if (JSON.stringify(s) !== JSON.stringify(roll.steps[i])) ch.push([i, s]); });
|
||
roll.euPrev = null; rollDo(ch);
|
||
});
|
||
for (const [id, kind] of [["rollms", "ms"], ["rollslc", "slc"]]) $(id).addEventListener("toggle", (e) => { if (e.target.open) rollStrip(e.target.querySelector(".rstripbox"), kind); });
|
||
$("rolleubox").addEventListener("toggle", (e) => { if (e.target.open) rollEuclidUi(); else { roll.euPrev = null; rollInvalidate(); } });
|
||
}
|
||
/* ============================================================ MATH (the formula editor) === */
|
||
/* MATH's formulas: write or edit one (BYTE: the VM above, the firmware's grammar), its picture, its sound (the emulator's
|
||
own samples when the device can play it: one of the firmware's formulas; the BYTE model otherwise), a seeded
|
||
generator, and a send to a track (the eight values by TRACK_PARAM after the engine). (V10.8.75) A formula of one's own
|
||
is MATH USER: compiled here to the device's bytecode (FVM, JIANT BYTE's compiler), heard through the emulator's own
|
||
machine (else the model), sent with FORMULA (100) and ALGO USER (-4) to a device whose INFO says 'E' (EDITOR_PROTOCOL.md
|
||
"1.5"); an older device keeps it in the browser, as before. Nothing is built or run until the tab opens; audio only on
|
||
Play */
|
||
const MATH_ENG = 3; /* the engine byte: LOFI, named MATH by INFO */
|
||
const mth = { built: false, wave: 5, f: 0, c: null, src: "", seed: 1, ctx: null, node: null, mod: null, modTried: false, raf: 0,
|
||
v: { note: 60, chip: 2, var: 0, motion: 0, grit: 0, bend: 0, loop: 0, sync: 0, algoB: 0, fbk: 0, morph: 0 } };
|
||
const M_KNOBS = {
|
||
5: [["note", "NOTE", 24, 96], ["var", "VARIANT", 0, 127], ["motion", "MOTION", 0, 255], ["grit", "GRIT", 0, 127], ["bend", "BEND", 0, 127], ["loop", "LOOP", 0, 127]],
|
||
6: [["note", "NOTE", 24, 96], ["algoB", "ALGO B", 0, 47], ["morph", "MORPH", 0, 127], ["var", "VARIANT", 0, 127], ["motion", "MOTION", 0, 255], ["fbk", "FEEDBK", 0, 127], ["loop", "LOOP", 0, 127]],
|
||
};
|
||
const M_OPS = ["t", "a", "(", ")", "+", "-", "*", "/", "%", "&", "|", "^", "~", "<<", ">>", "?:", "<", ">", "==", "!", "t >> 11", "t * (t >> 8 & 31)", "0xCA98 >> (t >> 9 & 14) & 15"];
|
||
function mathShow(on) {
|
||
if (!on) { mathStop(); return; }
|
||
if (!mth.built) mathBuild();
|
||
mathSendUi();
|
||
}
|
||
function mathBuild() {
|
||
mth.built = true;
|
||
$("mwave").addEventListener("click", (e) => { const b = e.target.closest("button[data-w]"); if (b) mathSetWave(+b.dataset.w); });
|
||
$("mstock").addEventListener("change", () => mathLoadStock(+$("mstock").value));
|
||
$("mf").addEventListener("input", () => mathCompile());
|
||
$("mops").replaceChildren(...M_OPS.map((o) => el("button", { type: "button", text: o, onclick: () => mathInsert(o === "?:" ? " ? : " : o.length > 2 ? o : ` ${o} `.replace(/^ ([ta()~!]) $/, "$1")) })));
|
||
$("mplay").addEventListener("click", () => mathPlay());
|
||
$("mstop").addEventListener("click", () => mathStop());
|
||
$("mfam").replaceChildren(...[["any", "mathAny"], ...MATH_FAMILIES.map((f) => [f.id, "mfam_" + f.id])].map(([v, k]) => el("option", { value: v, "data-t": k, text: t(k) })));
|
||
$("mchaos").addEventListener("input", () => { $("mchaosv").textContent = $("mchaos").value; });
|
||
$("mgen").addEventListener("click", () => mathGen());
|
||
$("mgenp").addEventListener("click", () => mathGenPatch());
|
||
$("mseed").addEventListener("change", () => { mth.seed = Math.max(1, +$("mseed").value | 0); });
|
||
$("msend").addEventListener("click", () => mathSend());
|
||
$("mread").addEventListener("click", () => mathRead());
|
||
$("msync").addEventListener("change", () => { mth.v.sync = $("msync").checked ? 1 : 0; });
|
||
$("mchip").addEventListener("click", (e) => { const b = e.target.closest("button[data-c]"); if (!b) return; mth.v.chip = +b.dataset.c; mathKnobs(); mathPicture(); });
|
||
mathSetWave(5, true);
|
||
mathLoadStock(4); /* B05: BYTEBEAT's own */
|
||
}
|
||
function mathSeed() { const v = Math.max(1, +$("mseed").value | 0); $("mseed").value = String(v + 1); return v; }
|
||
/* a formula of the family chosen (any: the seed's), as wild as CHAOS: written in the text box (in BYTE's view, where one's
|
||
own is written); an INT one plays on WAVE BYTE, a FIX one on WAVE FLOAT (mathCompile says which, the send sets it) */
|
||
function mathGen() {
|
||
mth.seed = mathSeed();
|
||
const chaos = +$("mchaos").value, g = mathGenerate(mth.seed, { family: $("mfam").value, chaos });
|
||
mathSetWave(5, true); $("mf").value = g.src; mathCompile();
|
||
sayK("mathGenerated", ` #${mth.seed} · ${t("mfam_" + g.family)} · ${t("mathChaos")} ${chaos}`);
|
||
}
|
||
function mathSetWave(w, keep) {
|
||
mth.wave = w;
|
||
for (const b of $("mwave").children) b.setAttribute("aria-pressed", +b.dataset.w === w ? "true" : "false");
|
||
const names = w === 6 ? MATH_FLOAT.map(([d], k) => `F${String(k + 1).padStart(2, "0")} ${d}`) : MATH_BYTE.map((s, k) => `B${String(k + 1).padStart(2, "0")} ${s.length > 46 ? s.slice(0, 44) + "…" : s}`);
|
||
$("mstock").replaceChildren(...(w === 5 ? [el("option", { value: -1, text: t("mathOwn") })] : []), ...names.map((n, k) => el("option", { value: k, text: n })));
|
||
$("mf").readOnly = w === 6;
|
||
$("mchip").hidden = w === 6; $("msyncl").hidden = w === 6;
|
||
$("mops").hidden = w === 6;
|
||
mathKnobs();
|
||
if (!keep) mathLoadStock(mth.f);
|
||
}
|
||
function mathLoadStock(k) {
|
||
if (k < 0) return;
|
||
mth.f = k;
|
||
$("mf").value = mth.wave === 6 ? MATH_FLOAT[k][1] : MATH_BYTE[k];
|
||
$("mstock").value = String(k);
|
||
mathCompile();
|
||
}
|
||
function mathInsert(s) {
|
||
const ta = $("mf"); if (ta.readOnly) return;
|
||
const a = ta.selectionStart ?? ta.value.length, b = ta.selectionEnd ?? a;
|
||
ta.value = ta.value.slice(0, a) + s + ta.value.slice(b);
|
||
ta.selectionStart = ta.selectionEnd = a + s.length; ta.focus();
|
||
mathCompile();
|
||
}
|
||
/* (V10.8.75) a text: one of the firmware's own (MathVM recognises it: sent as its ALGO), else a formula of one's own,
|
||
MATH USER: compiled to the device's bytecode (FVM, JIANT BYTE's compiler), run by the same machine for the picture and
|
||
the model; FIX (a number with a point, sin(w) ..) is a floatbeat, sent with WAVE FLOAT */
|
||
function mathCompileSrc(src) {
|
||
const s = MathVM.compile(src);
|
||
if (s.ok && s.stock >= 0) return s;
|
||
const f = FVM.compile(src);
|
||
if (!f.ok) return { ok: false, error: f.error, pos: f.pos };
|
||
const code = f.code;
|
||
const fn = f.fix ? (t, a) => ((FVM.sample(code, FVM.run(code, t, (t << 11) >>> 0, a)) >> 8) + 128) & 255 : (t, a) => FVM.run(code, t, 0, a) & 255;
|
||
return { ok: true, stock: -1, user: true, fvm: f, fn, size: code.length, usesA: /\ba\b/.test(src) };
|
||
}
|
||
/* the formula checked as typed: its error and where, or what it is (one of the firmware's: sendable) */
|
||
function mathCompile() {
|
||
const src = $("mf").value, msg = $("merr");
|
||
if (mth.wave === 6) { mth.c = null; msg.className = "dim"; msg.textContent = t("mathFloatRo"); mathPicture(); mathSendUi(); return; }
|
||
mth.c = mathCompileSrc(src);
|
||
if (!mth.c.ok) {
|
||
msg.className = "merr bad";
|
||
msg.textContent = `${t("mathErr")} ${mth.c.error} (${t("mathAt")} ${mth.c.pos + 1}): ${src.slice(Math.max(0, mth.c.pos - 12), mth.c.pos)}▸${src.slice(mth.c.pos, mth.c.pos + 12)}`;
|
||
} else {
|
||
if (mth.c.stock >= 0) mth.f = mth.c.stock;
|
||
$("mstock").value = String(mth.c.stock >= 0 ? mth.c.stock : -1);
|
||
msg.className = "merr ok";
|
||
msg.textContent = mth.c.stock >= 0 ? `B${String(mth.c.stock + 1).padStart(2, "0")} · ${t("mathIsStock")}` :
|
||
`${t("mathOwnOk")} (USER · ${mth.c.fvm.code.length}/${FVM.MAX} B · ${mth.c.fvm.fix ? "FIX → FLOAT" : "INT → BYTE"})`;
|
||
}
|
||
mathPicture(); mathSendUi();
|
||
}
|
||
/* the knobs: the device's E values of the wave */
|
||
function mathKnobs() {
|
||
const box = $("mknobs"), v = mth.v;
|
||
box.replaceChildren(...M_KNOBS[mth.wave].map(([k, lb, lo, hi]) => {
|
||
const r = el("input", { type: "range", min: lo, max: hi, value: v[k], "aria-label": lb });
|
||
const o = el("b", { text: mathKnobText(k, v[k]) });
|
||
r.addEventListener("input", () => { v[k] = +r.value; o.textContent = mathKnobText(k, v[k]); mathPicture(); });
|
||
return el("label", { class: "mk" }, el("span", { text: lb }), r, o);
|
||
}));
|
||
for (const b of $("mchip").children) b.setAttribute("aria-pressed", +b.dataset.c === v.chip ? "true" : "false");
|
||
$("msync").checked = !!v.sync;
|
||
}
|
||
function mathKnobText(k, x) {
|
||
if (k === "note") return noteName(x);
|
||
if (k === "motion") return x >= 128 ? `SYNC ${x - 128}` : String(x);
|
||
if (k === "var") return `${x} · a=${1 + (x >> 3)}`;
|
||
if (k === "algoB") return `F${String(x + 1).padStart(2, "0")}`;
|
||
return String(x);
|
||
}
|
||
/* the formula's picture: 128 rows of 256 samples of what it plays (VAR's mutation, BEND, the start), each its heat */
|
||
function mathPicture() {
|
||
if (mth.raf) return;
|
||
mth.raf = requestAnimationFrame(() => {
|
||
mth.raf = 0;
|
||
const cv = $("mscope"), c = cv.getContext("2d"), W = 256, H = 128;
|
||
const img = c.createImageData(W, H), v = mth.v, d = img.data;
|
||
const fn = mth.wave === 5 && mth.c && mth.c.ok ? mth.c.fn : null;
|
||
const heat = [];
|
||
for (let k = 0; k < 256; k++) { const m = /rgb\((\d+),(\d+),(\d+)\)/.exec(RPAL.heat(k)); heat.push([+m[1], +m[2], +m[3]]); }
|
||
const vr = v.var, a = 1 + (vr >> 3), bs = v.bend ? 13 - Math.floor(v.bend / 11) : 0, t0 = (mth.f < 32 && mth.c && mth.c.stock >= 0 ? MATH_T0[mth.f] : 0) << 9;
|
||
const lm = v.loop ? ((1 << (17 - Math.floor(v.loop * 12 / 127))) - 1) >>> 0 : 0xFFFFFFFF;
|
||
for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
|
||
let s = 0;
|
||
if (fn) { const tl = mathMut(((((y * 512 + x * 2) & lm) >>> 0) + t0) >>> 0, vr); s = fn(bs ? (tl ^ (tl >>> bs)) >>> 0 : tl, a); }
|
||
const [r, g, b] = fn ? heat[s] : [12, 11, 16], i = (y * W + x) * 4;
|
||
d[i] = r; d[i + 1] = g; d[i + 2] = b; d[i + 3] = 255;
|
||
}
|
||
c.putImageData(img, 0, 0);
|
||
});
|
||
}
|
||
/* the emulator's wasm, for the device's own sound (the site's /emu/felucca.wasm two levels up from /webapp/editor/; ?wasm= another) */
|
||
async function mathModule() {
|
||
if (mth.mod || mth.modTried) return mth.mod;
|
||
mth.modTried = true;
|
||
for (const u of [QS.get("wasm"), "../../emu/felucca.wasm", "../emu/felucca.wasm", "emu/felucca.wasm"].filter(Boolean)) {
|
||
try {
|
||
const r = await fetch(u); if (!r.ok) continue;
|
||
const m = await WebAssembly.compile(await r.arrayBuffer());
|
||
if (WebAssembly.Module.exports(m).some((x) => x.name === "web_ed")) { mth.mod = m; return m; }
|
||
} catch (e) { /* the next */ }
|
||
}
|
||
return null;
|
||
}
|
||
async function mathRender() {
|
||
const v = mth.v, secs = 3, o = { ...v, wave: mth.wave, f: mth.f, secs, gate: 2.4 };
|
||
const user = mth.wave === 5 && mth.c && mth.c.ok && mth.c.user;
|
||
const exact = mth.wave === 6 || (mth.c && mth.c.ok && mth.c.stock >= 0) || user;
|
||
if (exact) {
|
||
const m = await mathModule();
|
||
if (m) {
|
||
const inst = await WebAssembly.instantiate(m, {});
|
||
if (!user) return { ...mathEmuRender(inst.exports, o), src: "emu" };
|
||
const r = mathEmuRender(inst.exports, { ...o, user: true, code: mth.c.fvm.code, wave: mth.c.fvm.fix ? 6 : 5 });
|
||
if (r.formula) return { ...r, src: "emu" }; /* (V10.8.75: a firmware with FORMULA: the device's own VM) */
|
||
}
|
||
if (mth.wave === 6) return null;
|
||
}
|
||
if (!mth.c || !mth.c.ok) return null;
|
||
const l = mathRenderByte({ ...o, fn: mth.c.fn, f: mth.c.stock, rate: 44100 });
|
||
return { l, r: l, src: "model" };
|
||
}
|
||
async function mathPlay() {
|
||
mathStop();
|
||
$("msrc").textContent = t("mathRendering");
|
||
const r = await mathRender();
|
||
if (!r) { $("msrc").textContent = t(mth.wave === 6 ? "mathNoEmu" : "mathFixFirst"); return; }
|
||
const G = 6; /* (the device's level at MASTER 700, heard: both paths alike) */
|
||
mth.ctx = mth.ctx || new (window.AudioContext || window.webkitAudioContext)();
|
||
const buf = mth.ctx.createBuffer(2, r.l.length, 44100);
|
||
buf.getChannelData(0).set(r.l.map((x) => Math.max(-1, Math.min(1, x * G))));
|
||
buf.getChannelData(1).set(r.r.map((x) => Math.max(-1, Math.min(1, x * G))));
|
||
const n = mth.ctx.createBufferSource(); n.buffer = buf; n.loop = $("mloop").checked; n.connect(mth.ctx.destination);
|
||
if (mth.ctx.state === "suspended") await mth.ctx.resume();
|
||
n.start(); mth.node = n; mth.last = r;
|
||
n.onended = () => { if (mth.node === n) mth.node = null; };
|
||
$("msrc").textContent = t(r.src === "emu" ? "mathSrcEmu" : "mathSrcModel");
|
||
}
|
||
function mathStop() { if (mth.node) { try { mth.node.stop(); } catch (e) { /* stopped */ } mth.node = null; } }
|
||
/* a sound the device plays: one of its formulas (a musical choice of them), VAR's mutation, MOTION, BEND, LOOP, the bits;
|
||
seeded, so a seed is the same sound again */
|
||
function mathGenPatch() {
|
||
mth.seed = mathSeed();
|
||
const r = mathRng(mth.seed * 2654435761), pick = (a) => a[r() % a.length], v = mth.v;
|
||
const byte = r() % 4 !== 0;
|
||
mathSetWave(byte ? 5 : 6, true);
|
||
const f = byte ? pick([0, 1, 3, 4, 5, 6, 7, 10, 11, 13, 14, 16, 17, 18, 21, 22, 25, 26, 29, 32, 33, 36, 37, 39, 40, 43, 45, 46])
|
||
: pick([1, 2, 3, 5, 7, 8, 10, 15, 19, 22, 23, 27, 28, 33, 34, 35, 39, 40, 41, 44, 47]);
|
||
Object.assign(v, { var: pick([0, 0, 8, 16 + (r() % 8), 32 + (r() % 8), 48 + (r() % 6), 80 + (r() % 8), 96 + (r() % 6)]),
|
||
motion: pick([0, 0, 24, 48, 64, 64, 80, 128 + 64, 128 + 48]), grit: pick([0, 0, 0, 16, 40]), bend: pick([0, 0, 0, 30, 60, 90]),
|
||
loop: pick([0, 0, 0, 40, 70, 90]), chip: pick([2, 2, 2, 0, 1]), sync: 0, algoB: r() % 48, morph: pick([0, 0, 40, 80]), fbk: pick([0, 0, 20, 50]) });
|
||
mathKnobs();
|
||
mathLoadStock(f);
|
||
sayK("mathGenerated", ` #${mth.seed}`);
|
||
}
|
||
/* (V10.8.75) the texts of the formulas sent from here (the device keeps the bytes only): by their bytes, in this browser */
|
||
function mathTextKeep(code, src) {
|
||
try { const m = JSON.parse(localStorage.getItem("jiantMathUser") || "{}"); m[code.join(",")] = src; const k = Object.keys(m); if (k.length > 200) delete m[k[0]]; localStorage.setItem("jiantMathUser", JSON.stringify(m)); } catch (e) { /* none */ }
|
||
}
|
||
function mathTextOf(code) {
|
||
try { const m = JSON.parse(localStorage.getItem("jiantMathUser") || "{}"); return m[code.join(",")] ?? null; } catch (e) { return null; }
|
||
}
|
||
function mathSendUi() {
|
||
const b = $("msend"), why = $("msendmsg"); if (!b) return;
|
||
const user = mth.wave === 5 && mth.c && mth.c.ok && mth.c.user, has = !!(dev && dev.info && dev.info.formula);
|
||
const ok = mth.wave === 6 || (mth.c && mth.c.ok && mth.c.stock >= 0) || (user && has);
|
||
const ntrk = dev && dev.info && dev.info.ntrk ? dev.info.ntrk : 0, sel = $("mtrk");
|
||
if (sel.options.length !== ntrk) sel.replaceChildren(...Array.from({ length: ntrk }, (_, i) => el("option", { value: i, text: `T${i + 1}` })));
|
||
if (dev && dev.sel != null && !sel.dataset.touched) sel.value = String(dev.sel);
|
||
b.disabled = !dev || !dev.dump || !ok || !ntrk; $("mread").disabled = !dev || !dev.dump || !ntrk;
|
||
why.textContent = !dev ? t("mathConnect") : ok ? (user ? t("mathUserSend") : "") : t("mathOwnNoSend");
|
||
}
|
||
/* the sound to a track: selected (TRACK), made MATH (SET of G_ENGSEL: the device's own engine change, its first preset),
|
||
then its eight values (TRACK_PARAM), read back */
|
||
async function mathSend() {
|
||
const d = dev, tr = +$("mtrk").value;
|
||
await op(async () => {
|
||
if (tr !== (d.sel || 0)) d.sel = parse[CMD.TRACK](await rq(req.track(tr))).sel;
|
||
const td = parse[CMD.TRACK_DUMP](await rq(req.trackDump(tr)), d.info);
|
||
if (td.engine !== MATH_ENG) { selfLoad(true); await rq(req.set(1, gEng(), MATH_ENG)); }
|
||
const user = mth.wave === 5 && mth.c && mth.c.ok && mth.c.user;
|
||
if (user) { /* (V10.8.75) MATH USER: the formula first (FORMULA 100), read back */
|
||
const code = mth.c.fvm.code, r = parse[CMD.FORMULA](await rq(req.formula(tr, 1, code)));
|
||
if (r.rc || r.code.join() !== code.join()) { sayK("mathUserRefused", ` T${tr + 1}`); return; }
|
||
mathTextKeep(code, $("mf").value);
|
||
}
|
||
const vals = mathValues({ ...mth.v, wave: user ? (mth.c.fvm.fix ? 6 : 5) : mth.wave, f: mth.f, user }), got = [];
|
||
for (let k = 0; k < 8; k++) got.push(parse[CMD.TRACK_PARAM](await rq(req.trackParam(tr, d.info.pe0 + k, vals[k]))).value);
|
||
await afterSoundChange("ready");
|
||
const same = got.every((x, k) => x === vals[k]);
|
||
sayK(same ? "mathSent" : "mathSentClamped", ` T${tr + 1}: ${user ? "USER" : (mth.wave === 6 ? "F" : "B") + String(mth.f + 1).padStart(2, "0")}`);
|
||
});
|
||
}
|
||
/* a MATH track's sound into the editor (its formula and values) */
|
||
async function mathRead() {
|
||
const d = dev, tr = +$("mtrk").value;
|
||
await op(async () => {
|
||
const td = parse[CMD.TRACK_DUMP](await rq(req.trackDump(tr)), d.info);
|
||
if (td.engine !== MATH_ENG) { sayK("mathNotMath", ` T${tr + 1}`); return; }
|
||
const e = td.p.slice(d.info.pe0, d.info.pe0 + 8), w = e[1] === 6 ? 6 : 5, v = mth.v;
|
||
if (w === 6) Object.assign(v, { algoB: e[0] >> 2, var: e[3], motion: e[4], fbk: e[5], morph: e[6], loop: e[7] });
|
||
else Object.assign(v, { chip: e[0], sync: e[1] === 7 ? 1 : 0, var: e[3], motion: e[4], grit: e[5], bend: e[6], loop: e[7] });
|
||
if (e[2] < 0 && d.info.formula) { /* (V10.8.75) ALGO USER: the track's formula, its text if known here */
|
||
const r = parse[CMD.FORMULA](await rq(req.formula(tr, 0)));
|
||
mathSetWave(5, true); mathKnobs();
|
||
const txt = mathTextOf(r.code);
|
||
if (txt != null) { $("mf").value = txt; mathCompile(); }
|
||
sayK(txt != null ? "mathReadOk" : "mathReadUser", ` T${tr + 1} (USER, ${r.n} B)`);
|
||
return;
|
||
}
|
||
mathSetWave(w, true); mathKnobs(); mathLoadStock(Math.min(47, Math.max(0, e[2]) >> 2));
|
||
sayK("mathReadOk", ` T${tr + 1}`);
|
||
});
|
||
}
|
||
|
||
/* (?test=1: editor_browser_test.mjs reads the roll's state and finds a cell's place on the screen) */
|
||
if (QS.get("test") === "1") window.jiantRollTest = {
|
||
roll, read: () => ({ track: roll.track, engine: roll.engine, steps: roll.steps, motion: roll.motion, p: roll.p, sel: roll.sel, view: { ...roll.view } }),
|
||
cell: (step, row) => {
|
||
const g = rollGeom(), v = roll.view, r = roll.cv.getBoundingClientRect();
|
||
const y = rollDrum() ? g.gy + (row + .5) * v.rh : g.gy + (v.top - row + .5) * v.rh;
|
||
return { x: r.left + g.gx + (step - v.sx + .5) * v.cw, y: r.top + y };
|
||
},
|
||
idle: () => rollChain,
|
||
show: (note) => { roll.view.top = note + 4; rollClamp(); rollInvalidate(); },
|
||
math: () => ({ built: mth.built, playing: !!mth.node, wave: mth.wave, f: mth.f, v: { ...mth.v }, ok: !!(mth.c && mth.c.ok), stock: mth.c ? mth.c.stock : null, src: $("mf").value, last: mth.last ? mth.last.src : null,
|
||
user: !!(mth.c && mth.c.user), code: mth.c && mth.c.fvm ? mth.c.fvm.code.slice() : null, fix: !!(mth.c && mth.c.fvm && mth.c.fvm.fix) }),
|
||
mathRender: async () => { const r = await mathRender(); return r ? { src: r.src, n: r.l.length, peak: r.l.reduce((m, x) => Math.max(m, Math.abs(x)), 0) } : null; },
|
||
};
|
||
async function rollRefreshStep(i) {
|
||
const d = dev, tr = roll.track;
|
||
try {
|
||
const r = rollNorm(parse[CMD.TRACK_STEP](await rq(req.trackStep(tr, i, null, !!d.info.laneModes), { key: `rstep:${tr}:${i}` })));
|
||
if (d === dev && roll.track === tr) { roll.steps[i] = r; rollInvalidate(); }
|
||
} catch (err) { report(err); }
|
||
}
|
||
|
||
$("connect").addEventListener("click", () => {
|
||
if (dev) { wantConnected = false; disconnect(); } else connect();
|
||
});
|
||
applyLang();
|
||
showTab(tab);
|
||
libInit();
|
||
if (!MOCK && !navigator.requestMIDIAccess) sayK("nomidi");
|
||
})();
|
||
</script>
|
||
</body>
|
||
</html>
|
||
|
||
|
||
|