Compare commits

..
47 changed files with 3546 additions and 93 deletions

No files matched your search

+96 -9
View File
@@ -1502,6 +1502,67 @@ Two independent apps that talk over HTTP:
Unmeasured: what Traktor leaves after "None" (Konduktor removes the attribute).
Carried but deliberately unused until a second adapter
exists: `slot_labels: 'letter'`, `loops: 'separate_bank'`.
- **`lib/midi/` — MIDI controllers** (decided 2026-11-03,
[the discussion](.claude/discussions/discuss-midi-controllers-2026-11-03.md)):
MIDI only (no HID), ANY controller, mapped by LEARNING — no shipped
mappings — and input only (no LEDs). **Transport**: WKWebView has no Web
MIDI, so the shell reads ports with `midir` (`src-tauri/src/midi.rs`:
`midi_ports` / `midi_open` / `midi_close`; system messages ignored at the
driver; a sender thread per port drains its queue into ONE `Channel`
batch, so idle = no delay and a flood coalesces). Measured (2026-11-03,
`src-tauri/examples/midi_flood.rs`, a CoreMIDI virtual source): 0 drops
or reorders at 250-4000 msg/s, ~1 ms spread. A JS `Channel` cannot be
reused once its Rust side is dropped — every open makes a fresh one.
`transport.ts` hides that and Web MIDI (`./dev.sh` in Chrome) behind one
interface; `useMidi` (mounted in App) polls ports every 1.5 s (midir has
no hot-plug events) and keeps mappings in userprefs `midiMappings`.
**Model**: `messages.ts` (bytes → note / CC / pitch bend; `SourceKey`
`cc:1:33`), `encoding.ts` (button, abs 7/14-bit — CC n + n+32 or pitch
bend, a knob's centre exactly 0 — three relative schemes, and ABSOLUTE-
position jogs that wrap; `detectEncoding` guesses from what a control sent
while learning: relative REPEATS and jitters inside its zones, absolute
progresses), `actions.ts` (the vocabulary: deck buttons = the deck keys'
actions, plus pitch, jog, jog touch, fast scrub, load, SYNC, MASTER, keylock,
loops; mixer; browse / tree; performance mode; `shiftDefault` = the
keyboard's Shift meaning), `mapping.ts` (per controller, keyed by SOURCE;
each control a normal + a FREE Shift binding; learning REPLACES an
action's control in that layer and fills an empty Shift layer with the
default). **Encoders on button actions** (beat jump, loop size — common
on controllers): learning a button action by TURNING an encoder binds
that DIRECTION, a virtual source `cc:1:20+` / `cc:1:20-` (↻ / ↺); each
tick fires the action once (up to 8 per message), both directions share
the encoder's encoding and decoder, and a plain binding on the same
encoder wins only where it has an action for the layer. A CC learned for
a button waits 400 ms: one message, or any 0, = a button; several
non-zero = a turn (so a two's-complement encoder's 127s are not a press).
**`router.ts`**: Shift is a learned control — up to TWO per controller
(`Mapping.shifts`, many have one per deck; either held = the Shift layer;
the old single `shift` field still loads) (an unbound Shift
binding falls back to normal); deck B and the mixer act only in
performance mode; positions JUMP (no soft takeover — "the controller
always wins"); a held control releases where it was pressed; Learn sees
every message first (buttons on the first press — a CC button waits
250 ms for a note, since a touch jog sends both; positions after 12
messages or 800 ms; notes ignored for a jog; Shift held = the Shift
layer). Targets are registered by whoever is mounted (`targets.ts`,
cleanup clears only its OWN values: a new view registers before the old
one unmounts): PrepStrip's `DeckMidi` per deck (a hardware pitch move and
a jog NUDGE release SYNC), App's `load` (the table's highlighted row,
loaded PAUSED), TrackTable's `browse` (= ↑/↓), Sidebar's `tree` (Shift +
browse: All Tracks + the visible tree; a playlist opens as reached, a
folder opens on press). **Jog** (`useDeck`): touch = scratch through the
waveform-drag path, target sent straight to the worklet; no touch =
nudge (a per-frame bend, also in prep mode) while playing; while paused
a turn SCRATCHES too (decided 2026-11-05: grabbed on the first tick,
released `JOG_SCRATCH_IDLE_MS` after the last, so a jog without a touch
sensor still cues by ear); fast scrub stays a seek; scale `JOG_SEC_PER_TICK` × the mapping's sensitivity. **UI**:
Settings ▸ MIDI Controllers… (`MidiSettings`: per controller, Shift, jog
sensitivity / fast scrub, every action × Normal / Shift with Learn,
encoding + Reversed per binding, Import / Export as
`.konduktor-midi.json` through `/api/midi/import|export` — never
overwrites) and **Learn on screen** (`MidiLearnOverlay`: controls carry
`data-midi-action`; a click ARMS instead of acting). A new on-screen
control with a MIDI action should carry the attribute.
- `lib/trackColumns.tsx` — single source of truth for the library table's
columns (defs, default widths/visibility/order, the Columns-menu list, the
inline `InlineEdit` cell, and the `TableMeta.onEditField` augmentation).
@@ -1557,7 +1618,10 @@ docker build -f server/Dockerfile -t konduktor-server . # from the repo root
cd frontend
npm run dev # dev server (proxies /api -> :8000)
npm run build # tsc -b && vite build — run this to typecheck
npm run test # vitest — unit tests for src/lib/beatgrid.ts
npm run test # vitest — unit tests (src/lib/**/*.test.ts)
# MIDI without hardware (macOS): a virtual source flooding CC 33 on ch 1
cd frontend/src-tauri && cargo run --example midi_flood -- <Hz> <count> <delay s>
```
**Tests:** `cd backend && ./run_tests.sh` (runs against a temp copy of the real
@@ -1959,6 +2023,11 @@ serialization path.** It enforces:
last-collection and path-mapping helpers lose nothing either; an unreadable
file is moved aside, not overwritten. Against the old unlocked code it fails
on the first trial.
- `test_midi_mappings.py` — a MIDI mapping to and from a file: never
overwrites (`-2`), a name cannot leave the folder, import refuses non-JSON,
non-objects, other versions and oversized files, and `/api/fs/list`'s
`suffix` lists only mapping files. (The mapping logic itself is the
frontend's: `src/lib/midi/*.test.ts`.)
- `test_exports.py` — export sets against a temp copy of the real collection.
Pins the things that would fail SILENTLY: a live reference picks up a playlist
edited AFTER curation; contents dedupe across playlists and loose tracks; a
@@ -2705,8 +2774,12 @@ that number and nothing else — everything derives from it:
master, a phase meter you can drag to bend. See `lib/audio/`,
`components/deck/`, `components/mixer/` and "Prep strip" / "Prep engine";
[the discussion](.claude/discussions/discuss-performance-mode-2026-11-02.md).
Not yet: MIDI controllers (decided: later; WKWebView has no Web MIDI, so
through Tauri), headphone cue (decided: not needed), recording the mix.
Not yet: headphone cue (decided: not needed), recording the mix.
- 🟡 **MIDI controllers** (2026-11-03) — any MIDI controller, mapped by
learning, for prep (deck A) and performance mode; see `lib/midi/` under
Architecture. Built and unit-tested; not yet checked on real hardware
(scratch feel, jog scale) nor on Windows. Not planned for v1: HID
controllers, LED output, soft takeover, deck layers.
- ⬜ Serato adapter
- ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging
@@ -2782,9 +2855,21 @@ The prep strip plays every track through the **Web Audio API** (a plain
performance mode; [the discussion](.claude/discussions/discuss-performance-mode-2026-11-02.md)).
`deckCore.ts` renders a deck block by block: transport, seamless loops, the
stems in lockstep (ONE position for all), mute/solo as ramped gains,
varispeed (cubic interpolation) and scratch (the old ScriptProcessor's
drag/inertia feel; a release coasts and the deck PLAYS ON BY ITSELF, so there
is no gap). `deckProcessor.worklet.ts` wraps it (`?worker&url`, bundled
varispeed (cubic interpolation) and scratch (a release coasts and the deck
PLAYS ON BY ITSELF, so there is no gap). **Scratch is rebuilt for sound**
(2026-11-05): the hand's position arrives in STEPS (mouse ~60 Hz, a jog up
to one per block, bunched by the main thread), and chasing each step with a
one-pole made the speed swing ±67-83% at that rate — buzzing, with a click
each time it caught up (a hard mute at rest). Now the steps are joined into
a line played `handDelay` behind the newest (adapted to their spacing,
6-30 ms), followed by a critically damped spring (`SCRATCH_HZ` 45), so the
speed is continuous; volume follows speed; above 1x the source is averaged
over the span each frame covers (anti-aliasing); targets are RELATIVE to
the position given at the grab (`scratchBegin` / `scratchRegrab(sec)`), so a
stale main-thread position cannot jump it, and grabbing a playing deck
brakes from its speed. Measured (`deckCore.test.ts` "scratch sound"): speed
ripple 0 for even steps, 3% for jittery bursts; lag 13.5 ms (a jog every
block) to ~30 ms (mouse). `deckProcessor.worklet.ts` wraps it (`?worker&url`, bundled
self-contained); `deckEngine.ts` is the main thread's handle, with the old
PlaybackEngine's surface: commands are async, so it answers from a model
(last report + context clock, `position.ts`) that each command updates at
@@ -2811,7 +2896,9 @@ The prep strip plays every track through the **Web Audio API** (a plain
(LR4 crossovers at 250 Hz / 2.5 kHz, the low band through a 2.5 kHz
all-pass, so the bands sum flat — measured 0.0000 dB; Web Audio's
lowpass/highpass Q is in DB, Butterworth = -3.01, its allpass Q linear) →
FILTER FX (`FilterFx`, decided 2026-11-03 after Traktor's mixer: the
fader → FILTER FX, POST-fader (decided 2026-11-05: pulling the fader down
stops feeding the reverb / delay and their tails ring out rather than
being cut with it) (`FilterFx`, decided 2026-11-03 after Traktor's mixer: the
FILTER knob always filters — 4-pole, low-pass left / high-pass right, over
a RANGE: FULL (to 20 Hz / 20 kHz: a 100 Hz bass -56 dB at full left,
measured; one 12 dB stage left it at -28), MUSICAL (150 Hz / 8 kHz) or
@@ -2835,14 +2922,14 @@ The prep strip plays every track through the **Web Audio API** (a plain
knob, -54 at 60%). Resonance fades over the last stretch of the sweep (no
boom at 20 Hz). Each effect's one parameter is an APP SETTING, not a knob —
`mixerState.fx`; all built once and switched by gains) →
fader → crossfader (`xfadeGains(x, sharpness)`: each channel fades on a
crossfader (`xfadeGains(x, sharpness)`: each channel fades on a
quarter-cosine over the last `xfadeWidth` of the travel — the whole of it
at 0, constant power, -3 dB in the middle; 4% at 1, a cut; no dip in the
middle above ~0.52) → bus → limiter
(DynamicsCompressor at -1.5 dBFS 20:1 — Web Audio adds an automatic
MAKE-UP gain, +0.57 dB at -1/20:1, which let two loud decks peak at +0.3
dBFS until a gain after it took it back off) → speakers. Channel meters are
after the fader, before the crossfader. OUTSIDE performance mode the mixer
after the fader and FX, before the crossfader. OUTSIDE performance mode the mixer
is BYPASSED (A straight through, B silent, no limiter): prep listening is
unchanged. Controls live in `mixerState.ts` (an external store, not
persisted; a MIDI mapping would write the same setters); the curves in
+54 -4
View File
@@ -6,6 +6,7 @@ in the environment auto-loads that file on startup (used by dev and tests).
"""
from __future__ import annotations
import json
import logging
import os
from dataclasses import dataclass
@@ -16,7 +17,7 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
from . import __version__, exporter, exports, local_push, loudness_store, prefs
from . import __version__, exporter, exports, local_push, loudness_store, paths, prefs
from .app_state import STATE
from .core import auto_hotcues as ah
from .core import grid_detect, key_detect, loudness, structure
@@ -38,6 +39,7 @@ from .core.capabilities import Capabilities
from .jobs import JOBS, Job, JobBusy
from .core.pathmap import PathMapping
from .schemas import (
MidiExportRequest,
Relocation,
RelocationApplied,
RelocationApply,
@@ -582,13 +584,14 @@ def fs_places(platform: str | None = None) -> list[FsPlace]:
@app.get("/api/fs/list", response_model=FsListing)
def fs_list(path: str | None = None, platform: str | None = None) -> FsListing:
def fs_list(path: str | None = None, platform: str | None = None, suffix: str | None = None) -> FsListing:
"""List directories and openable library files for the in-app file browser.
`platform` narrows the files to that platform's own: a Traktor browse that
also listed `master.db` would be offering a file the chosen adapter cannot
open. A platform whose library is a directory contributes no suffixes at
all, so its browse shows folders only.
all, so its browse shows folders only. `suffix` instead lists files whose
NAME ends with it (a MIDI mapping's `.konduktor-midi.json`).
"""
base = Path(path).expanduser() if path else Path.home()
if not base.exists() or not base.is_dir():
@@ -604,7 +607,7 @@ def fs_list(path: str | None = None, platform: str | None = None) -> FsListing:
try:
if entry.is_dir():
dirs.append(FsEntry(name=entry.name, path=str(entry)))
elif entry.suffix.lower() in suffixes:
elif entry.name.lower().endswith(suffix.lower()) if suffix else entry.suffix.lower() in suffixes:
files.append(FsEntry(name=entry.name, path=str(entry)))
except OSError:
continue
@@ -616,6 +619,53 @@ def fs_list(path: str | None = None, platform: str | None = None) -> FsListing:
)
# ---- MIDI controller mappings ---------------------------------------------------
#
# A mapping lives in userprefs (`midiMappings`, written by the UI like any pref);
# these two only move one to and from a FILE, so mappings can be shared. The
# content is the UI's to validate (lib/midi/mapping.sanitizeMapping): here it
# only has to be a small JSON object of the right version.
MIDI_MAPPING_SUFFIX = ".konduktor-midi.json"
_MIDI_MAPPING_MAX_BYTES = 1_000_000
@app.post("/api/midi/export")
def midi_export(req: MidiExportRequest) -> dict:
"""Write a mapping into `dir` as `<name>.konduktor-midi.json`. Never
overwrites: an existing file gets a `-2`, `-3`… beside it."""
folder = Path(req.dir).expanduser()
if not folder.is_dir():
raise HTTPException(400, f"Not a folder: {req.dir}")
if req.mapping.get("version") != 1:
raise HTTPException(400, "Not a MIDI mapping")
stem = "".join("_" if c in '/\\:*?"<>|' else c for c in req.name).strip(" .") or "MIDI mapping"
target = folder / f"{stem}{MIDI_MAPPING_SUFFIX}"
n = 2
while target.exists():
target = folder / f"{stem}-{n}{MIDI_MAPPING_SUFFIX}"
n += 1
paths.write_json(target, req.mapping)
return {"path": str(target)}
@app.get("/api/midi/import")
def midi_import(path: str) -> dict:
"""Read a mapping file (size-capped; must be a version-1 JSON object)."""
file = Path(path).expanduser()
if not file.is_file():
raise HTTPException(404, f"No such file: {path}")
if file.stat().st_size > _MIDI_MAPPING_MAX_BYTES:
raise HTTPException(400, "That file is too large to be a MIDI mapping")
try:
data = json.loads(file.read_text(encoding="utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError):
raise HTTPException(400, "That file is not a MIDI mapping") from None
if not isinstance(data, dict) or data.get("version") != 1:
raise HTTPException(400, "That file is not a MIDI mapping")
return {"mapping": data}
# ---- export sets -------------------------------------------------------------
#
# Curation, not library data: a set is Konduktor's own record of what to export,
+8
View File
@@ -818,3 +818,11 @@ class NormalizeRequest(BaseModel):
measure: Literal["lufs", "rms"] = "lufs"
target: float = -9.0
ceiling: float = -1.0
class MidiExportRequest(BaseModel):
"""A controller mapping written to a file (`/api/midi/export`). Its shape
is the UI's (`lib/midi/mapping.ts`); only the version is checked here."""
dir: str
name: str
mapping: dict
+1 -1
View File
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
source .venv/bin/activate
fail=0
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_loudness.py test_loudness_store.py test_level_plan.py test_level_edit.py test_aac_gain.py test_normalize.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_export_level.py test_local_push.py test_traktor_file_block.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py test_remote_normalize.py; do
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_key_detect.py test_loudness.py test_loudness_store.py test_level_plan.py test_level_edit.py test_aac_gain.py test_normalize.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_midi_mappings.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_export_level.py test_local_push.py test_traktor_file_block.py test_device_export.py test_phase3.py test_history.py test_discard.py test_remote_protocol.py test_remote_server.py test_remote_adapter.py test_remote_stems.py test_remote_normalize.py; do
echo "──────────────────────────────────────────"
echo "▶ $t"
echo "──────────────────────────────────────────"
+80
View File
@@ -0,0 +1,80 @@
"""MIDI controller mappings moved to and from FILES (`/api/midi/export`,
`/api/midi/import`) — the only backend part of controller support; the
mapping itself lives in userprefs and is validated by the UI.
Pins what would hurt silently: an export never overwrites a file (a shared
mapping saved twice must not replace the first), the name cannot steer the
file outside the chosen folder, and import refuses anything that is not a
small version-1 JSON object rather than handing the UI garbage. The file
browser's `suffix` filter lists the mapping files.
"""
import json
import sys
import tempfile
from pathlib import Path
from fastapi import HTTPException
from konduktor import prefs
_TMP = tempfile.TemporaryDirectory()
prefs._PREFS_PATH = Path(_TMP.name) / "userprefs.json"
prefs._LEGACY_PREFS_PATH = Path(_TMP.name) / "absent.json"
from konduktor.main import fs_list, midi_export, midi_import # noqa: E402
from konduktor.schemas import MidiExportRequest # noqa: E402
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
def refused(fn, status):
try:
fn()
except HTTPException as e:
return e.status_code == status
return False
folder = Path(_TMP.name) / "maps"
folder.mkdir()
mapping = {"version": 1, "shift": "note:1:63", "bindings": {"note:1:11": {"encoding": "button", "normal": "deck.A.play"}}}
print("export")
first = Path(midi_export(MidiExportRequest(dir=str(folder), name="DDJ-400", mapping=mapping))["path"])
check("written as <name>.konduktor-midi.json", first.name == "DDJ-400.konduktor-midi.json")
check("holds the mapping", json.loads(first.read_text()) == mapping)
second = Path(midi_export(MidiExportRequest(dir=str(folder), name="DDJ-400", mapping={"version": 1}))["path"])
check("never overwrites: a second export is -2", second.name == "DDJ-400-2.konduktor-midi.json")
check("the first file is untouched", json.loads(first.read_text()) == mapping)
sneaky = Path(midi_export(MidiExportRequest(dir=str(folder), name="../../escape", mapping=mapping))["path"])
check("a name cannot leave the folder", sneaky.parent == folder, str(sneaky))
check("a missing folder is refused", refused(lambda: midi_export(MidiExportRequest(dir=str(folder / "nope"), name="x", mapping=mapping)), 400))
check("a non-mapping is refused", refused(lambda: midi_export(MidiExportRequest(dir=str(folder), name="x", mapping={"version": 9})), 400))
print("import")
check("reads back what was exported", midi_import(str(first))["mapping"] == mapping)
bad = folder / "bad.konduktor-midi.json"
bad.write_text("{not json")
check("invalid JSON refused", refused(lambda: midi_import(str(bad)), 400))
bad.write_text(json.dumps([1, 2]))
check("not an object refused", refused(lambda: midi_import(str(bad)), 400))
bad.write_text(json.dumps({"version": 2}))
check("wrong version refused", refused(lambda: midi_import(str(bad)), 400))
big = folder / "big.konduktor-midi.json"
big.write_text(json.dumps({"version": 1, "pad": "x" * 1_100_000}))
check("an oversized file refused", refused(lambda: midi_import(str(big)), 400))
check("a missing file is 404", refused(lambda: midi_import(str(folder / "absent.json")), 404))
print("file browser")
(folder / "notes.json").write_text("{}")
listed = {f.name for f in fs_list(path=str(folder), suffix=".konduktor-midi.json").files}
check("the suffix lists mapping files only", "notes.json" not in listed and first.name in listed, str(listed))
sys.exit(1 if failed else 0)
+130 -3
View File
@@ -43,6 +43,38 @@ dependencies = [
"alloc-no-stdlib",
]
[[package]]
name = "alsa"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3f93573e7ddb15145d27c58c0fa0a452faad9f5452ac17ed4554ea035ea9b71"
dependencies = [
"alsa-sys",
"bitflags 2.13.0",
"cfg-if",
"libc",
]
[[package]]
name = "alsa-sys"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0320138053ef93099f168102c37b46ac0b9c53affc56ef7696633ad5477e2be"
dependencies = [
"cc",
"libc",
"pkg-config",
]
[[package]]
name = "android-build"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9fc9904ad2ad097c3c1cfe2eacaaf0fc24710936fa9ed941cb310b7c6ed2ab7"
dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "android_log-sys"
version = "0.3.2"
@@ -80,6 +112,7 @@ name = "app"
version = "0.1.1"
dependencies = [
"log",
"midir",
"serde",
"serde_json",
"tauri",
@@ -516,6 +549,27 @@ dependencies = [
"libc",
]
[[package]]
name = "coremidi"
version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a57ede822fdaf19280cf1320a5a5d3a522c75c910d01750af1e8122b6ad2595b"
dependencies = [
"block2",
"core-foundation 0.10.1",
"core-foundation-sys",
"coremidi-sys",
]
[[package]]
name = "coremidi-sys"
version = "3.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a2b8c2cefa9a8f712213c5a1383ffe428efc8f1a1fd1e2f757be94daf7e256a"
dependencies = [
"core-foundation-sys",
]
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -739,6 +793,16 @@ dependencies = [
"winapi",
]
[[package]]
name = "dlopen2"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60768c353d76ba6dd1b6332a5dbbdd3bc2dddadc2935f4cc6a9d0f17ca8ecb6a"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "dlopen2_derive"
version = "0.4.3"
@@ -1706,6 +1770,15 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "java-locator"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09c46c1fe465c59b1474e665e85e1256c3893dd00927b8d55f63b09044c1e64f"
dependencies = [
"glob",
]
[[package]]
name = "javascriptcore-rs"
version = "1.1.2"
@@ -1738,7 +1811,9 @@ dependencies = [
"cesu8",
"cfg-if",
"combine",
"java-locator",
"jni-sys 0.3.1",
"libloading",
"log",
"thiserror 1.0.69",
"walkdir",
@@ -1775,6 +1850,21 @@ dependencies = [
"syn 2.0.118",
]
[[package]]
name = "jni-min-helper"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "913370a00ba1851b0f3369b49d0f3e745da2d20d3f15ecc296a64234ccda45f7"
dependencies = [
"android-build",
"dlopen2 0.9.0",
"jni 0.21.1",
"libc",
"log",
"ndk-context",
"process_path",
]
[[package]]
name = "jni-sys"
version = "0.3.1"
@@ -1873,9 +1963,9 @@ dependencies = [
[[package]]
name = "libc"
version = "0.2.186"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "libdbus-sys"
@@ -1961,6 +2051,27 @@ dependencies = [
"autocfg",
]
[[package]]
name = "midir"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fea58b9250a667b032ff61fb1bf77aed74873152563f5cd613016dce4c821832"
dependencies = [
"alsa",
"cc",
"coremidi",
"jni 0.21.1",
"jni-min-helper",
"js-sys",
"libc",
"log",
"ndk-context",
"parking_lot",
"wasm-bindgen",
"web-sys",
"windows",
]
[[package]]
name = "mime"
version = "0.3.17"
@@ -2030,6 +2141,12 @@ dependencies = [
"thiserror 1.0.69",
]
[[package]]
name = "ndk-context"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"
[[package]]
name = "ndk-sys"
version = "0.6.0+11769913"
@@ -2602,6 +2719,16 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "process_path"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f676f11eb0b3e2ea0fbaee218fa6b806689e2297b8c8adc5bf73df465c4f6171"
dependencies = [
"libc",
"winapi",
]
[[package]]
name = "ptr_meta"
version = "0.1.4"
@@ -3568,7 +3695,7 @@ dependencies = [
"crossbeam-channel",
"dbus",
"dispatch2",
"dlopen2",
"dlopen2 0.8.2",
"dpi",
"gdkwayland-sys",
"gdkx11-sys",
+2
View File
@@ -31,4 +31,6 @@ tokio = { version = "1", features = ["time"] } # timeout on the port handshake
# One-click update (UpdateDialog.tsx). No `zip` feature: it only unpacks
# v1-style zipped Windows installers (we ship the bare NSIS setup.exe), and
# every zip 4.x it would need is yanked.
# MIDI controller input (src/midi.rs): CoreMIDI on macOS, WinMM on Windows.
midir = "0.11"
tauri-plugin-updater = { version = "2.12", default-features = false, features = ["rustls-tls", "system-proxy"] }
+44
View File
@@ -0,0 +1,44 @@
// MIDI transport spike (macOS): a virtual CoreMIDI source named
// "Konduktor Flood" that sends a jog-like CC stream at a fixed rate, so the
// shell's MIDI path can be measured without hardware.
//
// cargo run --example midi_flood -- <rate Hz> <count> <start delay s>
//
// Each message is CC 33 on channel 1 with a 7-bit counter as its value, so
// the receiver can check for drops and reordering.
#[cfg(target_os = "macos")]
fn main() {
use midir::os::unix::VirtualOutput;
use midir::MidiOutput;
use std::time::{Duration, Instant};
let args: Vec<String> = std::env::args().collect();
let rate: f64 = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(1000.0);
let count: u32 = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(5000);
let delay: f64 = args.get(3).and_then(|s| s.parse().ok()).unwrap_or(3.0);
let out = MidiOutput::new("Konduktor Flood").expect("MIDI client");
let mut conn = out.create_virtual("Konduktor Flood").expect("virtual source");
std::thread::sleep(Duration::from_secs_f64(delay));
let start = Instant::now();
let step = Duration::from_secs_f64(1.0 / rate);
for i in 0..count {
let due = start + step * i;
while Instant::now() < due {
let left = due - Instant::now();
if left > Duration::from_micros(300) {
std::thread::sleep(left - Duration::from_micros(200));
}
}
conn.send(&[0xB0, 33, (i % 128) as u8]).expect("send");
}
eprintln!("sent {count} at {rate} Hz in {:.3} s", start.elapsed().as_secs_f64());
std::thread::sleep(Duration::from_secs(1));
}
#[cfg(not(target_os = "macos"))]
fn main() {
eprintln!("midi_flood needs CoreMIDI virtual ports (macOS).");
}
+11 -1
View File
@@ -37,6 +37,12 @@
// runs. Cancel in the Save / Discard prompt keeps the update staged, so the
// next ordinary quit installs it (without relaunching). A failed install is
// written to `failed.json` for the next launch's dialog to report.
//
// MIDI controllers (midi.rs): WKWebView has no Web MIDI, so the shell lists
// and opens the input ports itself and streams their messages to the page
// (`midi_ports` / `midi_open` / `midi_close`); everything else is the page's.
mod midi;
use std::collections::VecDeque;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -459,6 +465,7 @@ pub fn run() {
.manage(Staged(Mutex::new(None)))
.manage(Backend { status: Mutex::new(BackendStatus::Starting), generation: AtomicU64::new(0) })
.manage(Quit { allowed: AtomicBool::new(false), acked: AtomicBool::new(false) })
.manage(midi::MidiInputs::default())
.invoke_handler(tauri::generate_handler![
backend_status,
backend_restart,
@@ -467,7 +474,10 @@ pub fn run() {
quit_now,
update_download,
update_restart,
update_take_failure
update_take_failure,
midi::midi_ports,
midi::midi_open,
midi::midi_close
])
.on_window_event(|window, event| {
if let WindowEvent::CloseRequested { api, .. } = event {
+124
View File
@@ -0,0 +1,124 @@
// MIDI INPUT for controller mapping (decided 2026-11-03,
// .claude/discussions/discuss-midi-controllers-2026-11-03.md).
//
// WKWebView has no Web MIDI, so the shell reads the ports itself with midir
// (CoreMIDI on macOS, WinMM on Windows) and streams each port's messages to the
// page over a `Channel` — the frontend does all parsing, mapping and learning
// (lib/midi/). Input only: nothing is ever sent to a controller.
//
// Batching without a timer: the driver's callback queues each message on an
// mpsc; one sender thread per port blocks on it, then drains whatever else has
// queued and sends that as ONE batch. Idle, a message goes out the moment it
// arrives; under a jog wheel's flood, messages coalesce instead of queueing up
// one IPC call each. System messages (SysEx, MIDI clock, active sensing) are
// ignored at the driver: a 24-ppqn clock from a mixer would flood the page.
//
// `wall_us` is the wall clock (µs since the Unix epoch) when the driver handed
// the message over, so the page can measure transport latency against its own
// `Date.now()`.
use std::collections::HashMap;
use std::sync::mpsc;
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use midir::{Ignore, MidiInput, MidiInputConnection, MidiInputPort};
use serde::Serialize;
use tauri::ipc::Channel;
use tauri::State;
#[derive(Clone, Serialize)]
pub struct MidiPacket {
pub wall_us: u64,
pub bytes: Vec<u8>,
}
/// Open connections by port name. Dropping one closes the port and ends its
/// sender thread (the callback's mpsc sender goes with it).
#[derive(Default)]
pub struct MidiInputs(Mutex<HashMap<String, MidiInputConnection<()>>>);
fn client() -> Result<MidiInput, String> {
let mut input = MidiInput::new("Konduktor").map_err(|e| e.to_string())?;
input.ignore(Ignore::All);
Ok(input)
}
/// Every input port with a unique name: two identical controllers are
/// "X" and "X #2", in the order the OS lists them.
fn named_ports(input: &MidiInput) -> Vec<(String, MidiInputPort)> {
let mut seen: HashMap<String, usize> = HashMap::new();
input
.ports()
.into_iter()
.filter_map(|p| {
let base = input.port_name(&p).ok()?;
let n = seen.entry(base.clone()).or_insert(0);
*n += 1;
let name = if *n == 1 { base } else { format!("{base} #{n}") };
Some((name, p))
})
.collect()
}
fn now_us() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_micros() as u64).unwrap_or(0)
}
#[tauri::command]
pub fn midi_ports() -> Result<Vec<String>, String> {
Ok(named_ports(&client()?).into_iter().map(|(name, _)| name).collect())
}
/// Open `port` and stream its messages to `on_message`. Opening a port that is
/// already open replaces the old connection (a page reload re-opens).
#[tauri::command]
pub fn midi_open(
inputs: State<'_, MidiInputs>,
port: String,
on_message: Channel<Vec<MidiPacket>>,
) -> Result<(), String> {
let input = client()?;
let found = named_ports(&input)
.into_iter()
.find(|(name, _)| *name == port)
.map(|(_, p)| p)
.ok_or_else(|| format!("MIDI port not found: {port}"))?;
let (tx, rx) = mpsc::channel::<MidiPacket>();
std::thread::Builder::new()
.name(format!("midi:{port}"))
.spawn(move || {
while let Ok(first) = rx.recv() {
let mut batch = vec![first];
while let Ok(more) = rx.try_recv() {
batch.push(more);
}
if on_message.send(batch).is_err() {
break; // the page went away
}
}
})
.map_err(|e| e.to_string())?;
let conn = input
.connect(
&found,
"Konduktor input",
move |_stamp, bytes, _| {
let _ = tx.send(MidiPacket { wall_us: now_us(), bytes: bytes.to_vec() });
},
(),
)
.map_err(|e| e.to_string())?;
inputs.0.lock().unwrap().insert(port, conn);
Ok(())
}
#[tauri::command]
pub fn midi_close(inputs: State<'_, MidiInputs>, port: String) {
if let Some(conn) = inputs.0.lock().unwrap().remove(&port) {
conn.close();
}
}
+12
View File
@@ -41,6 +41,8 @@ import { StemReportDialog } from './components/StemReportDialog'
import { SetPositionDialog } from './components/SetPositionDialog'
import { Icon } from './lib/icons'
import { usePrefsWriter } from './lib/prefs'
import { useMidi } from './lib/midi/useMidi'
import { midiTargets, useMidiTargets } from './lib/midi/targets'
function applyFilters(tracks: Track[], f: Filters): Track[] {
const q = f.search.trim().toLowerCase()
@@ -261,6 +263,16 @@ export default function App() {
}, [])
const onError = useCallback((msg: string) => notify('error', msg), [notify])
// MIDI controllers (lib/midi): found as they are plugged in; a controller's
// load buttons take the track list's highlighted row, loaded paused.
useMidi(notify)
useMidiTargets({
load: (deck) => {
const t = midiTargets.lead?.()
if (t) loadTrack(t, undefined, deck)
},
})
// Inline single-field edit from a double-clicked table cell. Only offered when
// the library can take an edit: passing `undefined` makes those cells inert
// rather than firing a request the adapter will refuse. Defaults to false, so
+6 -2
View File
@@ -1140,8 +1140,12 @@ export const api = {
// shortcuts and the browsable files are only meaningful inside that answer.
collectionOptions: (platform?: string) =>
getJSON<CollectionOptions>(`/api/library/options${qs({ platform })}`),
listDir: (path?: string, platform?: string) =>
getJSON<FsListing>(`/api/fs/list${qs({ path, platform })}`),
listDir: (path?: string, platform?: string, suffix?: string) =>
getJSON<FsListing>(`/api/fs/list${qs({ path, platform, suffix })}`),
/** A MIDI controller mapping to / from a file (lib/midi/mapping.ts). */
midiExport: (dir: string, name: string, mapping: unknown) =>
send<{ path: string }>('POST', '/api/midi/export', { dir, name, mapping }),
midiImport: (path: string) => getJSON<{ mapping: unknown }>(`/api/midi/import${qs({ path })}`),
/** Folders on the machine that HOLDS the library (a remote's server),
* confined to its content folder — `home` is that folder. */
libraryListDir: (path?: string) => getJSON<FsListing>(`/api/library/fs/list${qs({ path })}`),
+7 -5
View File
@@ -26,10 +26,10 @@ import { Icon, type IconName } from '../lib/icons'
* the cache key. Passing it back up through a callback would mean an effect
* firing on every navigation to tell the parent what it already asked for.
*/
export function useFsListing(path: string | undefined, platform?: string, listing: Listing = 'host') {
export function useFsListing(path: string | undefined, platform?: string, listing: Listing = 'host', suffix?: string) {
return useQuery({
queryKey: ['fs', listing, path ?? '~', platform ?? null],
queryFn: () => (listing === 'library' ? api.libraryListDir(path) : api.listDir(path, platform)),
queryKey: ['fs', listing, path ?? '~', platform ?? null, suffix ?? null],
queryFn: () => (listing === 'library' ? api.libraryListDir(path) : api.listDir(path, platform, suffix)),
})
}
@@ -65,10 +65,12 @@ interface Props {
footer?: ReactNode
/** Whose folders are browsed (see `Listing`). Default: this computer's. */
listing?: Listing
/** Instead of a platform's files, those whose name ends with this. */
suffix?: string
}
export function FileBrowser({ mode, platform, path, onNavigate, onPickFile, footer, listing: whose = 'host' }: Props) {
const listing = useFsListing(path, platform, whose)
export function FileBrowser({ mode, platform, path, onNavigate, onPickFile, footer, listing: whose = 'host', suffix }: Props) {
const listing = useFsListing(path, platform, whose, suffix)
const places = useQuery({
queryKey: ['fs-places', platform ?? null],
queryFn: () => api.places(platform),
+4
View File
@@ -5,6 +5,8 @@ import { Icon } from '../lib/icons'
import { RenameField } from './RenameField'
interface Props {
/** The deck's MIDI action prefix (`deck.A`), for on-screen learning. */
midi?: string
cues: CuePoint[]
/** Bank size, from capabilities — not every platform has eight. */
slotCount: number
@@ -42,6 +44,7 @@ const READONLY_LABELS: Record<string, string> = {
* than surfacing the refusal as an error.
*/
export function HotcueBar({
midi,
cues,
slotCount,
slotLabel,
@@ -74,6 +77,7 @@ export function HotcueBar({
return (
<button
key={slot}
data-midi-action={midi && `${midi}.hotcue.${slot + 1}`}
onContextMenu={(e) => {
e.preventDefault()
onSlotMenu(slot, e.clientX, e.clientY)
+13
View File
@@ -12,6 +12,9 @@ export function sizeLabel(size: number): string {
export type LoopMode = 'beat' | 'manual'
interface Props {
/** The deck's MIDI action prefix (`deck.A`): its controls carry
* `data-midi-action` for on-screen learning (lib/midi). */
midi?: string
mode: LoopMode
onMode: (mode: LoopMode) => void
hasGrid: boolean // beat loops and jumps are sized in beats; inert without a grid
@@ -67,6 +70,7 @@ const CLUSTER = 'well flex h-10 w-[8.5rem] shrink-0 items-center gap-0.5 rounded
* Presentational: PrepStrip owns every piece of state and does the seeking.
*/
export function LoopControls({
midi,
mode,
onMode,
hasGrid,
@@ -85,6 +89,7 @@ export function LoopControls({
onToggleLoop,
onMove,
}: Props) {
const m = (op: string) => (midi ? `${midi}.${op}` : undefined)
const atMin = size <= LOOP_SIZES[0]
const atMax = size >= LOOP_SIZES[LOOP_SIZES.length - 1]
const what = loopActive ? 'Move the loop' : `Jump ${sizeLabel(size)} beat${size === 1 ? '' : 's'}`
@@ -107,6 +112,7 @@ export function LoopControls({
<div role="group" aria-label="Loop size" className={`${CLUSTER} font-mono`}>
<button
onClick={onSmaller}
data-midi-action={m('sizeDown')}
disabled={atMin}
title="Halve the size (Cmd/Ctrl+↓)"
className={`${KEY} h-[34px] w-7 text-[15px] text-muted hover:bg-ink-800 hover:text-text`}
@@ -115,6 +121,7 @@ export function LoopControls({
</button>
<button
onClick={onToggleSize}
data-midi-action={m('sizeLoop')}
disabled={!hasGrid || !ready}
title={hasGrid ? `${sizeLabel(size)}-beat loop — click to switch on or off` : 'No beatgrid'}
className={`${KEY} h-[34px] min-w-0 flex-1 px-2 text-sm font-semibold ${
@@ -125,6 +132,7 @@ export function LoopControls({
</button>
<button
onClick={onBigger}
data-midi-action={m('sizeUp')}
disabled={atMax}
title="Double the size (Cmd/Ctrl+↑)"
className={`${KEY} h-[34px] w-7 text-[15px] text-muted hover:bg-ink-800 hover:text-text`}
@@ -136,6 +144,7 @@ export function LoopControls({
<div role="group" aria-label="Manual loop" className={`${CLUSTER} text-xs font-semibold`}>
<button
onClick={onLoopIn}
data-midi-action={m('loopIn')}
disabled={!ready}
aria-pressed={inArmed || manualSet}
title={inArmed ? 'Loop in is set — now press OUT (or IN again to move it)' : 'Loop in at the playhead'}
@@ -145,6 +154,7 @@ export function LoopControls({
</button>
<button
onClick={onLoopOut}
data-midi-action={m('loopOut')}
disabled={!ready || (!inArmed && !manualSet)}
aria-pressed={manualSet && !inArmed}
title={
@@ -160,6 +170,7 @@ export function LoopControls({
</button>
<button
onClick={onToggleLoop}
data-midi-action={m('loopToggle')}
disabled={!canToggle}
title={loopActive ? 'Switch the loop off' : 'Switch the loop on'}
aria-pressed={loopActive}
@@ -173,6 +184,7 @@ export function LoopControls({
<div role="group" aria-label="Jump or move loop" className="glass-group flex h-10 items-center rounded-xl">
<button
onClick={() => onMove(-1)}
data-midi-action={m('jumpBack')}
disabled={!canMove}
title={`${what} back (←)`}
className={`${HALF} rounded-l-xl`}
@@ -181,6 +193,7 @@ export function LoopControls({
</button>
<button
onClick={() => onMove(1)}
data-midi-action={m('jumpFwd')}
disabled={!canMove}
title={`${what} forward (→)`}
className={`${HALF} rounded-r-xl`}
+8 -3
View File
@@ -34,7 +34,8 @@ interface Props {
secPerView: number
onZoomChange: (secPerView: number) => void
onSeek: (t: number) => void
onScratchStart: () => void
/** Grab at `from` (s): later moves are relative to it. */
onScratchStart: (from: number) => void
onScratchMove: (t: number) => void
onScratchEnd: (t: number) => void
/** A stem track: one lane per stem instead of the three-band mix view. */
@@ -236,11 +237,15 @@ export function MainWaveform({
const rect = e.currentTarget.getBoundingClientRect()
const dx = e.clientX - d.startX
if (!d.moved && Math.abs(dx) > DRAG_THRESHOLD) {
// Measure from HERE and NOW: a playing deck has moved on since the
// press, and the threshold's pixels would be a jump.
d.moved = true
onScratchStart()
d.startX = e.clientX
d.startTime = currentTime
onScratchStart(currentTime)
}
if (d.moved) {
const t = Math.min(duration, Math.max(0, d.startTime - (dx / rect.width) * secPerView))
const t = Math.min(duration, Math.max(0, d.startTime - ((e.clientX - d.startX) / rect.width) * secPerView))
d.lastT = t
onScratchMove(t)
}
@@ -0,0 +1,108 @@
import { useEffect } from 'react'
import { createPortal } from 'react-dom'
import { actionDef } from '../lib/midi/actions'
import { armLearn, getMidiState, setOnScreenLearn, useMidiState } from '../lib/midi/store'
/**
* On-screen MIDI learning (Settings ▸ MIDI Controllers… ▸ Learn on screen):
* every control that has a MIDI action (`data-midi-action`) is ringed;
* clicking one ARMS it instead of using it, and the next control moved on a
* controller is bound to it — into the Shift layer if the controller's Shift
* is held. Mapped controls show solid, the armed one glows, and Done or Esc
* leaves. Mounted once (main.tsx); renders nothing until switched on.
*/
export function MidiLearnOverlay() {
const onScreen = useMidiState((s) => s.onScreen)
const armed = useMidiState((s) => s.armed)
const mappings = useMidiState((s) => s.mappings)
const ports = useMidiState((s) => s.ports)
const learned = useMidiState((s) => s.learned)
// Clicks on a learnable control arm it; nothing else changes. Pointer and
// mouse events are stopped in the capture phase so the control never acts
// (knobs and faders start their drags on pointerdown).
useEffect(() => {
if (!onScreen) return
const target = (e: Event) => (e.target as Element | null)?.closest?.('[data-midi-action]') as HTMLElement | null
const stop = (e: Event) => {
const el = target(e)
if (!el) return
e.preventDefault()
e.stopPropagation()
if (e.type !== 'pointerdown') return
const action = el.dataset.midiAction!
const a = getMidiState().armed
armLearn(a && 'layer' in a && a.action === action ? null : { action, layer: 'normal' })
}
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return
e.preventDefault()
e.stopPropagation()
if (getMidiState().armed) armLearn(null)
else setOnScreenLearn(false)
}
const kinds = ['pointerdown', 'pointerup', 'mousedown', 'mouseup', 'click', 'dblclick', 'contextmenu']
for (const k of kinds) window.addEventListener(k, stop, true)
window.addEventListener('keydown', onKey, true)
document.body.classList.add('midi-learn')
return () => {
for (const k of kinds) window.removeEventListener(k, stop, true)
window.removeEventListener('keydown', onKey, true)
document.body.classList.remove('midi-learn')
}
}, [onScreen])
// Mark the controls: mapped (on a connected controller), armed, just learned.
useEffect(() => {
if (!onScreen) return
const mapped = new Set<string>()
for (const p of ports) {
for (const b of Object.values(mappings[p]?.bindings ?? {})) {
if (b.normal) mapped.add(b.normal)
if (b.shift) mapped.add(b.shift)
}
}
const armedId = armed && 'layer' in armed ? armed.action : null
const flash = learned && performance.now() - learned.at < 1500 ? learned.action : null
for (const el of document.querySelectorAll<HTMLElement>('[data-midi-action]')) {
const id = el.dataset.midiAction!
el.toggleAttribute('data-midi-mapped', mapped.has(id))
el.toggleAttribute('data-midi-armed', id === armedId)
el.toggleAttribute('data-midi-learned', id === flash)
}
// The "just learned" flash fades on its own.
const fade = flash ? setTimeout(() => document.querySelector('[data-midi-learned]')?.removeAttribute('data-midi-learned'), 1500) : 0
return () => {
clearTimeout(fade)
for (const el of document.querySelectorAll('[data-midi-action]')) {
el.removeAttribute('data-midi-mapped')
el.removeAttribute('data-midi-armed')
el.removeAttribute('data-midi-learned')
}
}
}, [onScreen, armed, mappings, ports, learned])
if (!onScreen) return null
const armedLabel = armed && 'layer' in armed ? actionDef(armed.action)?.label : null
return createPortal(
<div className="pointer-events-none fixed inset-x-0 top-3 z-[80] flex justify-center">
<div className="pointer-events-auto flex items-center gap-3 glass-overlay rounded-full px-4 py-2 text-sm text-text">
<span className="h-2 w-2 animate-pulse rounded-full bg-accent" />
{ports.length === 0 ? (
<span>MIDI learn — plug in a controller</span>
) : armedLabel ? (
<span>
<span className="font-semibold">{armedLabel}</span>: move a control on your controller — an encoder a few clicks in
this action's direction (hold its Shift for the Shift layer)
</span>
) : (
<span>MIDI learn — click a control, then move it on your controller</span>
)}
<button onClick={() => setOnScreenLearn(false)} className="rounded-full btn-primary px-3 py-1 text-xs font-semibold">
Done
</button>
</div>
</div>,
document.body,
)
}
+397
View File
@@ -0,0 +1,397 @@
import { useEffect, useMemo, useState } from 'react'
import { api } from '../api'
import { ACTION_GROUPS, ACTIONS, type ActionDef } from '../lib/midi/actions'
import { ENCODING_LABELS, ENCODINGS } from '../lib/midi/encoding'
import {
DEFAULT_JOG_SENSITIVITY,
DEFAULT_SCRUB_SPEED,
bindShift,
emptyMapping,
sanitizeMapping,
setBinding,
sourcesFor,
unbind,
type Layer,
type Mapping,
} from '../lib/midi/mapping'
import { describeSource, splitSource, type SourceKey } from '../lib/midi/messages'
import { armLearn, replaceMappings, setOnScreenLearn, updateMapping, useMidiState, type LearnTarget } from '../lib/midi/store'
import { askConfirm } from '../lib/confirm'
import { ContextMenu, type MenuItem } from './ContextMenu'
import { FileBrowser } from './FileBrowser'
import { FolderPicker } from './FolderPicker'
import { Modal } from './Modal'
const section = 'text-[11px] font-semibold uppercase tracking-wider text-faint'
const MAPPING_SUFFIX = '.konduktor-midi.json'
const which = (t: LearnTarget) => ('layer' in t ? t.layer : t.slot)
const sameTarget = (a: LearnTarget | null, b: LearnTarget) => a != null && a.action === b.action && which(a) === which(b)
/**
* Settings ▸ MIDI Controllers… (decided 2026-11-03): every controller is
* mapped by LEARNING — press Learn beside an action (or "Learn on screen" and
* click the control), then move the control. Each control has a normal and a
* free Shift binding; Shift itself is a learned control. Mappings are per
* controller, kept in userprefs, and shareable as files.
*/
export function MidiSettings({ onClose }: { onClose: () => void }) {
const available = useMidiState((s) => s.available)
const blocked = useMidiState((s) => s.blocked)
const ports = useMidiState((s) => s.ports)
const mappings = useMidiState((s) => s.mappings)
const armed = useMidiState((s) => s.armed)
const activity = useMidiState((s) => s.activity)
const learned = useMidiState((s) => s.learned)
const known = useMemo(() => [...new Set([...ports, ...Object.keys(mappings)])], [ports, mappings])
const [selected, setSelected] = useState<string | null>(null)
const port = selected && known.includes(selected) ? selected : (known[0] ?? null)
const mapping: Mapping = (port && mappings[port]) || emptyMapping()
const [filter, setFilter] = useState('')
const [menu, setMenu] = useState<{ x: number; y: number; items: MenuItem[] } | null>(null)
const [exporting, setExporting] = useState(false)
const [importing, setImporting] = useState(false)
const [note, setNote] = useState<{ error: boolean; text: string } | null>(null)
// What was just learned shows under its own controller.
useEffect(() => {
if (learned) setSelected(learned.port)
}, [learned])
// Closing the dialog stops waiting for a control.
useEffect(() => () => armLearn(null), [])
const learn = (t: LearnTarget) => armLearn(sameTarget(armed, t) ? null : t)
const edit = (fn: (m: Mapping) => Mapping) => port && updateMapping(port, fn)
const bindingMenu = (e: React.MouseEvent, src: SourceKey, action: ActionDef, layer: Layer) => {
const b = mapping.bindings[src]
if (!b) return
const r = e.currentTarget.getBoundingClientRect()
const items: MenuItem[] = [{ heading: describeSource(src) }]
if (splitSource(src).dir) {
// An encoder turned for a button action: how it counts its clicks.
items.push(
{
label: 'Encoding',
submenu: ENCODINGS.filter((x) => x !== 'button' && x !== 'abs7' && x !== 'abs14').map((x) => ({
label: ENCODING_LABELS[x],
hint: x === b.encoding ? '✓' : undefined,
onClick: () => edit((m) => setBinding(m, src, { encoding: x })),
})),
},
{ separator: true },
)
} else if (action.kind !== 'button' && action.kind !== 'hold') {
items.push(
{
label: 'Encoding',
submenu: ENCODINGS.filter((x) => x !== 'button').map((x) => ({
label: ENCODING_LABELS[x],
hint: x === b.encoding ? '✓' : undefined,
onClick: () => edit((m) => setBinding(m, src, { encoding: x })),
})),
},
{ label: 'Reversed', checked: !!b.invert, onToggle: () => edit((m) => setBinding(m, src, { invert: !b.invert || undefined })) },
{ separator: true },
)
}
items.push(
{ label: 'Learn again', onClick: () => learn({ action: action.id, layer }) },
{ label: 'Clear', danger: true, onClick: () => edit((m) => unbind(m, action.id, layer)) },
)
setMenu({ x: r.left, y: r.bottom + 4, items })
}
const cell = (action: ActionDef, layer: Layer) => {
const t: LearnTarget = { action: action.id, layer }
if (sameTarget(armed, t)) {
return (
<button onClick={() => armLearn(null)} className="w-full animate-pulse rounded-md bg-accent/25 px-2 py-1 text-left text-[11px] text-text ring-1 ring-accent">
Move a control…
</button>
)
}
const sources = sourcesFor(mapping, action.id, layer)
if (sources.length === 0) {
return (
<button onClick={() => learn(t)} className="w-full rounded-md px-2 py-1 text-left text-[11px] text-faint hover:bg-ink-800 hover:text-text">
Learn
</button>
)
}
return (
<div className="flex flex-wrap gap-1">
{sources.map((src) => {
const enc = mapping.bindings[src]?.encoding
return (
<button
key={src}
onClick={(e) => bindingMenu(e, src, action, layer)}
title={enc && enc !== 'button' ? ENCODING_LABELS[enc] : undefined}
className="rounded-md bg-ink-800 px-2 py-1 font-mono text-[10.5px] text-text hover:bg-ink-700"
>
{describeSource(src)}
{mapping.bindings[src]?.invert ? ' ⇄' : ''}
</button>
)
})}
</div>
)
}
const needle = filter.trim().toLowerCase()
const shown = ACTIONS.filter((a) => !needle || a.label.toLowerCase().includes(needle) || a.group.toLowerCase().includes(needle))
const forget = async () => {
if (!port) return
const ok = await askConfirm({
title: `Forget ${port}'s mapping?`,
body: 'Every learned control on this controller is cleared.',
confirmLabel: 'Forget',
})
if (!ok) return
const next = { ...mappings }
delete next[port]
replaceMappings(next)
}
const doExport = async (dir: string) => {
if (!port) return
try {
const { path } = await api.midiExport(dir, port, mapping)
setNote({ error: false, text: `Saved ${path}` })
} catch (e) {
setNote({ error: true, text: (e as Error).message })
}
}
const doImport = async (path: string) => {
setImporting(false)
if (!port) return
try {
const m = sanitizeMapping((await api.midiImport(path)).mapping)
if (!m) throw new Error('That file is not a MIDI mapping')
if (Object.keys(mapping.bindings).length > 0 || mapping.shifts.some(Boolean)) {
const ok = await askConfirm({
title: `Replace ${port}'s mapping?`,
body: 'The imported mapping replaces every control learned on this controller.',
confirmLabel: 'Replace',
})
if (!ok) return
}
updateMapping(port, () => m)
setNote({ error: false, text: `Imported ${Object.keys(m.bindings).length} controls` })
} catch (e) {
setNote({ error: true, text: (e as Error).message })
}
}
return (
<Modal onDismiss={armed ? () => armLearn(null) : onClose}>
<div className="flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden glass-overlay">
<div className="flex items-center justify-between border-b border-line px-5 py-3">
<h2 className="text-sm font-semibold text-text">MIDI Controllers</h2>
<button onClick={onClose} className="rounded px-1.5 text-faint hover:text-text" aria-label="Close">
×
</button>
</div>
{!available ? (
<div className="px-5 py-6 text-sm text-muted">
MIDI is not available here. The desktop app reads controllers itself; in a browser, use Chrome.
</div>
) : blocked && known.length === 0 ? (
<div className="space-y-1 px-5 py-6 text-sm text-muted">
<p>The browser refused access to MIDI devices.</p>
<p className="text-xs text-faint">
Allow it from the site settings (the icon left of the address: MIDI devices → Allow). Konduktor asks again on
its own. ({blocked})
</p>
</div>
) : known.length === 0 ? (
<div className="px-5 py-6 text-sm text-muted">Plug in a MIDI controller — it shows up here within a couple of seconds.</div>
) : (
<>
<div className="space-y-3 border-b border-line px-5 py-3 text-sm">
<div className="flex flex-wrap items-center gap-2">
<select
value={port ?? ''}
onChange={(e) => setSelected(e.target.value)}
className="min-w-0 max-w-[16rem] rounded-lg well px-2 py-1 text-sm text-text outline-none"
>
{known.map((p) => (
<option key={p} value={p}>
{p}
{ports.includes(p) ? '' : ' (not connected)'}
</option>
))}
</select>
<span className="min-w-0 flex-1 truncate font-mono text-[11px] text-faint">
{activity
? `${activity.port}: ${describeSource(activity.source)} → ${activity.value}`
: 'Move a control to see it here'}
</span>
<button
onClick={() => {
setOnScreenLearn(true)
onClose()
}}
className="btn-glass rounded-full px-3 py-1 text-xs text-text"
title="Click a control on screen, then move it on your controller"
>
Learn on screen
</button>
<button onClick={() => setImporting(true)} className="btn-glass rounded-full px-3 py-1 text-xs text-muted hover:text-text">
Import…
</button>
<button onClick={() => setExporting(true)} className="btn-glass rounded-full px-3 py-1 text-xs text-muted hover:text-text">
Export…
</button>
{mappings[port ?? ''] && (
<button onClick={() => void forget()} className="rounded-full px-2 py-1 text-xs text-faint hover:text-pink">
Forget
</button>
)}
</div>
{note && <div className={`text-xs ${note.error ? 'text-pink' : 'text-faint'}`}>{note.text}</div>}
<div className="grid grid-cols-[auto_1fr] items-center gap-x-4 gap-y-2">
{([0, 1] as const).map((slot) => {
const src = mapping.shifts[slot]
const t: LearnTarget = { action: 'shift', slot }
return (
<div key={slot} className="contents">
<span className="text-text">{slot === 0 ? 'Shift button' : 'Second Shift'}</span>
<div className="flex items-center gap-2">
{sameTarget(armed, t) ? (
<button onClick={() => armLearn(null)} className="animate-pulse rounded-md bg-accent/25 px-2 py-1 text-[11px] text-text ring-1 ring-accent">
Press the controller's Shift…
</button>
) : src ? (
<>
<span className="rounded-md bg-ink-800 px-2 py-1 font-mono text-[10.5px] text-text">{describeSource(src)}</span>
<button onClick={() => learn(t)} className="text-[11px] text-faint hover:text-text">
Learn again
</button>
<button onClick={() => edit((m) => bindShift(m, null, slot))} className="text-[11px] text-faint hover:text-pink">
Clear
</button>
</>
) : (
<button onClick={() => learn(t)} className="rounded-md px-2 py-1 text-[11px] text-faint hover:bg-ink-800 hover:text-text">
Learn
</button>
)}
<span className="text-[11px] text-faint">
{slot === 0
? 'Hold it while moving a control to learn its Shift action.'
: 'Optional — many controllers have one per deck. Either one gives the Shift layer.'}
</span>
</div>
</div>
)
})}
<span className="text-text">Jog sensitivity</span>
<Slider
value={mapping.jogSensitivity}
min={0.05}
max={4}
step={0.05}
reset={DEFAULT_JOG_SENSITIVITY}
format={(v) => `×${v.toFixed(2)}`}
onChange={(v) => edit((m) => ({ ...m, jogSensitivity: v }))}
/>
<span className="text-text">Fast scrub</span>
<Slider
value={mapping.scrubSpeed}
min={2}
max={32}
step={1}
reset={DEFAULT_SCRUB_SPEED}
format={(v) => `×${v} a jog`}
onChange={(v) => edit((m) => ({ ...m, scrubSpeed: v }))}
/>
</div>
</div>
<div className="flex items-center gap-3 border-b border-line px-5 py-2">
<input
value={filter}
onChange={(e) => setFilter(e.target.value)}
placeholder="Find an action…"
className="w-56 rounded-md well px-2 py-1 text-xs text-text outline-none focus:ring-1 focus:ring-accent"
/>
<span className="min-w-0 flex-1 truncate text-[11px] text-faint" title="A button action can be an encoder turned one way: learn it by turning a few clicks in that direction (↻ / ↺).">
Buttons: press it, or turn an encoder a few clicks in this action's direction.
</span>
<span className="w-36 text-[11px] font-semibold uppercase tracking-wider text-faint">Control</span>
<span className="w-36 text-[11px] font-semibold uppercase tracking-wider text-faint">With Shift</span>
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-5 pb-4">
{ACTION_GROUPS.map((g) => {
const rows = shown.filter((a) => a.group === g)
if (rows.length === 0) return null
return (
<section key={g} className="pt-3">
<h3 className={`${section} pb-1`}>
{g}
{g === 'Deck B' || g === 'Mixer' ? <span className="ml-2 normal-case tracking-normal">— performance mode only</span> : null}
</h3>
{rows.map((a) => (
<div key={a.id} className="flex items-center gap-3 border-b border-line/40 py-1">
<span className="min-w-0 flex-1 truncate text-sm text-text">{a.label}</span>
<div className="w-36 shrink-0">{cell(a, 'normal')}</div>
<div className="w-36 shrink-0">{cell(a, 'shift')}</div>
</div>
))}
</section>
)
})}
</div>
</>
)}
</div>
{menu && <ContextMenu {...menu} onClose={() => setMenu(null)} />}
{exporting && <FolderPicker value="" onChange={(dir) => void doExport(dir)} onClose={() => setExporting(false)} />}
{importing && <ImportPicker onPick={(p) => void doImport(p)} onClose={() => setImporting(false)} />}
</Modal>
)
}
function Slider({ value, min, max, step, reset, format, onChange }: {
value: number; min: number; max: number; step: number; reset: number; format: (v: number) => string; onChange: (v: number) => void
}) {
return (
<div className="flex items-center gap-3">
<input
type="range"
min={min}
max={max}
step={step}
value={value}
onChange={(e) => onChange(Number(e.target.value))}
onDoubleClick={() => onChange(reset)}
className="w-48"
/>
<span className="font-mono text-[11px] text-muted">{format(value)}</span>
</div>
)
}
/** Pick a `.konduktor-midi.json` file. */
function ImportPicker({ onPick, onClose }: { onPick: (path: string) => void; onClose: () => void }) {
const [dir, setDir] = useState<string | undefined>(undefined)
return (
<Modal onDismiss={onClose} layer="nested" padding="p-4">
<div className="flex h-[70vh] w-full max-w-2xl flex-col overflow-hidden glass-overlay">
<div className="border-b border-line px-5 py-3">
<h2 className="text-sm font-semibold text-text">Import a MIDI mapping</h2>
</div>
<FileBrowser mode="file" suffix={MAPPING_SUFFIX} path={dir} onNavigate={setDir} onPickFile={onPick} />
<div className="flex justify-end border-t border-line px-5 py-3">
<button onClick={onClose} className="btn-glass rounded-full px-3 py-1.5 text-sm text-muted hover:text-text">
Cancel
</button>
</div>
</div>
</Modal>
)
}
+43
View File
@@ -2,6 +2,8 @@ import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'
import { useQuery } from '@tanstack/react-query'
import { api, type Capabilities, type Track, type TrackOrigin } from '../api'
import { useDeckKeys, type DeckKeyTargets } from '../lib/deckKeys'
import { useMidiTargets } from '../lib/midi/targets'
import type { DeckMidi } from '../lib/midi/router'
import { useDropTarget, type DragPayload } from '../lib/drag'
import { usePrefsWriter } from '../lib/prefs'
import { mixer } from '../lib/audio/mixer'
@@ -283,6 +285,47 @@ export function PrepStrip({
return phaseOffset(theirs, mine, octaveFor(eo, em))
}
// A controller (lib/midi): the same deck handles the keys get, plus pitch
// and jog. Moving the pitch fader or nudging with the jog releases SYNC, as
// the on-screen fader and the phase meter's bend do (decided 2026-11-03).
const releaseSync = (id: DeckId) => live.current.synced[id] && setSynced((s) => ({ ...s, [id]: false }))
const midiDeck = (id: DeckId): DeckMidi => {
const d = deckOf(id)
return {
...d.shortcuts,
toggleSizeLoop: d.toggleSizeLoop,
loopIn: d.loopIn,
loopOut: d.loopOut,
toggleLoop: d.toggleLoop,
toggleSync: () => {
if (!performance) return
if (synced[id] || !syncBlocked(id)) toggleSync(id)
else onError?.(syncBlocked(id)!)
},
// As the on-screen MASTER button: performance mode, a track loaded.
makeMaster: () => {
if (performance && d.track) makeMaster(id)
},
toggleKeylock: () => d.setKeylock(!d.keylock),
pitch: d.pitch,
setPitch: (v) => {
releaseSync(id)
d.setPitch(v)
},
jogTouch: (on) => d.jogTouch(on),
jogTurn: (ticks, sensitivity) => {
if (d.jogTurn(ticks, sensitivity) === 'nudge') releaseSync(id)
},
scrub: (ticks, sensitivity) => d.scrub(ticks, sensitivity),
}
}
useMidiTargets({
performance,
focused: lead,
decks: { A: midiDeck('A'), B: performance ? midiDeck('B') : null },
togglePerformance: onTogglePerformance,
})
const keys = useRef<DeckKeyTargets>({ focused: null, other: null })
keys.current = {
focused: deckOf(lead).shortcuts,
+13
View File
@@ -4,6 +4,7 @@ import { api } from '../api'
import { AppSettings } from './AppSettings'
import { useCaps } from '../lib/capabilities'
import { LocalLibrariesSettings } from './LocalLibrariesSettings'
import { MidiSettings } from './MidiSettings'
import { PerformanceSettings } from './PerformanceSettings'
import { RemoteCacheSettings } from './RemoteCacheSettings'
import { ShortcutsDialog } from './ShortcutsDialog'
@@ -26,6 +27,7 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
const [showApp, setShowApp] = useState(false)
const [showLocal, setShowLocal] = useState(false)
const [showPerformance, setShowPerformance] = useState(false)
const [showMidi, setShowMidi] = useState(false)
const ref = useRef<HTMLDivElement>(null)
// Path remapping is a library on THIS computer's business; a remote's
// mapping is its server's configuration.
@@ -157,6 +159,16 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
<span className="text-sm text-text">Performance mode…</span>
<span className="text-[11px] text-faint">The second deck, the mixer and its effects</span>
</button>
<button
onClick={() => {
setShowMidi(true)
setOpen(false)
}}
className={item}
>
<span className="text-sm text-text">MIDI Controllers…</span>
<span className="text-[11px] text-faint">Map a controller by moving its controls</span>
</button>
<button
onClick={() => {
setShowShortcuts(true)
@@ -175,6 +187,7 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
{showApp && <AppSettings onClose={() => setShowApp(false)} />}
{showLocal && <LocalLibrariesSettings onClose={() => setShowLocal(false)} />}
{showPerformance && <PerformanceSettings onClose={() => setShowPerformance(false)} />}
{showMidi && <MidiSettings onClose={() => setShowMidi(false)} />}
</div>
)
}
+52 -2
View File
@@ -16,6 +16,10 @@ import { PlatformIcon } from '../lib/platformIcons'
import { addTracksToPlaylist } from '../lib/addTracks'
import { useDragPayload, usePressToDrag, useDropTarget, type DragPayload, type TracksOrFiles } from '../lib/drag'
import { findNode, idsAfter, nodeIdsUnder, playlistIdsUnder } from '../lib/playlistTree'
import { useMidiTargets } from '../lib/midi/targets'
/** All Tracks' place in a controller's walk of the tree (no node has this id). */
const ALL_ROW = 'konduktor:all-tracks'
/**
* Which view the main table is showing.
@@ -104,6 +108,8 @@ interface RowActions {
/** Whether a folder is open, and opening / closing it. */
isOpen: (node: PlaylistNode) => boolean
setOpen: (node: PlaylistNode, open: boolean) => void
/** Where a controller's playlist browsing stands (lib/midi), when not on the open playlist. */
isCursor: (node: PlaylistNode) => boolean
onContextMenu: (e: React.MouseEvent, node: PlaylistNode) => void
onRename: (node: PlaylistNode, name: string, parentId: string | null) => void
onDelete: (node: PlaylistNode) => void
@@ -300,6 +306,7 @@ function NodeRow({
<div
ref={dropRef}
data-node-row
data-node-id={node.id}
onPointerDown={startDrag}
onContextMenu={(e) => actions.onContextMenu(e, node)}
className={`group relative flex items-center gap-1 rounded-[10px] pr-1 text-sm transition-colors ${
@@ -307,7 +314,9 @@ function NodeRow({
? 'bg-accent-soft/40 text-text ring-1 ring-accent'
: selected
? 'is-selected font-medium text-text'
: 'text-muted hover:bg-ink-800 hover:text-text'
: actions.isCursor(node)
? 'bg-ink-800 text-text ring-1 ring-accent/60'
: 'text-muted hover:bg-ink-800 hover:text-text'
}`}
>
{line && (
@@ -485,6 +494,45 @@ export function Sidebar({
useEffect(() => setOpenOverrides({}), [library?.path, expandByDefault])
const setFolderOpen = (id: string, open: boolean) =>
setOpenOverrides((o) => ({ ...o, [id]: open }))
const isOpen = (node: PlaylistNode) => openOverrides[node.id] ?? expandByDefault
// A controller's Shift + browse walks All Tracks and the visible playlist
// tree (decided 2026-11-03): a playlist opens as it is reached, a folder is
// only highlighted (the cursor) and opens / closes on the encoder's press.
const [treeCursor, setTreeCursor] = useState<string | null>(null)
useEffect(() => setTreeCursor(null), [source])
const visibleRows = (): { id: string; node: PlaylistNode | null }[] => {
const out: { id: string; node: PlaylistNode | null }[] = [{ id: ALL_ROW, node: null }]
const walk = (nodes: PlaylistNode[]) => {
for (const n of nodes) {
out.push({ id: n.id, node: n })
if (n.kind === 'folder' && isOpen(n)) walk(n.children)
}
}
walk(playlists ?? [])
return out
}
useMidiTargets({
tree: {
step: (ticks) => {
const rows = visibleRows()
const at = treeCursor ?? (source.kind === 'all' ? ALL_ROW : source.kind === 'playlist' ? source.id : null)
const i = rows.findIndex((r) => r.id === at)
const next = rows[Math.max(0, Math.min(rows.length - 1, i < 0 ? 0 : i + ticks))]
if (!next) return
if (!next.node) onSelect({ kind: 'all' })
else if (next.node.kind !== 'folder' && next.node.selectable) {
onSelect({ kind: 'playlist', id: next.node.id, name: next.node.name })
}
setTreeCursor(next.id)
document.querySelector(`[data-node-id="${CSS.escape(next.id)}"]`)?.scrollIntoView({ block: 'nearest' })
},
press: () => {
const node = treeCursor ? findNode(playlists ?? [], treeCursor) : null
if (node?.kind === 'folder') setFolderOpen(node.id, !isOpen(node))
},
},
})
// A folder's id — and so every id under it — may change when it is renamed
// or moved (a platform addressing folders by path), so open state follows
// the subtree to its new ids. Reads the tree as refetched after the edit.
@@ -631,8 +679,9 @@ export function Sidebar({
}
const actions: RowActions = {
isOpen: (node) => openOverrides[node.id] ?? expandByDefault,
isOpen,
setOpen: (node, open) => setFolderOpen(node.id, open),
isCursor: (node) => treeCursor === node.id,
onContextMenu: (e, node) => openMenu(e, nodeItems(node)),
onRename: (node, name, parentId) => rename.mutate({ node, name, parentId }),
onDelete: confirmDelete,
@@ -760,6 +809,7 @@ export function Sidebar({
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto">
<div className="shrink-0 px-2 pt-3">
<button
data-node-id={ALL_ROW}
onClick={() => onSelect({ kind: 'all' })}
className={`flex w-full items-center gap-2 rounded-[10px] px-2 py-1.5 text-left text-sm transition-colors ${
source.kind === 'all'
+17 -2
View File
@@ -13,6 +13,7 @@ import {
import { useVirtualizer } from '@tanstack/react-virtual'
import { Icon } from '../lib/icons'
import { useCaps } from '../lib/capabilities'
import { useMidiTargets } from '../lib/midi/targets'
import {
DndContext,
PointerSensor,
@@ -542,11 +543,16 @@ export function TrackTable({
}
if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return
e.preventDefault()
moveLead(e.key === 'ArrowDown' ? 1 : -1, e.shiftKey)
}
/** Move the highlight `step` rows (Shift: extend the selection) — ↑/↓, and
* a controller's browse encoder. */
const moveLead = (step: number, extend: boolean) => {
if (!selection || rows.length === 0) return
const lead = indexOf(leadRef.current)
const step = e.key === 'ArrowDown' ? 1 : -1
const next = lead < 0 ? 0 : Math.max(0, Math.min(rows.length - 1, lead + step))
const anchor = indexOf(anchorRef.current)
if (e.shiftKey && anchor >= 0) {
if (extend && anchor >= 0) {
leadRef.current = rows[next].original.id
selection.onChange(new Set(rangeIds(anchor, next)))
} else {
@@ -554,6 +560,15 @@ export function TrackTable({
}
virtualizer.scrollToIndex(next)
}
// A controller's browse encoder moves the highlight as ↑/↓ do, and its load
// buttons take the highlighted row (lib/midi).
useMidiTargets({
browse: selection && onPlay ? (ticks) => moveLead(ticks, false) : null,
lead: () => {
const i = indexOf(leadRef.current)
return i >= 0 && selection?.selected.has(rows[i].original.id) ? rows[i].original : null
},
})
useEffect(() => {
const onKey = (e: KeyboardEvent) => keysRef.current(e)
window.addEventListener('keydown', onKey)
@@ -88,11 +88,15 @@ export function DeckControls({ deck, stacked = false }: { deck: Deck; stacked?:
renamingSlot,
renameSlot,
tempoProps,
channel,
} = deck
// On-screen MIDI learning (lib/midi): controls carry their action.
const midi = `deck.${channel}`
const transport = (
<>
<button
onClick={toggle}
data-midi-action={`${midi}.play`}
disabled={!ready}
className={
'flex h-10 w-10 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 disabled:cursor-not-allowed disabled:opacity-40 ' +
@@ -107,6 +111,7 @@ export function DeckControls({ deck, stacked = false }: { deck: Deck; stacked?:
<Icon name={playing ? 'pause' : 'play'} size={16} />
</button>
<button
data-midi-action={`${midi}.cue`}
onPointerDown={(e) => {
e.preventDefault()
e.currentTarget.setPointerCapture(e.pointerId)
@@ -131,6 +136,7 @@ export function DeckControls({ deck, stacked = false }: { deck: Deck; stacked?:
)
const loopControls = (
<LoopControls
midi={midi}
mode={loopMode}
onMode={setLoopMode}
hasGrid={grid != null}
@@ -198,6 +204,7 @@ export function DeckControls({ deck, stacked = false }: { deck: Deck; stacked?:
/>
) : (
<HotcueBar
midi={midi}
cues={cueData?.cues ?? []}
slotCount={slotCount}
slotLabel={slotLabel}
@@ -36,6 +36,7 @@ export function DeckTempo({ deck, master, synced, syncBlocked, onSync, onMaster,
return (
<div className="flex h-9 shrink-0 items-center gap-2">
<button
data-midi-action={`deck.${deck.channel}.keylock`}
onClick={() => setKeylock(!keylock)}
disabled={!keylockAvailable}
aria-pressed={keylock}
@@ -51,6 +52,7 @@ export function DeckTempo({ deck, master, synced, syncBlocked, onSync, onMaster,
KEY
</button>
<button
data-midi-action={`deck.${deck.channel}.sync`}
onClick={onSync}
disabled={!track || (!synced && syncBlocked != null)}
aria-pressed={synced}
@@ -60,6 +62,7 @@ export function DeckTempo({ deck, master, synced, syncBlocked, onSync, onMaster,
SYNC
</button>
<button
data-midi-action={`deck.${deck.channel}.master`}
onClick={onMaster}
disabled={!track}
aria-pressed={master}
@@ -79,6 +82,7 @@ export function DeckTempo({ deck, master, synced, syncBlocked, onSync, onMaster,
}}
/>
<Fader
midi={`deck.${deck.channel}.pitch`}
orientation="horizontal"
value={pitch}
min={-1}
@@ -5,6 +5,7 @@ import { Icon } from '../../lib/icons'
export function PerformanceButton({ on, onToggle }: { on: boolean; onToggle: () => void }) {
return (
<button
data-midi-action="app.performance"
onClick={onToggle}
aria-pressed={on}
aria-label="Performance mode"
+143 -6
View File
@@ -48,6 +48,17 @@ import { LOOP_SIZES, type LoopMode } from '../LoopControls'
import type { StemLane } from '../MainWaveform'
import { usePrefsWriter } from '../../lib/prefs'
/** A controller's jog (lib/midi), at sensitivity 1: seconds of track per
* tick — scratch and scrub (vinyl at 33⅓ is 1.8 s a turn, over a typical
* ~500 ticks) — and the nudge's bend per tick in a frame, its limit, and the
* frames without a tick before it springs back. */
const JOG_SEC_PER_TICK = 1.8 / 500
const JOG_NUDGE_PER_TICK = 0.004
const JOG_NUDGE_MAX = 0.1
const JOG_NUDGE_IDLE_FRAMES = 4
/** A paused deck's untouched jog scratches; this long without a tick lets go. */
const JOG_SCRATCH_IDLE_MS = 120
export interface DeckOptions {
/** The track loaded into this deck, if any. */
track: Track | null
@@ -603,18 +614,23 @@ export function useDeck({
scratchRafRef.current = requestAnimationFrame(tick)
}
const onScratchStart = () => {
/** Grab the platter. Later targets are RELATIVE to `from` (default: the
* engine's position), which is returned — so a caller measuring its moves
* from a slightly stale position cannot make the deck jump. */
const onScratchStart = (from?: number): number | null => {
const eng = playbackRef.current
if (!eng || !eng.ready) return
if (!eng || !eng.ready) return null
const ref = from ?? eng.getPosition()
if (engagedRef.current) {
eng.scratchRegrab() // re-grab while coasting
return
eng.scratchRegrab(ref) // re-grab while coasting
return ref
}
wasPlayingRef.current = eng.playing
if (eng.playing) setPlaying(false)
eng.scratchBegin(eng.getPosition())
eng.scratchBegin(ref)
engagedRef.current = true
runScratchRaf()
return ref
}
const onScratchMove = (t: number) => {
@@ -634,6 +650,122 @@ export function useDeck({
}
}
// ---- jog (MIDI controllers) ---------------------------------------------
// Touching the top SCRATCHES — the same engine path as dragging the
// waveform, the target sent straight to the worklet. A turn without touch
// NUDGES while playing (a momentary bend, as the phase meter's drag) and
// SCRATCHES while paused too — the platter grabbed on the first tick and let
// go `JOG_SCRATCH_IDLE_MS` after the last, so a jog without a touch sensor
// still cues by ear; `scrub` (Shift + jog) moves fast, playing or not.
// Nudge and scrub are gathered per frame so a jog's flood of messages costs
// one render a frame. How many ticks a turn sends differs per controller,
// so the scale is a starting point times the mapping's sensitivity.
const jogRef = useRef({
touching: false,
/** Scratching from an untouched turn on a paused deck (released when idle). */
turning: false,
turnTimer: 0,
target: 0,
nudge: 0,
scrub: 0,
raf: 0,
idle: 0,
bending: false,
})
const jogLatest = useRef({ seekManual, duration })
jogLatest.current = { seekManual, duration }
const flushJog = () => {
const j = jogRef.current
j.raf = 0
const eng = playbackRef.current
if (!eng) return
const { seekManual: seekTo, duration: dur } = jogLatest.current
if (j.scrub !== 0) {
seekTo(Math.max(0, Math.min(dur, eng.getPosition() + j.scrub)))
j.scrub = 0
}
if (j.nudge !== 0) {
setBend(1 + Math.max(-JOG_NUDGE_MAX, Math.min(JOG_NUDGE_MAX, j.nudge * JOG_NUDGE_PER_TICK)))
j.nudge = 0
j.idle = 0
j.bending = true
} else if (j.bending && ++j.idle >= JOG_NUDGE_IDLE_FRAMES) {
setBend(1)
j.bending = false
}
if (j.bending) j.raf = requestAnimationFrame(flushJog)
}
const scheduleJog = () => {
if (!jogRef.current.raf) jogRef.current.raf = requestAnimationFrame(flushJog)
}
useEffect(
() => () => {
cancelAnimationFrame(jogRef.current.raf)
clearTimeout(jogRef.current.turnTimer)
},
[],
)
/** Hand a turn-scratch over to a touch (or end it), without releasing it. */
const endTurn = () => {
const j = jogRef.current
clearTimeout(j.turnTimer)
j.turning = false
}
const jogTouch = (on: boolean) => {
const j = jogRef.current
const eng = playbackRef.current
if (on) {
if (!eng || !eng.ready || j.touching) return
endTurn()
const ref = onScratchStart()
if (ref == null) return
j.touching = true
j.target = ref
} else if (j.touching) {
j.touching = false
onScratchEnd(j.target)
}
}
/** A jog turn. Returns 'nudge' when it bent a playing deck (SYNC lets go). */
const jogTurn = (ticks: number, sensitivity: number): 'nudge' | null => {
const j = jogRef.current
const eng = playbackRef.current
if (!eng || !eng.ready) return null
if (j.touching && engagedRef.current) {
j.target = Math.max(0, Math.min(duration, j.target + ticks * JOG_SEC_PER_TICK * sensitivity))
eng.scratchTarget(j.target)
return null
}
if (eng.playing) {
j.nudge += ticks * sensitivity
scheduleJog()
return 'nudge'
}
// Paused (or coasting from a scratch): grab the platter and scratch.
if (!j.turning || !engagedRef.current) {
const ref = onScratchStart()
if (ref == null) return null
j.turning = true
j.target = ref
}
j.target = Math.max(0, Math.min(duration, j.target + ticks * JOG_SEC_PER_TICK * sensitivity))
eng.scratchTarget(j.target)
clearTimeout(j.turnTimer)
j.turnTimer = window.setTimeout(() => {
j.turning = false
// Let go as a touch release does (a deck that was playing plays on);
// nothing if something else ended the scratch meanwhile.
if (!j.touching && engagedRef.current) playbackRef.current?.scratchRelease(wasPlayingRef.current)
}, JOG_SCRATCH_IDLE_MS)
return null
}
const scrub = (ticks: number, sensitivity: number) => {
if (!playbackRef.current?.ready) return
jogRef.current.scrub += ticks * JOG_SEC_PER_TICK * sensitivity
scheduleJog()
}
// ---- loops ------------------------------------------------------------
// Snap a time to the nearest beat when Snap is on (needs a beatgrid).
const snapTime = (t: number) => (snap && grid ? grid.snapToBeat(t) : Math.max(0, t))
@@ -1216,7 +1348,8 @@ export function useDeck({
// A pitch BEND: a momentary push or drag on top of the fader (the phase
// meter's drag), 1 = none. Part of `rate`, so the readout and a follower see it.
const [bend, setBend] = useState(1)
const rate = tempoActive ? (1 + pitch * pitchRange) * bend : 1
// A jog nudge bends the prep deck too (its pitch fader does not apply there).
const rate = tempoActive ? (1 + pitch * pitchRange) * bend : bend
useEffect(() => {
playbackRef.current?.setRate(rate)
}, [rate, ready])
@@ -1376,6 +1509,7 @@ export function useDeck({
}
return {
channel,
caps,
track,
origin,
@@ -1493,6 +1627,9 @@ export function useDeck({
keylock,
setKeylock,
keylockAvailable,
jogTouch,
jogTurn,
scrub,
}
}
+8 -2
View File
@@ -23,6 +23,8 @@ interface KnobProps {
describe: (v: number) => string
color?: string
size?: number
/** Its MIDI action, for on-screen learning (lib/midi). */
midi?: string
}
/** A point on the knob's circle at angle `deg` (0 = straight up). */
@@ -40,6 +42,7 @@ function arc(r: number, from: number, to: number, c: number): string {
}
export function Knob({
midi,
value,
min,
max,
@@ -76,7 +79,7 @@ export function Knob({
onChange(clamp(value - (e.deltaY / (e.shiftKey ? 2000 : 400)) * range, min, max))
}
return (
<div className="flex flex-col items-center gap-0.5" title={describe(value)}>
<div className="flex flex-col items-center gap-0.5" title={describe(value)} data-midi-action={midi}>
<div
role="slider"
aria-label={label}
@@ -125,10 +128,12 @@ interface FaderProps {
label: string
describe: (v: number) => string
className?: string
/** Its MIDI action, for on-screen learning (lib/midi). */
midi?: string
}
/** A fader: grab anywhere on it and the cap follows the pointer. */
export function Fader({ value, min, max, defaultValue, onChange, orientation, label, describe, className = '' }: FaderProps) {
export function Fader({ value, min, max, defaultValue, onChange, orientation, label, describe, className = '', midi }: FaderProps) {
const vertical = orientation === 'vertical'
const t = (clamp(value, min, max) - min) / (max - min)
const set = (e: PointerEvent<HTMLDivElement>) => {
@@ -139,6 +144,7 @@ export function Fader({ value, min, max, defaultValue, onChange, orientation, la
return (
<div
role="slider"
data-midi-action={midi}
aria-label={label}
aria-orientation={orientation}
aria-valuemin={min}
+7 -1
View File
@@ -133,6 +133,7 @@ export function MixerPanel({
<div className="flex h-6 shrink-0 items-center justify-center gap-2 px-1">
<span className="font-mono text-[11px] font-semibold text-muted">A</span>
<Fader
midi="mixer.crossfader"
orientation="horizontal"
value={crossfader}
min={-1}
@@ -187,6 +188,7 @@ function Strip({
}
const eq = (band: 'high' | 'mid' | 'low', label: string, name: string) => (
<Knob
midi={`mixer.${ch}.${band}`}
value={s[band]}
min={-1}
max={1}
@@ -205,6 +207,7 @@ function Strip({
<div className={`flex items-center gap-2 self-center ${mirrored ? 'flex-row-reverse' : ''}`}>
<div className="grid grid-cols-2 gap-x-1.5 gap-y-1.5">
<Knob
midi={`mixer.${ch}.gain`}
value={s.trim}
min={-TRIM_RANGE_DB}
max={TRIM_RANGE_DB}
@@ -230,6 +233,7 @@ function Strip({
</div>
<div className="flex flex-col items-center gap-2" style={{ width: FILTER_KNOB }}>
<button
data-midi-action={`mixer.${ch}.fxNext`}
onClick={(e) => {
const r = e.currentTarget.getBoundingClientRect()
setFxMenu({ x: r.left, y: r.bottom + 4 })
@@ -241,6 +245,7 @@ function Strip({
<Icon name="chevronDown" size={9} />
</button>
<Knob
midi={`mixer.${ch}.filter`}
value={s.color}
min={-1}
max={1}
@@ -258,6 +263,7 @@ function Strip({
const fader = (
<div className="flex flex-col items-center gap-0.5">
<Fader
midi={`mixer.${ch}.fader`}
orientation="vertical"
value={s.fader}
min={0}
@@ -272,7 +278,7 @@ function Strip({
</div>
)
const meter = (
<div className="flex flex-col pb-3" title={`Channel ${ch} level (after its fader)`}>
<div className="flex flex-col pb-3" title={`Channel ${ch} level (after its fader and FX)`}>
<MeterBar fillRef={meterRef} />
</div>
)
+28
View File
@@ -324,3 +324,31 @@ option {
@media (prefers-reduced-motion: reduce) {
.ambient-wash { animation: none !important; }
}
/* ---- On-screen MIDI learning (MidiLearnOverlay.tsx) --------------------- */
/* Outlines, not borders or shadows: they sit outside the control and change
no layout, and the controls' own shadows (lit buttons) stay as they are. */
body.midi-learn [data-midi-action] {
outline: 1px dashed color-mix(in oklab, var(--color-accent) 70%, transparent);
outline-offset: 2px;
cursor: crosshair;
}
body.midi-learn [data-midi-action][data-midi-mapped] {
outline-style: solid;
}
body.midi-learn [data-midi-action][data-midi-armed] {
outline: 2px solid var(--color-accent);
outline-offset: 3px;
animation: midi-armed 0.9s ease-in-out infinite alternate;
}
body.midi-learn [data-midi-action][data-midi-learned] {
outline: 2px solid var(--color-mint);
outline-offset: 3px;
}
@keyframes midi-armed {
from { outline-color: var(--color-accent); }
to { outline-color: color-mix(in oklab, var(--color-accent) 30%, transparent); }
}
@media (prefers-reduced-motion: reduce) {
body.midi-learn [data-midi-action][data-midi-armed] { animation: none; }
}
+108
View File
@@ -203,6 +203,26 @@ describe('DeckCore scratch', () => {
expect(core.positionSec - before).toBeCloseTo((10 * QUANTUM) / SR, 6)
})
it('a re-grab that arrives after the coast settled grabs afresh (and echoes its id)', () => {
const core = new DeckCore(SR, null)
core.load(ramp(SR * 4))
core.scratchBegin(1, 7)
core.scratchTarget(1.1)
run(core, 50)
core.scratchRelease(false)
for (let b = 0; b < 3000 && core.scratching; b++) run(core, 1)
expect(core.scratching).toBe(false)
expect(core.scratchId).toBe(7)
// The caller has not heard scratchDone yet and thinks it is still coasting.
const p = core.positionSec
core.scratchRegrab(p, 8)
expect(core.scratching).toBe(true)
expect(core.scratchId).toBe(8)
core.scratchTarget(p + 0.2)
run(core, 200)
expect(core.positionSec).toBeGreaterThan(p + 0.15)
})
it('a release without resume settles paused', () => {
const core = new DeckCore(SR, null)
core.load(ramp(SR * 4))
@@ -216,6 +236,94 @@ describe('DeckCore scratch', () => {
})
})
describe('DeckCore scratch sound', () => {
const tone = (freq: number): DeckSource => {
const ch = sine(freq, 20)
return { stems: [[ch]], length: ch.length, sampleRate: SR }
}
/** Drag at `speed`, the hand's position arriving after each of `gaps`
* (blocks, cycled) — as a mouse or a jog delivers it, in steps. Returns
* the speed after every block and the output. */
function drag(core: DeckCore, speed: number, gaps: number[], blocks: number) {
const start = core.positionSec
const speeds: number[] = []
const out = new Float32Array(blocks * QUANTUM)
const l = new Float32Array(QUANTUM)
const r = new Float32Array(QUANTUM)
let next = gaps[0]
for (let b = 0, g = 0; b < blocks; b++) {
if (b === next) {
core.scratchTarget(start + (speed * b * QUANTUM) / SR)
next += gaps[++g % gaps.length]
}
core.render(l, r)
out.set(l, b * QUANTUM)
speeds.push(core.speed)
}
return { speeds, out }
}
const worst = (xs: number[], ref: number) => Math.max(...xs.map((x) => Math.abs(x - ref)))
const maxStep = (x: Float32Array) => {
let m = 0
for (let i = 1; i < x.length; i++) m = Math.max(m, Math.abs(x[i] - x[i - 1]))
return m
}
it('a steady hand moving in mouse-rate steps plays at a steady speed', () => {
const core = new DeckCore(SR, null)
core.load(tone(440))
core.scratchBegin(1)
const { speeds } = drag(core, 1, [6], 700) // a position every 17 ms
expect(worst(speeds.slice(200), 1)).toBeLessThan(0.03)
})
it('and in jittery bursts, as a busy main thread delivers a jog', () => {
const core = new DeckCore(SR, null)
core.load(tone(440))
core.scratchBegin(1)
const { speeds } = drag(core, 1, [1, 1, 4, 1, 7, 2, 1, 3, 5, 1], 700)
expect(worst(speeds.slice(200), 1)).toBeLessThan(0.1)
})
it('stopping the hand fades out — no click at rest', () => {
const core = new DeckCore(SR, null)
core.load(tone(440))
core.scratchBegin(1)
const moving = drag(core, 1, [6], 200)
const resting = run(core, 100)
// A 0.5 amplitude 440 Hz sine at 1x moves at most 0.031 a sample.
expect(maxStep(moving.out)).toBeLessThan(0.05)
expect(maxStep(resting)).toBeLessThan(0.05)
expect(Math.max(...resting.slice(-QUANTUM).map(Math.abs))).toBeLessThan(1e-3)
})
it('grabbing a playing deck neither jumps nor clicks, whatever position the caller had', () => {
const core = new DeckCore(SR, null)
core.load(tone(440))
core.play()
const before = run(core, 20)
const p = core.positionSec
core.scratchBegin(p + 0.04) // a stale main-thread estimate
core.scratchTarget(p + 0.04) // the hand has not moved
const after = run(core, 20)
expect(Math.abs(core.positionSec - p)).toBeLessThan(0.01)
const joined = new Float32Array(before.length + after.length)
joined.set(before)
joined.set(after, before.length)
expect(maxStep(joined)).toBeLessThan(0.05)
})
it('a fast scratch does not fold highs back down as noise', () => {
const core = new DeckCore(SR, null)
core.load(tone(15000))
core.scratchBegin(1)
const { out } = drag(core, 3, [1], 300) // 3x: 45 kHz, far past Nyquist
const tail = out.slice(150 * QUANTUM)
const rms = Math.sqrt(tail.reduce((a, x) => a + x * x, 0) / tail.length)
expect(rms).toBeLessThan(0.05) // the tone itself is 0.35 RMS
})
})
describe('DeckCore keylock', () => {
it('keeps the pitch while the tempo changes; plain varispeed does not', () => {
const tone = sine(440, 6)
+207 -34
View File
@@ -40,11 +40,33 @@ export type DeckEvent = 'ended' | 'scratchDone'
type Mode = 'stopped' | 'playing' | 'drag' | 'inertia'
type StretchState = 'off' | 'warming' | 'on'
// Scratch feel — the values the ScriptProcessor scratch engine was tuned with.
const GLIDE = 400 // samples: how tightly position chases the target while dragging
// Scratch. The hand's position arrives in STEPS (a mouse move, a jog message:
// 60 Hz to 1 kHz, bunched by the main thread), and chasing each step made the
// speed lurch at that rate — a buzzing, distorted scratch with a click each
// time it caught up. So the steps are first joined into a line, played a
// little BEHIND the newest (`delay`, adapted to how far apart they arrive), and
// the platter follows that line through a critically damped spring: its speed
// is continuous. Volume follows speed (no hard mute at rest), and above 1x the
// source is averaged over the span each output frame covers (anti-aliasing).
const RATE_CAP = 12 // max source samples per output frame (pitch ceiling)
const INERTIA_FRICTION = 0.9998 // per-frame easing toward the target velocity (~0.4 s)
const SETTLE_EPS = 0.02 // |velocity - target| below this = settled
/** The platter's spring (Hz): higher follows the hand tighter, lower smooths more. */
const SCRATCH_HZ = 45
/** Hand-line delay (s): at least a block or two, at most this. */
const HAND_DELAY_MIN = 0.006
const HAND_DELAY_MAX = 0.03
const HAND_DELAY_START = 0.012
/** Two hand positions further apart than this (s) = the hand paused. */
const HAND_PAUSE = 0.06
/** How fast the delay may change: 3% of playing time (inaudible). */
const HAND_DELAY_SLEW = 0.03
/** Speed (source samples per frame) at which a scratch is at full volume. */
const SCRATCH_FULL_SPEED = 0.05
/** The volume's follow time (s). */
const SCRATCH_ENV_TAU = 0.003
/** Hand positions kept (a 1 kHz jog over the longest delay is ~30). */
const HAND_POINTS = 256
/** Blocks of varispeed while the stretchers prime (~29 ms at 44.1 kHz). */
export const WARM_QUANTA = 10
@@ -84,10 +106,31 @@ export class DeckCore {
private gainBuf: Float32Array[] = []
// Scratch (source samples, and source samples per output frame).
private target = 0
private velocity = 0
private targetVelocity = 0
private resume = false
/** The caller's id for the current grab, echoed with its scratchDone. */
scratchId = 0
/** Output frames rendered so far: the hand positions' clock. */
private clock = 0
/** The hand's positions (clock frame, source sample), oldest first, a ring. */
private readonly handT = new Float64Array(HAND_POINTS)
private readonly handX = new Float64Array(HAND_POINTS)
private handHead = 0
private handLen = 0
/** Was the newest hand point sent (not a hold point added here)? */
private handLastReal = false
/** How far behind the clock the hand line is played (frames). */
private handDelay: number
/** Recent largest gap between hand positions (frames). */
private handGap = 0
/** The core's playhead minus the caller's position at the grab (samples):
* targets are relative, so a stale main-thread position cannot jump it. */
private handOffset = 0
/** Scratch volume, following speed. */
private env = 0
private readonly springW: number
private readonly envCoef: number
// Keylock.
private stretchers: Stretcher[] = []
@@ -119,6 +162,9 @@ export class DeckCore {
this.ctxRate = ctxRate
this.rb = rb
this.gainCoef = Math.exp(-1 / (GAIN_TAU * ctxRate))
this.springW = (2 * Math.PI * SCRATCH_HZ) / ctxRate
this.envCoef = 1 - Math.exp(-1 / (SCRATCH_ENV_TAU * ctxRate))
this.handDelay = HAND_DELAY_START * ctxRate
}
// ---- state -----------------------------------------------------------
@@ -238,24 +284,94 @@ export class DeckCore {
this.keylock = on
}
scratchBegin(sec: number): void {
/** Grab the platter. `sec` is where the CALLER thinks the playhead is: later
* targets move relative to it. Grabbing a playing deck starts from its own
* speed, so the stop is a quick brake rather than a click. */
scratchBegin(sec: number, id = this.scratchId + 1): void {
if (!this.len) return
this.scratchId = id
const p = sec * this.srcRate
if (this.mode === 'playing') {
this.velocity = this.step
this.env = 1
} else if (!this.scratching) {
this.velocity = 0
this.env = 0
}
// The caller's position is an estimate; trust our own unless far off.
if (Math.abs(p - this.pos) > 0.25 * this.srcRate || this.pos < 0) {
this.pos = Math.max(0, Math.min(p, this.len - 1))
}
this.mode = 'drag'
this.pos = Math.max(0, Math.min(sec * this.srcRate, this.len - 1))
this.target = this.pos
this.velocity = 0
this.sState = 'off'
this.grabHand(p)
}
/** Re-grab while the platter is still coasting: resume dragging from here. */
scratchRegrab(): void {
if (!this.scratching) return
/** Re-grab while the platter is still coasting: resume dragging from here.
* If the coast has already settled (its scratchDone still on its way to
* the caller), this is a fresh grab — ignoring it would leave the caller
* dragging a deck that no longer listens. */
scratchRegrab(sec?: number, id = this.scratchId + 1): void {
if (!this.len) return
if (!this.scratching) {
this.scratchBegin(sec ?? this.positionSec, id)
return
}
this.scratchId = id
this.mode = 'drag'
this.target = this.pos
this.grabHand(sec == null ? this.pos : sec * this.srcRate)
}
scratchTarget(sec: number): void {
this.target = Math.max(0, Math.min(this.len - 1, sec * this.srcRate))
if (!this.handLen) return
const x = Math.max(0, Math.min(this.len - 1, sec * this.srcRate + this.handOffset))
const now = this.clock
const last = (this.handHead + this.handLen - 1) % HAND_POINTS
const lt = this.handT[last]
// Several in one block: the newest wins (they share an arrival time).
if (now <= lt) {
this.handX[last] = x
return
}
const gap = now - lt
if (this.handLastReal && gap < HAND_PAUSE * this.ctxRate) this.handGap = Math.max(gap, this.handGap * 0.97)
// The line already reached the last point and is holding it: start the
// move from where it is now, so the step is spread over the delay.
if (lt < now - this.handDelay) this.pushHand(now - this.handDelay, this.handX[last])
this.pushHand(now, x)
this.handLastReal = true
}
private grabHand(callerPos: number): void {
this.handOffset = this.pos - callerPos
this.handHead = 0
this.handLen = 0
this.handGap = 0
this.pushHand(this.clock - this.handDelay, this.pos)
this.handLastReal = false
}
private pushHand(t: number, x: number): void {
if (this.handLen === HAND_POINTS) {
this.handHead = (this.handHead + 1) % HAND_POINTS
this.handLen--
}
const i = (this.handHead + this.handLen) % HAND_POINTS
this.handT[i] = t
this.handX[i] = x
this.handLen++
}
/** The hand line at clock frame `t` (points before it are dropped). */
private handAt(t: number): number {
while (this.handLen > 1 && this.handT[(this.handHead + 1) % HAND_POINTS] <= t) {
this.handHead = (this.handHead + 1) % HAND_POINTS
this.handLen--
}
const a = this.handHead
if (this.handLen < 2 || t <= this.handT[a]) return this.handX[a]
const b = (a + 1) % HAND_POINTS
return this.handX[a] + ((this.handX[b] - this.handX[a]) * (t - this.handT[a])) / (this.handT[b] - this.handT[a])
}
/** Release the platter: coast toward playing speed (resume) or a stop. The
@@ -279,6 +395,8 @@ export class DeckCore {
/** Render one block into `outL` / `outR` (QUANTUM frames). */
render(outL: Float32Array, outR: Float32Array): void {
const n = outL.length
const base = this.clock
this.clock += n
this.events.length = 0
if (!this.len || this.mode === 'stopped') {
outL.fill(0)
@@ -288,7 +406,7 @@ export class DeckCore {
}
this.advanceGains(n)
if (this.scratching) {
this.renderScratch(outL, outR, n)
this.renderScratch(outL, outR, n, base)
return
}
@@ -404,27 +522,13 @@ export class DeckCore {
}
}
private renderScratch(outL: Float32Array, outR: Float32Array, n: number): void {
private renderScratch(outL: Float32Array, outR: Float32Array, n: number, base: number): void {
const w = this.springW
const w2 = w * w
const sr = this.ctxRate
const wantDelay = Math.max(HAND_DELAY_MIN * sr, Math.min(HAND_DELAY_MAX * sr, this.handGap * 1.2 + QUANTUM))
for (let i = 0; i < n; i++) {
if (this.mode === 'drag') {
const diff = this.target - this.pos
if (Math.abs(diff) < 1) {
// Hand at rest on the platter: no movement, no sound.
this.velocity = 0
outL[i] = 0
outR[i] = 0
continue
}
let step = diff / GLIDE
if (step > RATE_CAP) step = RATE_CAP
else if (step < -RATE_CAP) step = -RATE_CAP
this.pos += step
this.velocity = this.velocity * 0.9 + step * 0.1 // smoothed, for release momentum
} else if (this.mode === 'inertia') {
this.velocity = this.targetVelocity + (this.velocity - this.targetVelocity) * INERTIA_FRICTION
this.pos += this.velocity
if (Math.abs(this.velocity - this.targetVelocity) < SETTLE_EPS) this.settle()
} else {
if (!this.scratching) {
// Settled mid-block: the rest of it plays (or stays silent) normally.
if (this.mode === 'playing') {
this.frame(this.pos, i, false, outL, outR)
@@ -435,6 +539,31 @@ export class DeckCore {
}
continue
}
// Read, then advance — as the playing path does, so a grab or a settle
// neither skips nor repeats a sample.
const speed = Math.abs(this.velocity)
this.env += ((speed >= SCRATCH_FULL_SPEED ? 1 : speed / SCRATCH_FULL_SPEED) - this.env) * this.envCoef
this.scratchFrame(this.pos, this.velocity, i, outL, outR)
outL[i] *= this.env
outR[i] *= this.env
if (this.mode === 'drag') {
const d = wantDelay - this.handDelay
this.handDelay += d > HAND_DELAY_SLEW ? HAND_DELAY_SLEW : d < -HAND_DELAY_SLEW ? -HAND_DELAY_SLEW : d
const target = this.handAt(base + i - this.handDelay)
// Critically damped spring (semi-implicit Euler: stable at this w).
let v = this.velocity + w2 * (target - this.pos) - 2 * w * this.velocity
if (v > RATE_CAP) v = RATE_CAP
else if (v < -RATE_CAP) v = -RATE_CAP
this.velocity = v
this.pos += v
} else {
this.velocity = this.targetVelocity + (this.velocity - this.targetVelocity) * INERTIA_FRICTION
if (!this.resume && Math.abs(this.velocity) < SETTLE_EPS) this.velocity = 0
this.pos += this.velocity
if (this.resume && Math.abs(this.velocity - this.targetVelocity) < SETTLE_EPS) this.settle()
// A paused release stops once it has faded out.
else if (!this.resume && this.velocity === 0 && this.env < 1e-3) this.settle()
}
// Clamp to the track; hitting an edge kills momentum.
if (this.pos < 0) {
this.pos = 0
@@ -445,10 +574,54 @@ export class DeckCore {
this.velocity = 0
if (this.mode === 'inertia') this.settle()
}
this.frame(this.pos, i, false, outL, outR)
}
}
/** Mix every stem at p for a platter moving v samples a frame: above 1x,
* the span it covered is averaged (blended in from 1x to 2x), so highs
* played past the Nyquist frequency do not fold back down as noise. */
private scratchFrame(p: number, v: number, i: number, outL: Float32Array, outR: Float32Array): void {
const av = Math.abs(v)
const box = av <= 1 ? 0 : av >= 2 ? 1 : av - 1
if (box === 0) {
this.frame(p, i, false, outL, outR)
return
}
const a = v > 0 ? p - v : p
const k = Math.ceil(av)
let l = 0
let r = 0
for (let s = 0; s < this.stems.length; s++) {
const g = this.gainBuf[s][i]
if (g < 1e-5) continue
const chs = this.stems[s]
const c0 = chs[0]
const c1 = chs.length > 1 ? chs[1] : null
const sl = this.span(c0, a, av, k)
const vl = box < 1 ? (1 - box) * this.read(c0, p, false) + box * sl : sl
l += vl * g
if (c1) {
const sr = this.span(c1, a, av, k)
r += (box < 1 ? (1 - box) * this.read(c1, p, false) + box * sr : sr) * g
} else r += vl * g
}
outL[i] = l
outR[i] = r
}
/** Mean of `ch` over [a, a + len] (trapezoid over k linear-read steps). */
private span(ch: Float32Array, a: number, len: number, k: number): number {
let sum = 0
for (let j = 0; j <= k; j++) {
const q = a + (len * j) / k
const qi = Math.floor(q)
const f = q - qi
const x = this.at(ch, qi, false) * (1 - f) + this.at(ch, qi + 1, false) * f
sum += j === 0 || j === k ? 0.5 * x : x
}
return sum / k
}
private settle(): void {
this.mode = this.resume ? 'playing' : 'stopped'
this.velocity = 0
+22 -6
View File
@@ -30,6 +30,8 @@ export class DeckEngine {
private _keylockAvailable = false
private onEnded: (() => void) | null = null
private onScratchDone: ((playing: boolean) => void) | null = null
/** The latest grab's id: a scratchDone for an earlier one is superseded. */
private scratchSeq = 0
/** The worklet module loads asynchronously, once per app. `destination` is
* where the deck plays into: its mixer channel. */
@@ -57,6 +59,20 @@ export class DeckEngine {
console.warn(msg.message)
return
}
if (msg.type === 'event' && msg.event === 'scratchDone') {
// NOT filtered by generation: a command sent while the coast settled (a
// pitch fader's trickle of rate changes) would drop it, leaving the deck
// "scratching" for good — every later grab a re-grab the audio thread
// ignores. Only a newer grab supersedes it.
if (msg.scratch !== this.scratchSeq) return
const current = msg.gen === this.gen
const playing = current ? msg.playing : this.m.playing
this.m = current
? { ...this.m, pos: msg.pos, time: this.ctx.currentTime, speed: playing ? this.rate : 0, playing, scratching: false }
: { ...this.m, scratching: false }
this.onScratchDone?.(playing)
return
}
if (msg.gen !== this.gen) return // a report from before the latest command
if (msg.type === 'state') {
this._keylockAvailable = msg.keylockAvailable
@@ -64,8 +80,7 @@ export class DeckEngine {
return
}
this.m = { ...this.m, pos: msg.pos, time: this.ctx.currentTime, speed: msg.playing ? this.rate : 0, playing: msg.playing, scratching: false }
if (msg.event === 'ended') this.onEnded?.()
else this.onScratchDone?.(msg.playing)
this.onEnded?.()
}
private send(cmd: DeckCommand, positional = true): void {
@@ -199,12 +214,13 @@ export class DeckEngine {
scratchBegin(sec: number): void {
resumeAudio()
this.m = { pos: sec, time: this.ctx.currentTime, speed: 0, playing: false, scratching: true }
this.send({ op: 'scratchBegin', sec })
this.send({ op: 'scratchBegin', sec, id: ++this.scratchSeq })
}
/** Re-grab while the platter is still coasting. */
scratchRegrab(): void {
this.send({ op: 'scratchRegrab' }, false)
/** Re-grab while the platter is still coasting; later targets move
* relative to `sec`. */
scratchRegrab(sec: number): void {
this.send({ op: 'scratchRegrab', sec, id: ++this.scratchSeq }, false)
}
scratchTarget(sec: number): void {
@@ -29,8 +29,8 @@ export type DeckCommand =
| { op: 'rate'; rate: number }
| { op: 'keylock'; on: boolean }
| { op: 'leadIn'; on: boolean }
| { op: 'scratchBegin'; sec: number }
| { op: 'scratchRegrab' }
| { op: 'scratchBegin'; sec: number; id: number }
| { op: 'scratchRegrab'; sec: number; id: number }
| { op: 'scratchTarget'; sec: number }
| { op: 'scratchRelease'; resume: boolean }
@@ -54,7 +54,15 @@ export interface DeckReport {
export type DeckOutbound =
| DeckReport
| { type: 'event'; event: 'ended' | 'scratchDone'; gen: number; pos: number; playing: boolean }
| {
type: 'event'
event: 'ended' | 'scratchDone'
gen: number
/** The grab (`scratchBegin` / `scratchRegrab` id) a scratchDone ends. */
scratch: number
pos: number
playing: boolean
}
| { type: 'error'; message: string }
class DeckProcessor extends AudioWorkletProcessor {
@@ -113,9 +121,9 @@ class DeckProcessor extends AudioWorkletProcessor {
case 'leadIn':
return core.setLeadIn(c.on)
case 'scratchBegin':
return core.scratchBegin(c.sec)
return core.scratchBegin(c.sec, c.id)
case 'scratchRegrab':
return core.scratchRegrab()
return core.scratchRegrab(c.sec, c.id)
case 'scratchTarget':
return core.scratchTarget(c.sec)
case 'scratchRelease':
@@ -148,6 +156,7 @@ class DeckProcessor extends AudioWorkletProcessor {
type: 'event',
event,
gen: this.gen,
scratch: this.core.scratchId,
pos: this.core.positionSec,
playing: this.core.playing,
})
+10 -7
View File
@@ -1,8 +1,11 @@
// The mixer's audio graph (performance mode, decided 2026-11-02). Both decks
// play into it; it follows the controls in `mixerState.ts`.
//
// deck → gain → 3-band isolator → filter FX → fader ─┬→ crossfader → bus
// deck → gain → 3-band isolator → fader → filter FX ─┬→ crossfader → bus
// └→ meter
//
// The filter FX is POST-fader, so pulling the fader down stops feeding the
// reverb / delay and their tails ring out instead of being cut with it.
// bus → limiter → master meter → speakers
//
// GAIN (`trim` in the state) starts at the track's own auto gain (the DJ app's, `Track.auto_gain_db`;
@@ -329,16 +332,16 @@ class Strip {
mlB.connect(this.bands[1]).connect(eqOut)
mhB.connect(this.bands[2]).connect(eqOut)
this.fx = new FilterFx(ctx)
eqOut.connect(this.fx.input)
this.fader = ctx.createGain()
this.fx.output.connect(this.fader)
eqOut.connect(this.fader)
this.fx = new FilterFx(ctx)
this.fader.connect(this.fx.input)
this.meter = ctx.createAnalyser()
this.meter.fftSize = 512
this.fader.connect(this.meter)
this.fx.output.connect(this.meter)
this.xfade = ctx.createGain()
this.wetGate = ctx.createGain()
this.fader.connect(this.xfade).connect(this.wetGate).connect(bus)
this.fx.output.connect(this.xfade).connect(this.wetGate).connect(bus)
this.dryGate = ctx.createGain()
this.input.connect(this.dryGate).connect(bus)
}
@@ -362,7 +365,7 @@ class Strip {
}
export interface MixerLevels {
/** Peak dBFS: each channel after its fader, and the master after the limiter. */
/** Peak dBFS: each channel after its fader and FX, and the master after the limiter. */
A: number
B: number
master: number
+129
View File
@@ -0,0 +1,129 @@
// Everything a controller can be mapped to. Buttons do what the deck keys do
// (lib/deckKeys.ts), so a key and a pad mean the same thing; the rest are the
// controls a keyboard has no equivalent for — pitch, jog, the mixer, browsing.
//
// Kinds: `button` acts on press; `hold` also on release (CUE and hotcue
// previews, jog touch); `continuous` takes a position (or relative ticks from
// an endless knob); `jog` takes ticks.
export type DeckId = 'A' | 'B'
export type ActionKind = 'button' | 'hold' | 'continuous' | 'jog'
export type ActionGroup = 'Deck A' | 'Deck B' | 'Mixer' | 'Library' | 'App'
export interface ActionDef {
id: string
label: string
group: ActionGroup
kind: ActionKind
}
/** Hotcue pads offered per deck (a platform's bank may be smaller: the deck ignores the rest). */
export const HOTCUE_ACTIONS = 8
export const STEM_ACTIONS = 4
function deckActions(d: DeckId): ActionDef[] {
const group: ActionGroup = `Deck ${d}`
const a = (id: string, label: string, kind: ActionKind = 'button'): ActionDef => ({
id: `deck.${d}.${id}`,
label,
group,
kind,
})
const range = (n: number) => Array.from({ length: n }, (_, i) => i + 1)
return [
a('play', 'Play / pause'),
a('cue', 'CUE', 'hold'),
a('sync', 'SYNC'),
a('master', 'Tempo MASTER'),
a('keylock', 'Keylock'),
a('pitch', 'Pitch fader', 'continuous'),
a('jog', 'Jog wheel', 'jog'),
a('jogTouch', 'Jog touch (scratch)', 'hold'),
a('scrub', 'Fast scrub', 'jog'),
...range(HOTCUE_ACTIONS).map((n) => a(`hotcue.${n}`, `Hotcue ${n}`, 'hold')),
...range(HOTCUE_ACTIONS).map((n) => a(`hotcueErase.${n}`, `Erase hotcue ${n}`)),
a('jumpBack', 'Beat jump / move loop back'),
a('jumpFwd', 'Beat jump / move loop forward'),
a('markerPrev', 'Previous grid marker'),
a('markerNext', 'Next grid marker'),
a('sizeDown', 'Loop / jump size −'),
a('sizeUp', 'Loop / jump size +'),
a('sizeLoop', 'Loop (at size)'),
a('loopIn', 'Loop in'),
a('loopOut', 'Loop out'),
a('loopToggle', 'Loop on / off'),
...range(STEM_ACTIONS).map((n) => a(`stem.${n}`, `Mute stem ${n}`)),
...range(STEM_ACTIONS).map((n) => a(`stemSolo.${n}`, `Solo stem ${n}`)),
a('load', 'Load selected track'),
]
}
function channelActions(c: DeckId): ActionDef[] {
const a = (id: string, label: string, kind: ActionKind = 'continuous'): ActionDef => ({
id: `mixer.${c}.${id}`,
label: `${c}: ${label}`,
group: 'Mixer',
kind,
})
return [
a('gain', 'Gain'),
a('high', 'EQ high'),
a('mid', 'EQ mid'),
a('low', 'EQ low'),
a('filter', 'Filter'),
a('fxNext', 'Next effect', 'button'),
a('fxPrev', 'Previous effect', 'button'),
a('fader', 'Channel fader'),
]
}
export const ACTIONS: ActionDef[] = [
...deckActions('A'),
...deckActions('B'),
...channelActions('A'),
...channelActions('B'),
{ id: 'mixer.crossfader', label: 'Crossfader', group: 'Mixer', kind: 'continuous' },
{ id: 'library.browse', label: 'Browse tracks', group: 'Library', kind: 'jog' },
{ id: 'library.browsePress', label: 'Load to focused deck', group: 'Library', kind: 'button' },
{ id: 'library.tree', label: 'Browse playlists', group: 'Library', kind: 'jog' },
{ id: 'library.treePress', label: 'Open / close folder', group: 'Library', kind: 'button' },
{ id: 'app.performance', label: 'Performance mode on / off', group: 'App', kind: 'button' },
]
export const ACTION_GROUPS: ActionGroup[] = ['Deck A', 'Deck B', 'Mixer', 'Library', 'App']
const BY_ID = new Map(ACTIONS.map((a) => [a.id, a]))
export const actionDef = (id: string): ActionDef | undefined => BY_ID.get(id)
/**
* What a control does under Shift when nothing else is chosen: the keyboard's
* Shift meaning (hotcue -> erase it, stem -> solo it, beat jump -> step
* markers), plus Shift+jog = fast scrub and Shift+browse = the playlist tree
* (decided 2026-11-03). Filled in when the control is learned; overridable.
*/
export function shiftDefault(id: string): string | null {
const m = id.match(/^deck\.([AB])\.(.+)$/)
if (m) {
const [, d, rest] = m
const swap: Record<string, string> = { jumpBack: 'markerPrev', jumpFwd: 'markerNext', jog: 'scrub' }
if (swap[rest]) return `deck.${d}.${swap[rest]}`
const n = rest.match(/^(hotcue|stem)\.(\d+)$/)
if (n) return `deck.${d}.${n[1] === 'hotcue' ? 'hotcueErase' : 'stemSolo'}.${n[2]}`
return null
}
if (id === 'library.browse') return 'library.tree'
if (id === 'library.browsePress') return 'library.treePress'
return null
}
/** The deck an action belongs to, if any (mixer channels count as their deck). */
export function actionDeck(id: string): DeckId | null {
const m = id.match(/^(?:deck|mixer)\.([AB])\./)
return m ? (m[1] as DeckId) : null
}
/** Acts only in performance mode: deck B and the whole mixer (prep mode has
* one deck and plays past the mixer). */
export function performanceOnly(id: string): boolean {
return id.startsWith('mixer.') || actionDeck(id) === 'B'
}
+106
View File
@@ -0,0 +1,106 @@
import { describe, expect, it } from 'vitest'
import { absValue, Decoder, detectEncoding, relativeTicks, wrapDelta } from './encoding'
import { describeSource, parseMessage, parseSource, sourceKey, type MidiMessage } from './messages'
const cc = (number: number, value: number, channel = 1): MidiMessage => ({ kind: 'cc', channel, number, value })
const note = (number: number, value: number, channel = 1): MidiMessage => ({ kind: 'note', channel, number, value })
describe('messages', () => {
it('parses notes, CCs and pitch bend, and ignores the rest', () => {
expect(parseMessage([0x91, 11, 127])).toEqual({ kind: 'note', channel: 2, number: 11, value: 127 })
expect(parseMessage([0x81, 11, 64])).toEqual({ kind: 'note', channel: 2, number: 11, value: 0 })
expect(parseMessage([0x90, 11, 0])?.value).toBe(0)
expect(parseMessage([0xb0, 33, 65])).toEqual({ kind: 'cc', channel: 1, number: 33, value: 65 })
expect(parseMessage([0xe3, 0x7f, 0x7f])).toEqual({ kind: 'pb', channel: 4, number: 0, value: 16383 })
expect(parseMessage([0xc0, 5])).toBeNull()
expect(parseMessage([0xf8])).toBeNull()
})
it('names sources and reads them back', () => {
expect(sourceKey(cc(33, 1, 2))).toBe('cc:2:33')
expect(sourceKey({ kind: 'pb', channel: 1, number: 0 })).toBe('pb:1')
expect(parseSource('note:16:127')).toEqual({ kind: 'note', channel: 16, number: 127 })
expect(parseSource('cc:17:1')).toBeNull()
expect(describeSource('cc:2:33')).toBe('CC 33 · Ch 2')
expect(describeSource('cc:1:20+')).toBe('CC 20 · Ch 1 ↻')
expect(parseSource('cc:1:20-')).toEqual({ kind: 'cc', channel: 1, number: 20 })
expect(parseSource('note:1:20+')).toBeNull() // only a control that turns has a direction
})
})
describe('decoding', () => {
it('reads the three relative schemes', () => {
expect([1, 3, 127, 125].map((v) => relativeTicks('relTwos', v))).toEqual([1, 3, -1, -3])
expect([65, 67, 63, 61].map((v) => relativeTicks('rel64', v))).toEqual([1, 3, -1, -3])
expect([1, 3, 65, 67].map((v) => relativeTicks('relSignMag', v))).toEqual([1, 3, -1, -3])
})
it('maps a knob centre to exactly 0 and its ends to ±1', () => {
expect(absValue(64, 127).bipolar).toBe(0)
expect(absValue(0, 127).bipolar).toBe(-1)
expect(absValue(127, 127).bipolar).toBe(1)
expect(absValue(8192, 16383).bipolar).toBe(0)
expect(absValue(127, 127).unit).toBe(1)
})
it('steps the short way round a wheel', () => {
expect(wrapDelta(120, 3, 128)).toBe(11)
expect(wrapDelta(3, 120, 128)).toBe(-11)
expect(wrapDelta(16380, 4, 16384)).toBe(8)
})
it('turns an absolute jog position into ticks across the wrap, both ways', () => {
const d = new Decoder('jogAbs7')
expect(d.feed(cc(16, 125))).toBeNull() // the first position only sets where we are
expect(d.feed(cc(16, 127))).toEqual({ type: 'delta', ticks: 2 })
expect(d.feed(cc(16, 2))).toEqual({ type: 'delta', ticks: 3 })
expect(d.feed(cc(16, 126))).toEqual({ type: 'delta', ticks: -4 })
})
it('combines a 14-bit MSB/LSB pair, and pitch bend', () => {
const d = new Decoder('abs14')
d.feed(cc(0, 64))
const v = d.feed(cc(32, 0), true)
expect(v).toEqual({ type: 'abs', unit: 8192 / 16383, bipolar: 0 })
const j = new Decoder('jogAbs14')
expect(j.feed({ kind: 'pb', channel: 1, number: 0, value: 16380 })).toBeNull()
expect(j.feed({ kind: 'pb', channel: 1, number: 0, value: 5 })).toEqual({ type: 'delta', ticks: 9 })
})
it('inverts positions and ticks', () => {
expect(new Decoder('abs7', true).feed(cc(1, 0))).toEqual({ type: 'abs', unit: 1, bipolar: 1 })
expect(new Decoder('rel64', true).feed(cc(1, 66))).toEqual({ type: 'delta', ticks: -2 })
})
it('treats any value above 0 as a press', () => {
const b = new Decoder('button')
expect(b.feed(note(1, 1))).toEqual({ type: 'press', down: true })
expect(b.feed(cc(1, 0))).toEqual({ type: 'press', down: false })
})
})
describe('detecting an encoding while learning', () => {
const seq = (vals: number[], n = 20) => vals.map((v) => cc(n, v))
it('a fader swept up and back is absolute', () => {
expect(detectEncoding(seq([10, 14, 19, 25, 33, 40, 48, 41, 30, 22, 15, 9]), 'continuous')).toBe('abs7')
})
it('a knob moved a little near its centre, changing every message, is absolute', () => {
expect(detectEncoding(seq([60, 61, 62, 63, 64, 65, 66, 67, 68, 67, 66, 65]), 'continuous')).toBe('abs7')
})
it('a jog reporting its position (wrapping) is an absolute jog', () => {
expect(detectEncoding(seq([100, 108, 116, 124, 4, 12, 20, 28, 36, 44, 52, 60]), 'jog')).toBe('jogAbs7')
})
it('centred-on-64 relative, both ways and one way', () => {
expect(detectEncoding(seq([65, 65, 66, 65, 63, 62, 63, 63]), 'jog')).toBe('rel64')
expect(detectEncoding(seq([65, 65, 65, 66, 65]), 'jog')).toBe('rel64')
})
it('a fast centred jog jittering with speed is still relative', () => {
expect(detectEncoding(seq([66, 70, 68, 73, 69, 72, 67, 71, 75, 70, 66, 69]), 'jog')).toBe('rel64')
})
it("two's complement and sign-magnitude", () => {
expect(detectEncoding(seq([1, 1, 2, 1, 127, 127, 126]), 'jog')).toBe('relTwos')
expect(detectEncoding(seq([1, 1, 2, 1, 65, 65, 66]), 'jog')).toBe('relSignMag')
})
it('a 14-bit pair, whichever half came first', () => {
const pair = [cc(39, 3), cc(7, 40), cc(39, 90), cc(7, 41), cc(39, 12), cc(7, 42)]
expect(detectEncoding([cc(7, 40), ...pair], 'continuous')).toBe('abs14')
expect(detectEncoding([{ kind: 'pb', channel: 1, number: 0, value: 9000 }], 'continuous')).toBe('abs14')
expect(detectEncoding([{ kind: 'pb', channel: 1, number: 0, value: 9000 }], 'jog')).toBe('jogAbs14')
})
it('a button is a button', () => {
expect(detectEncoding([note(1, 127)], 'button')).toBe('button')
})
})
+175
View File
@@ -0,0 +1,175 @@
// How a control encodes what it does, and turning its raw values into
// something an action can use: a press, a position, or a number of ticks.
//
// Controllers disagree on everything here, so a binding stores its encoding
// (detected while learning — `detectEncoding` — and overridable in the editor):
// button a note or CC: any value > 0 = down, 0 = up
// abs7 a knob / fader, 0-127
// abs14 a 14-bit knob / fader: CC n (MSB) + CC n+32 (LSB), or pitch bend
// relTwos relative, two's complement: 1.. = +1.., 127.. = -1..
// rel64 relative, centred on 64: 65.. = +1.., 63.. = -1..
// relSignMag relative, sign + magnitude: 1.. = +1.., 65.. = -1..
// jogAbs7 a jog reporting its ABSOLUTE position, 7 bits, wrapping
// jogAbs14 the same at 14 bits (MSB/LSB pair, or pitch bend)
import type { MidiMessage } from './messages'
export const ENCODINGS = ['button', 'abs7', 'abs14', 'relTwos', 'rel64', 'relSignMag', 'jogAbs7', 'jogAbs14'] as const
export type Encoding = (typeof ENCODINGS)[number]
export const ENCODING_LABELS: Record<Encoding, string> = {
button: 'Button',
abs7: 'Absolute',
abs14: 'Absolute 14-bit',
relTwos: 'Relative (01 / 7F)',
rel64: 'Relative (41 / 3F)',
relSignMag: 'Relative (01 / 41)',
jogAbs7: 'Jog position',
jogAbs14: 'Jog position 14-bit',
}
/** Whether a 14-bit encoding pairs this CC with CC number + 32. */
export const isFourteenBit = (e: Encoding) => e === 'abs14' || e === 'jogAbs14'
/** What one message means once decoded. */
export type Decoded =
| { type: 'press'; down: boolean }
/** `unit` 0..1; `bipolar` -1..1 with the control's centre detent exactly 0. */
| { type: 'abs'; unit: number; bipolar: number }
| { type: 'delta'; ticks: number }
/** Two's-complement / centred / sign-magnitude value -> signed ticks. */
export function relativeTicks(encoding: Encoding, v: number): number {
switch (encoding) {
case 'relTwos':
return v < 64 ? v : v - 128
case 'rel64':
return v - 64
case 'relSignMag':
return v < 64 ? v : -(v - 64)
default:
return 0
}
}
/** The shortest signed step from position `prev` to `next` on a wheel of
* `size` positions: 120 -> 3 on a 7-bit jog is +11, not -117. */
export function wrapDelta(prev: number, next: number, size: number): number {
let d = (next - prev) % size
if (d > size / 2) d -= size
if (d < -size / 2) d += size
return d
}
/** A position on 0..max -> unit and bipolar, the centre value (max+1)/2
* mapping to exactly 0 (64 of 0-127: a knob's detent reads flat). */
export function absValue(raw: number, max: number): { unit: number; bipolar: number } {
const c = (max + 1) / 2
return { unit: raw / max, bipolar: raw < c ? (raw - c) / c : (raw - c) / (max - c) }
}
/**
* Decodes one control's messages. Keeps the state an encoding needs between
* them: the other half of a 14-bit pair, and an absolute jog's last position.
* One per bound source (the router keys them by port + source).
*/
export class Decoder {
private msb = 0
private lsb = 0
private lastPos: number | null = null
readonly encoding: Encoding
readonly invert: boolean
constructor(encoding: Encoding, invert = false) {
this.encoding = encoding
this.invert = invert
}
/** `isLsb`: the message is the CC n+32 half of a 14-bit pair. */
feed(m: MidiMessage, isLsb = false): Decoded | null {
const e = this.encoding
const flip = this.invert ? -1 : 1
if (e === 'button') return { type: 'press', down: m.value > 0 }
if (e === 'abs7') {
const v = absValue(m.value, 127)
return this.invert ? { unit: 1 - v.unit, bipolar: -v.bipolar, type: 'abs' } : { type: 'abs', ...v }
}
if (e === 'abs14' || e === 'jogAbs14') {
let pos: number
if (m.kind === 'pb') pos = m.value
else {
if (isLsb) this.lsb = m.value
else this.msb = m.value
pos = (this.msb << 7) | this.lsb
}
if (e === 'abs14') {
const v = absValue(pos, 16383)
return this.invert ? { unit: 1 - v.unit, bipolar: -v.bipolar, type: 'abs' } : { type: 'abs', ...v }
}
return this.jog(pos, 16384, flip)
}
if (e === 'jogAbs7') return this.jog(m.value, 128, flip)
const ticks = relativeTicks(e, m.value) * flip
return ticks === 0 ? null : { type: 'delta', ticks }
}
private jog(pos: number, size: number, flip: number): Decoded | null {
const prev = this.lastPos
this.lastPos = pos
if (prev == null) return null // the first position only sets where we are
const ticks = wrapDelta(prev, pos, size) * flip
return ticks === 0 ? null : { type: 'delta', ticks }
}
}
/** What the action being learned expects, which narrows the guess. */
export type LearnKind = 'button' | 'continuous' | 'jog'
/**
* Guess a control's encoding from the messages it sent while being learned
* (the user was asked to move it both ways). The tells:
* - Pitch bend, or CC n with CC n+32 interleaved, is 14-bit.
* - A relative control REPEATS values (65 65 65 while turning steadily) and
* stays in its zones (near 0 / 127, or near 64); an absolute one changes on
* every message and wanders across its range.
* - Which relative scheme: 63s mean centred on 64; 127s mean two's
* complement; 1s with 65s mean sign-magnitude; one direction only is
* ambiguous between schemes and falls back to the common one.
* Wrong guesses are rare and fixable in the editor.
*/
export function detectEncoding(samples: MidiMessage[], kind: LearnKind): Encoding {
if (kind === 'button' || samples.length === 0) return 'button'
const absolute = kind === 'jog' ? 'jogAbs' : 'abs'
const first = samples[0]
if (first.kind === 'pb') return `${absolute}14` as Encoding
if (first.kind === 'cc' && first.number < 32 && samples.some((m) => m.kind === 'cc' && m.number === first.number + 32)) {
return `${absolute}14` as Encoding
}
const vals = samples.filter((m) => m.kind === first.kind && m.number === first.number).map((m) => m.value)
let repeats = 0
for (let i = 1; i < vals.length; i++) if (vals[i] === vals[i - 1]) repeats++
const inZones = vals.every((v) => v <= 16 || v >= 112 || (v >= 48 && v <= 80))
const distinct = new Set(vals).size
// An absolute control moved both ways turns back once or twice; a relative
// one at varying speed jitters up and down all the time.
let reversals = 0
let lastSign = 0
for (let i = 1; i < vals.length; i++) {
const d = Math.sign(wrapDelta(vals[i - 1], vals[i], 128))
if (d === 0) continue
if (lastSign !== 0 && d !== lastSign) reversals++
lastSign = d
}
const relative = repeats >= 2 || (inZones && (distinct <= 6 || reversals > 2))
if (!relative) return `${absolute}7` as Encoding
const has = (lo: number, hi: number) => vals.some((v) => v >= lo && v <= hi)
if (has(48, 63)) return 'rel64'
if (has(112, 127)) return 'relTwos'
if (has(1, 16) && has(65, 80)) return 'relSignMag'
if (has(65, 80)) return 'rel64'
return 'relTwos'
}
+97
View File
@@ -0,0 +1,97 @@
import { describe, expect, it } from 'vitest'
import { ACTIONS, shiftDefault } from './actions'
import { bind, bindShift, emptyMapping, resolveBinding, sanitizeMapping, setBinding, sourcesFor, unbind } from './mapping'
describe('actions', () => {
it('have unique ids', () => {
expect(new Set(ACTIONS.map((a) => a.id)).size).toBe(ACTIONS.length)
})
it("default Shift layer = the keyboard's Shift meaning", () => {
expect(shiftDefault('deck.A.hotcue.3')).toBe('deck.A.hotcueErase.3')
expect(shiftDefault('deck.B.stem.2')).toBe('deck.B.stemSolo.2')
expect(shiftDefault('deck.A.jumpFwd')).toBe('deck.A.markerNext')
expect(shiftDefault('deck.B.jog')).toBe('deck.B.scrub')
expect(shiftDefault('library.browse')).toBe('library.tree')
expect(shiftDefault('deck.A.play')).toBeNull()
for (const a of ACTIONS) {
const d = shiftDefault(a.id)
if (d) expect(ACTIONS.some((x) => x.id === d)).toBe(true)
}
})
})
describe('mapping', () => {
it('learning fills the Shift layer with the default, and replaces the old control', () => {
let m = bind(emptyMapping(), 'note:1:0', 'button', 'normal', 'deck.A.hotcue.1')
expect(m.bindings['note:1:0']).toEqual({ encoding: 'button', normal: 'deck.A.hotcue.1', shift: 'deck.A.hotcueErase.1' })
m = bind(m, 'note:1:8', 'button', 'normal', 'deck.A.hotcue.1')
expect(sourcesFor(m, 'deck.A.hotcue.1', 'normal')).toEqual(['note:1:8'])
// The old pad keeps its Shift action, and the new one does not duplicate it.
expect(m.bindings['note:1:0']).toEqual({ encoding: 'button', shift: 'deck.A.hotcueErase.1' })
expect(m.bindings['note:1:8'].shift).toBeUndefined()
})
it('a free Shift layer: any action under Shift', () => {
let m = bind(emptyMapping(), 'note:1:11', 'button', 'normal', 'deck.A.play')
m = bind(m, 'note:1:11', 'button', 'shift', 'deck.A.sync')
expect(m.bindings['note:1:11']).toEqual({ encoding: 'button', normal: 'deck.A.play', shift: 'deck.A.sync' })
m = unbind(m, 'deck.A.play', 'normal')
expect(m.bindings['note:1:11']).toEqual({ encoding: 'button', shift: 'deck.A.sync' })
m = unbind(m, 'deck.A.sync', 'shift')
expect(m.bindings['note:1:11']).toBeUndefined()
})
it('the Shift control does nothing else', () => {
let m = bind(emptyMapping(), 'note:1:63', 'button', 'normal', 'deck.A.play')
m = bindShift(m, 'note:1:63')
expect(m.shifts).toEqual(['note:1:63', null])
expect(m.bindings['note:1:63']).toBeUndefined()
m = bind(m, 'note:1:63', 'button', 'normal', 'deck.A.cue')
expect(m.shifts).toEqual([null, null])
})
it('two Shift controls, each in its own slot', () => {
let m = bindShift(emptyMapping(), 'note:1:63')
m = bindShift(m, 'note:2:63', 1)
expect(m.shifts).toEqual(['note:1:63', 'note:2:63'])
// Learning one into the other slot moves it, never doubles it.
m = bindShift(m, 'note:1:63', 1)
expect(m.shifts).toEqual([null, 'note:1:63'])
m = bindShift(m, null, 1)
expect(m.shifts).toEqual([null, null])
})
it("reads the single-Shift form mappings had before", () => {
expect(sanitizeMapping({ version: 1, shift: 'note:1:63', bindings: {} })?.shifts).toEqual(['note:1:63', null])
expect(sanitizeMapping({ version: 1, shifts: ['note:1:63', 'note:1:63'] })?.shifts).toEqual(['note:1:63', null])
})
it('the LSB half of a 14-bit pair reaches its MSB', () => {
const m = bind(emptyMapping(), 'cc:1:0', 'abs14', 'normal', 'deck.A.pitch')
expect(resolveBinding(m, 'cc:1:32')).toMatchObject({ key: 'cc:1:0', isLsb: true })
const seven = bind(emptyMapping(), 'cc:1:0', 'abs7', 'normal', 'deck.A.pitch')
expect(resolveBinding(seven, 'cc:1:32')).toBeNull()
})
it("an encoder's two directions share its encoding", () => {
let m = bind(emptyMapping(), 'cc:1:20+', 'rel64', 'normal', 'deck.A.sizeUp')
m = bind(m, 'cc:1:20-', 'relTwos', 'normal', 'deck.A.sizeDown')
expect(m.bindings['cc:1:20+'].encoding).toBe('relTwos')
m = setBinding(m, 'cc:1:20+', { encoding: 'relSignMag' })
expect(m.bindings['cc:1:20-'].encoding).toBe('relSignMag')
expect(sanitizeMapping(m)?.bindings['cc:1:20-']).toEqual({ encoding: 'relSignMag', normal: 'deck.A.sizeDown' })
})
it('sanitises what prefs or a file hold', () => {
const m = sanitizeMapping({
version: 1,
shift: 'note:1:63',
jogSensitivity: 99,
bindings: {
'note:1:0': { encoding: 'button', normal: 'deck.A.play' },
'note:1:1': { encoding: 'bogus', normal: 'deck.A.play' },
'note:1:2': { encoding: 'button', normal: 'no.such.action' },
'nonsense': { encoding: 'button', normal: 'deck.A.play' },
},
})
expect(m?.shifts).toEqual(['note:1:63', null])
expect(m?.jogSensitivity).toBe(10)
expect(Object.keys(m!.bindings)).toEqual(['note:1:0'])
expect(sanitizeMapping({ version: 2 })).toBeNull()
expect(sanitizeMapping({ version: 1, jogSensitivity: 0.05 })?.jogSensitivity).toBe(0.05)
expect(sanitizeMapping({ version: 1, jogSensitivity: 0.01 })?.jogSensitivity).toBe(0.05)
})
})
+170
View File
@@ -0,0 +1,170 @@
// A controller's mapping: which physical control does what, in the normal
// and the Shift layer. Keyed by SOURCE (the control), so two buttons may share
// an action; the editor looks the other way, action -> sources. One mapping
// per controller, keyed by its port name, kept in userprefs (`midiMappings`)
// and exported / imported as a file.
import { actionDef, shiftDefault } from './actions'
import { ENCODINGS, isFourteenBit, type Encoding } from './encoding'
import { parseSource, splitSource, turnSource, type SourceKey } from './messages'
export type Layer = 'normal' | 'shift'
export interface Binding {
encoding: Encoding
invert?: boolean
normal?: string
shift?: string
}
export interface Mapping {
version: 1
/** The controls acting as Shift (learned controls), up to two — many
* controllers have one per deck. Either held = the Shift layer. Slot order
* is only the editor's; a mapping from before two were allowed had `shift`. */
shifts: [SourceKey | null, SourceKey | null]
bindings: Record<SourceKey, Binding>
/** Jog: scratch / nudge / scrub sensitivity (1 = the default feel). */
jogSensitivity: number
/** Fast scrub (Shift + jog) relative to an ordinary scrub. */
scrubSpeed: number
}
export type Mappings = Record<string, Mapping>
export const DEFAULT_JOG_SENSITIVITY = 1
export const DEFAULT_SCRUB_SPEED = 8
export function emptyMapping(): Mapping {
return { version: 1, shifts: [null, null], bindings: {}, jogSensitivity: DEFAULT_JOG_SENSITIVITY, scrubSpeed: DEFAULT_SCRUB_SPEED }
}
const num = (v: unknown, lo: number, hi: number, fallback: number) =>
typeof v === 'number' && isFinite(v) ? Math.min(hi, Math.max(lo, v)) : fallback
/** A mapping from prefs or a file, keeping only what is valid. */
export function sanitizeMapping(raw: unknown): Mapping | null {
if (!raw || typeof raw !== 'object') return null
const r = raw as Record<string, unknown>
if (r.version !== 1) return null
const out = emptyMapping()
const shift = (v: unknown) => (typeof v === 'string' && parseSource(v) ? v : null)
if (Array.isArray(r.shifts)) out.shifts = [shift(r.shifts[0]), shift(r.shifts[1])]
else out.shifts = [shift(r.shift), null] // the single-Shift form
if (out.shifts[0] && out.shifts[0] === out.shifts[1]) out.shifts[1] = null
out.jogSensitivity = num(r.jogSensitivity, 0.05, 10, DEFAULT_JOG_SENSITIVITY)
out.scrubSpeed = num(r.scrubSpeed, 1, 64, DEFAULT_SCRUB_SPEED)
const bindings = r.bindings && typeof r.bindings === 'object' ? (r.bindings as Record<string, unknown>) : {}
for (const [key, b] of Object.entries(bindings)) {
if (!parseSource(key) || !b || typeof b !== 'object') continue
const x = b as Record<string, unknown>
if (!ENCODINGS.includes(x.encoding as Encoding)) continue
const binding: Binding = { encoding: x.encoding as Encoding }
if (x.invert === true) binding.invert = true
if (typeof x.normal === 'string' && actionDef(x.normal)) binding.normal = x.normal
if (typeof x.shift === 'string' && actionDef(x.shift)) binding.shift = x.shift
if (binding.normal || binding.shift) out.bindings[key] = binding
}
return out
}
export function sanitizeMappings(raw: unknown): Mappings {
const out: Mappings = {}
if (!raw || typeof raw !== 'object') return out
for (const [port, m] of Object.entries(raw as Record<string, unknown>)) {
const clean = sanitizeMapping(m)
if (clean) out[port] = clean
}
return out
}
/** The sources bound to `action` in `layer`. */
export function sourcesFor(m: Mapping, action: string, layer: Layer): SourceKey[] {
return Object.entries(m.bindings)
.filter(([, b]) => b[layer] === action)
.map(([k]) => k)
}
/** Drop `action` from `layer` everywhere (and bindings left empty). */
export function unbind(m: Mapping, action: string, layer: Layer): Mapping {
const bindings: Record<SourceKey, Binding> = {}
for (const [k, b] of Object.entries(m.bindings)) {
const next = b[layer] === action ? { ...b, [layer]: undefined } : b
if (next.normal || next.shift) bindings[k] = next
}
return { ...m, bindings }
}
/**
* Learn: `source` now does `action` in `layer`. It REPLACES the action's
* previous control in that layer (learning means "this is the control for
* X"). Learning a control's normal action fills its Shift layer with the
* keyboard's Shift meaning when the Shift layer is empty. A control that was
* Shift stops being Shift.
*/
export function bind(m: Mapping, source: SourceKey, encoding: Encoding, layer: Layer, action: string): Mapping {
const cleared = unbind(m, action, layer)
const prev = cleared.bindings[source]
// A new encoding (another kind of control) leaves the other layer's action
// only if it still makes sense: same kind of encoding.
const sameKind = prev && (prev.encoding === 'button') === (encoding === 'button')
const next: Binding = { encoding, invert: prev?.invert, normal: sameKind ? prev?.normal : undefined, shift: sameKind ? prev?.shift : undefined }
next[layer] = action
if (layer === 'normal' && !next.shift) {
const d = shiftDefault(action)
if (d && sourcesFor(cleared, d, 'shift').length === 0) next.shift = d
}
if (!next.invert) delete next.invert
const bindings = { ...cleared.bindings, [source]: next }
// An encoder's two directions are one control, decoded once: they share
// its encoding.
const { base, dir } = splitSource(source)
const other = dir && bindings[turnSource(base, dir === '+' ? '-' : '+')]
if (dir && other) bindings[turnSource(base, dir === '+' ? '-' : '+')] = { ...other, encoding }
return { ...cleared, shifts: withoutShift(cleared.shifts, source), bindings }
}
const withoutShift = (s: Mapping['shifts'], source: SourceKey): Mapping['shifts'] => [
s[0] === source ? null : s[0],
s[1] === source ? null : s[1],
]
/** Whether `source` is one of the mapping's Shift controls. */
export const isShift = (m: Mapping, source: SourceKey) => m.shifts[0] === source || m.shifts[1] === source
/** Make `source` Shift control `slot` (it then does nothing else; it leaves
* the other slot if it was there). `null` clears the slot. */
export function bindShift(m: Mapping, source: SourceKey | null, slot: 0 | 1 = 0): Mapping {
const bindings = { ...m.bindings }
const shifts = source ? withoutShift(m.shifts, source) : ([...m.shifts] as Mapping['shifts'])
shifts[slot] = source
if (source) delete bindings[source]
return { ...m, shifts, bindings }
}
export function setBinding(m: Mapping, source: SourceKey, patch: Partial<Binding>): Mapping {
const b = m.bindings[source]
if (!b) return m
const bindings = { ...m.bindings, [source]: { ...b, ...patch } }
// A directional turn's encoding is its encoder's: both directions follow.
const { base, dir } = splitSource(source)
const otherKey = dir && turnSource(base, dir === '+' ? '-' : '+')
if (otherKey && bindings[otherKey] && patch.encoding) bindings[otherKey] = { ...bindings[otherKey], encoding: patch.encoding }
return { ...m, bindings }
}
/**
* The binding a message's source reaches: its own, or — for the LSB half of
* a 14-bit pair (CC n+32) — its MSB's. `isLsb` says which half it is.
*/
export function resolveBinding(m: Mapping, source: SourceKey): { key: SourceKey; binding: Binding; isLsb: boolean } | null {
const own = m.bindings[source]
if (own) return { key: source, binding: own, isLsb: false }
const s = parseSource(source)
if (s?.kind === 'cc' && s.number >= 32 && s.number < 64) {
const key = `cc:${s.channel}:${s.number - 32}`
const msb = m.bindings[key]
if (msb && isFourteenBit(msb.encoding)) return { key, binding: msb, isLsb: true }
}
return null
}
+80
View File
@@ -0,0 +1,80 @@
// MIDI messages as the mapping layer sees them: notes, control changes and
// pitch bend, each from a SOURCE — what one physical control sends on.
// Everything else a controller may send (aftertouch, program change) is
// ignored; system messages never leave the shell (src-tauri/src/midi.rs).
export type MidiKind = 'note' | 'cc' | 'pb'
export interface MidiMessage {
kind: MidiKind
/** 1-16, as controllers' manuals number them. */
channel: number
/** Note or controller number; 0 for pitch bend. */
number: number
/** 0-127; pitch bend 0-16383. A note-off (or note-on at velocity 0) is 0. */
value: number
}
/** One physical control: `note:1:11`, `cc:2:33`, `pb:1`. */
export type SourceKey = string
export function parseMessage(bytes: ArrayLike<number>): MidiMessage | null {
if (bytes.length < 2) return null
const type = bytes[0] & 0xf0
const channel = (bytes[0] & 0x0f) + 1
const d1 = bytes[1] & 0x7f
const d2 = bytes.length > 2 ? bytes[2] & 0x7f : 0
switch (type) {
case 0x80:
return { kind: 'note', channel, number: d1, value: 0 }
case 0x90:
return { kind: 'note', channel, number: d1, value: d2 }
case 0xb0:
return { kind: 'cc', channel, number: d1, value: d2 }
case 0xe0:
return { kind: 'pb', channel, number: 0, value: d1 | (d2 << 7) }
default:
return null
}
}
export function sourceKey(m: Pick<MidiMessage, 'kind' | 'channel' | 'number'>): SourceKey {
return m.kind === 'pb' ? `pb:${m.channel}` : `${m.kind}:${m.channel}:${m.number}`
}
/**
* An encoder's TURN in one direction, bound to a button action (decided
* 2026-11-03: controllers put beat jump and loop size on encoders): the
* source key plus `+` (clockwise / up) or `-`. Each tick fires the action once.
*/
export type TurnDirection = '+' | '-'
export const turnSource = (base: SourceKey, dir: TurnDirection): SourceKey => `${base}${dir}`
/** The physical control of a (possibly directional) source, and its direction. */
export function splitSource(key: SourceKey): { base: SourceKey; dir: TurnDirection | null } {
const last = key.at(-1)
return last === '+' || last === '-' ? { base: key.slice(0, -1), dir: last } : { base: key, dir: null }
}
export function parseSource(key: SourceKey): Pick<MidiMessage, 'kind' | 'channel' | 'number'> | null {
const { base, dir } = splitSource(key)
const [kind, ch, num] = base.split(':')
const channel = Number(ch)
if (!(channel >= 1 && channel <= 16)) return null
if (kind === 'pb') return dir ? null : { kind, channel, number: 0 }
const number = Number(num)
if ((kind !== 'note' && kind !== 'cc') || !(number >= 0 && number <= 127)) return null
// Only a control that turns has a direction.
if (dir && kind !== 'cc') return null
return { kind, channel, number }
}
/** "Note 11 · Ch 1", "CC 33 · Ch 2", "Pitch bend · Ch 1", "CC 20 · Ch 1 ↻". */
export function describeSource(key: SourceKey): string {
const s = parseSource(key)
if (!s) return key
const what = s.kind === 'pb' ? 'Pitch bend' : s.kind === 'note' ? `Note ${s.number}` : `CC ${s.number}`
const dir = splitSource(key).dir
return `${what} · Ch ${s.channel}${dir === '+' ? ' ↻' : dir === '-' ? ' ↺' : ''}`
}
+271
View File
@@ -0,0 +1,271 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { bind, bindShift, emptyMapping, type Mapping } from './mapping'
import { EMPTY_TARGETS, MidiRouter, type DeckMidi, type MidiTargets } from './router'
import { armLearn, getMidiState, replaceMappings } from './store'
import { getMixerState, setChannel, setMixer } from '../audio/mixerState'
const PORT = 'DDJ'
function fakeDeck(): DeckMidi & { calls: string[] } {
const calls: string[] = []
const log = (name: string) => (...args: unknown[]) => void calls.push([name, ...args].join(' '))
return {
calls,
slotCount: 8,
pitch: 0,
toggle: log('toggle'),
onCuePress: log('cuePress'),
onCueRelease: log('cueRelease'),
onSlotPress: log('slotPress'),
onSlotRelease: log('slotRelease'),
deleteHotcueSlot: log('deleteSlot'),
toggleStem: log('stem'),
moveOrJump: log('move'),
prevMarker: log('prevMarker'),
nextMarker: log('nextMarker'),
stepSize: log('stepSize'),
toggleSizeLoop: log('sizeLoop'),
loopIn: log('loopIn'),
loopOut: log('loopOut'),
toggleLoop: log('toggleLoop'),
toggleSync: log('sync'),
makeMaster: log('master'),
toggleKeylock: log('keylock'),
setPitch: log('pitch'),
jogTouch: log('jogTouch'),
jogTurn: log('jogTurn'),
scrub: log('scrub'),
}
}
let A: ReturnType<typeof fakeDeck>
let B: ReturnType<typeof fakeDeck>
let targets: MidiTargets
let router: MidiRouter
const note = (n: number, v: number) => router.receive(PORT, [0x90, n, v])
const cc = (n: number, v: number) => router.receive(PORT, [0xb0, n, v])
function map(fn: (m: Mapping) => Mapping) {
replaceMappings({ [PORT]: fn(emptyMapping()) }, false)
}
beforeEach(() => {
A = fakeDeck()
B = fakeDeck()
targets = { ...EMPTY_TARGETS, decks: { A, B }, load: vi.fn(), browse: vi.fn() }
router = new MidiRouter(() => targets)
armLearn(null)
setMixer({ crossfader: 0 })
setChannel('A', { fader: 1, trim: 0, color: 0, fx: 'filter' })
map((m) => {
m = bindShift(m, 'note:1:63')
m = bind(m, 'note:1:11', 'button', 'normal', 'deck.A.play')
m = bind(m, 'note:1:0', 'button', 'normal', 'deck.A.hotcue.1')
m = bind(m, 'note:2:11', 'button', 'normal', 'deck.B.play')
m = bind(m, 'cc:1:33', 'rel64', 'normal', 'deck.A.jog')
m = bind(m, 'note:1:54', 'button', 'normal', 'deck.A.jogTouch')
m = bind(m, 'cc:1:0', 'abs14', 'normal', 'deck.A.pitch')
m = bind(m, 'cc:7:19', 'abs7', 'normal', 'mixer.A.fader')
m = bind(m, 'cc:7:31', 'abs7', 'normal', 'mixer.crossfader')
m = bind(m, 'cc:7:64', 'rel64', 'normal', 'library.browse')
return m
})
})
describe('router', () => {
it('MASTER is a mappable button on each deck', () => {
map((m) => bind(m, 'note:2:20', 'button', 'normal', 'deck.B.master'))
router.receive(PORT, [0x91, 20, 127])
expect(B.calls).toEqual([]) // deck B: performance mode only
targets.performance = true
router.receive(PORT, [0x91, 20, 127])
expect(B.calls).toEqual(['master'])
})
it('runs a button on press only', () => {
note(11, 127)
note(11, 0)
expect(A.calls).toEqual(['toggle'])
})
it('Shift + pad erases the hotcue; the pad alone presses and releases it', () => {
note(0, 127)
note(0, 0)
note(63, 127)
note(0, 127)
note(63, 0)
expect(A.calls).toEqual(['slotPress 0', 'slotRelease 0', 'deleteSlot 0'])
})
it('a held pad releases where it was pressed, even if Shift changes between', () => {
note(0, 127)
note(63, 127)
note(0, 0)
expect(A.calls).toEqual(['slotPress 0', 'slotRelease 0'])
})
it('with two Shift buttons, either one held gives the Shift layer', () => {
map((m) => bindShift(bindShift(bind(m, 'note:1:0', 'button', 'normal', 'deck.A.hotcue.1'), 'note:1:63', 0), 'note:2:63', 1))
router.receive(PORT, [0x91, 63, 127]) // the second Shift (deck B's side)
note(0, 127)
note(63, 127) // both held…
router.receive(PORT, [0x91, 63, 0]) // …one let go: still shifted
note(0, 127)
note(63, 0)
note(0, 127)
expect(A.calls).toEqual(['deleteSlot 0', 'deleteSlot 0', 'slotPress 0'])
})
it('an unbound Shift layer falls back to the normal action', () => {
note(63, 127)
note(11, 127)
expect(A.calls).toEqual(['toggle'])
})
it('prep mode: deck B and the mixer do nothing', () => {
router.receive(PORT, [0x91, 11, 127]) // deck B's play, channel 2
router.receive(PORT, [0xb6, 19, 0]) // channel A's fader, channel 7
expect(B.calls).toEqual([])
expect(getMixerState().A.fader).toBe(1)
targets.performance = true
router.receive(PORT, [0x91, 11, 127])
router.receive(PORT, [0xb6, 19, 0])
expect(B.calls).toEqual(['toggle'])
expect(getMixerState().A.fader).toBe(0)
})
it('positions jump straight to the control (no takeover)', () => {
targets.performance = true
router.receive(PORT, [0xb6, 31, 127])
expect(getMixerState().crossfader).toBe(1)
router.receive(PORT, [0xb6, 31, 64])
expect(getMixerState().crossfader).toBe(0)
})
it('a 14-bit pitch fader: MSB then LSB', () => {
cc(0, 0)
cc(32, 0)
expect(A.calls.at(-1)).toBe('pitch -1')
cc(0, 64)
expect(A.calls.at(-1)).toBe('pitch 0')
})
it('jog ticks carry the mapping sensitivity; Shift + jog = fast scrub', () => {
cc(33, 66)
note(63, 127)
cc(33, 62)
expect(A.calls).toEqual(['jogTurn 2 1', 'scrub -2 8'])
})
it('jog touch is a hold', () => {
note(54, 127)
note(54, 0)
expect(A.calls).toEqual(['jogTouch true 1', 'jogTouch false 1'])
})
it('browse moves the track list; Shift + browse would move the tree', () => {
router.receive(PORT, [0xb6, 64, 63])
expect(targets.browse).toHaveBeenCalledWith(-1)
})
})
describe('learning', () => {
it('a button learns from its first press, into the Shift layer if Shift is held', () => {
armLearn({ action: 'deck.A.cue', layer: 'normal' })
note(12, 127)
expect(getMidiState().mappings[PORT].bindings['note:1:12']?.normal).toBe('deck.A.cue')
expect(getMidiState().armed).toBeNull()
armLearn({ action: 'deck.A.sync', layer: 'normal' })
note(63, 127)
note(12, 127)
expect(getMidiState().mappings[PORT].bindings['note:1:12']?.shift).toBe('deck.A.sync')
expect(A.calls).toEqual([]) // learning never acts
})
it('a continuous control learns its encoding from what it sent', () => {
armLearn({ action: 'mixer.B.fader', layer: 'normal' })
for (const v of [10, 20, 30, 40, 50, 60, 70, 80, 90, 80, 70, 60]) router.receive(PORT, [0xb1, 19, v])
expect(getMidiState().mappings[PORT].bindings['cc:2:19']).toEqual({ encoding: 'abs7', normal: 'mixer.B.fader' })
})
it('a jog ignores its touch note while learning, and finds it is relative', () => {
armLearn({ action: 'deck.B.jog', layer: 'normal' })
router.receive(PORT, [0x91, 54, 127])
for (const v of [65, 65, 66, 65, 65, 63, 63, 62, 63, 63, 65, 65]) router.receive(PORT, [0xb1, 34, v])
expect(getMidiState().mappings[PORT].bindings['cc:2:34']).toMatchObject({ encoding: 'rel64', normal: 'deck.B.jog', shift: 'deck.B.scrub' })
})
it('a 14-bit pitch fader learns on its MSB, whichever half arrives first', () => {
armLearn({ action: 'deck.B.pitch', layer: 'normal' })
for (let i = 0; i < 6; i++) {
router.receive(PORT, [0xb1, 32 + 5, (i * 37) % 128]) // LSB (CC 37)
router.receive(PORT, [0xb1, 5, 60 + i]) // MSB (CC 5)
}
const b = getMidiState().mappings[PORT].bindings
expect(b['cc:2:5']).toEqual({ encoding: 'abs14', normal: 'deck.B.pitch' })
expect(b['cc:2:37']).toBeUndefined()
// …and then drives the deck from both halves.
targets.performance = true
router.receive(PORT, [0xb1, 5, 127])
router.receive(PORT, [0xb1, 37, 127])
expect(B.calls.at(-1)).toBe('pitch 1')
})
it('a jog reporting its absolute position learns as one, and turns across the wrap', () => {
armLearn({ action: 'deck.A.jog', layer: 'normal' })
for (const v of [100, 108, 116, 124, 4, 12, 20, 28, 36, 44, 52, 60]) cc(40, v)
expect(getMidiState().mappings[PORT].bindings['cc:1:40']?.encoding).toBe('jogAbs7')
cc(40, 126)
cc(40, 3)
expect(A.calls).toEqual(['jogTurn 5 1'])
})
it('an encoder turned for button actions binds each direction, in either layer', async () => {
vi.useFakeTimers()
try {
const turn = (vals: number[]) => {
for (const v of vals) router.receive(PORT, [0xb0, 20, v])
vi.advanceTimersByTime(500)
}
armLearn({ action: 'deck.A.sizeUp', layer: 'normal' })
turn([65, 65, 65])
armLearn({ action: 'deck.A.sizeDown', layer: 'normal' })
turn([63, 63])
armLearn({ action: 'deck.A.jumpFwd', layer: 'normal' })
note(63, 127) // the controller's Shift held: the Shift layer
turn([65, 66])
note(63, 0)
const b = getMidiState().mappings[PORT].bindings
expect(b['cc:1:20+']).toMatchObject({ encoding: 'rel64', normal: 'deck.A.sizeUp', shift: 'deck.A.jumpFwd' })
expect(b['cc:1:20-']).toMatchObject({ encoding: 'rel64', normal: 'deck.A.sizeDown' })
expect(b['cc:1:20']).toBeUndefined()
cc(20, 65) // one click up
cc(20, 61) // three clicks down at once
note(63, 127)
cc(20, 65)
cc(20, 63) // Shift + down: no Shift action -> the normal one
expect(A.calls).toEqual(['stepSize 1', 'stepSize -1', 'stepSize -1', 'stepSize -1', 'move 1', 'stepSize -1'])
} finally {
vi.useRealTimers()
}
})
it("a CC button pressed (and released) while learning stays a button", () => {
vi.useFakeTimers()
try {
armLearn({ action: 'deck.A.loopToggle', layer: 'normal' })
cc(70, 127)
cc(70, 0)
vi.advanceTimersByTime(500)
armLearn({ action: 'deck.A.loopIn', layer: 'normal' })
cc(71, 127) // held past the window
vi.advanceTimersByTime(500)
const b = getMidiState().mappings[PORT].bindings
expect(b['cc:1:70']).toMatchObject({ encoding: 'button', normal: 'deck.A.loopToggle' })
expect(b['cc:1:71']).toMatchObject({ encoding: 'button', normal: 'deck.A.loopIn' })
} finally {
vi.useRealTimers()
}
})
it("a two's-complement encoder turned down (127s) is a turn, not a button", () => {
vi.useFakeTimers()
try {
armLearn({ action: 'deck.A.jumpBack', layer: 'normal' })
cc(72, 127)
cc(72, 127)
vi.advanceTimersByTime(500)
expect(getMidiState().mappings[PORT].bindings['cc:1:72-']).toMatchObject({ encoding: 'relTwos', normal: 'deck.A.jumpBack' })
} finally {
vi.useRealTimers()
}
})
it('the Shift control itself', () => {
armLearn({ action: 'shift', slot: 1 })
note(70, 127)
expect(getMidiState().mappings[PORT].shifts).toEqual(['note:1:63', 'note:1:70'])
})
})
+419
View File
@@ -0,0 +1,419 @@
// Every MIDI message from every controller comes through here: Shift is
// tracked, Learn gets first look, then the message is decoded through its
// binding and the action is run on whatever is mounted to take it (`targets`).
//
// Rules from the discussion (2026-11-03):
// - Shift is a learned control; each control has a free Shift binding, and
// an unbound one falls back to the control's normal action.
// - Prep mode has one deck: deck B and the mixer act only in performance mode.
// - The controller always wins: a position is applied as it arrives (no soft
// takeover), and moving pitch or nudging with the jog releases SYNC (the
// deck target does that, as the on-screen fader and phase meter do).
// - A held control's release reaches the action its press ran, even if
// Shift was let go in between (as useDeckKeys' `held`).
import { actionDef, actionDeck, performanceOnly, type ActionKind, type DeckId } from './actions'
import { Decoder, detectEncoding, type Decoded, type Encoding, type LearnKind } from './encoding'
import { bind, bindShift, isShift, resolveBinding, type Binding, type Layer, type Mapping } from './mapping'
import { parseMessage, sourceKey, splitSource, turnSource, type MidiMessage, type SourceKey } from './messages'
import { armLearn, getMidiState, patchMidi, updateMapping, type LearnTarget } from './store'
import type { Track } from '../../api'
import type { DeckShortcuts } from '../deckKeys'
import { FX_TYPES, getMixerState, setChannel, setMixer, type ChannelState } from '../audio/mixerState'
import { TRIM_RANGE_DB } from '../audio/mixerMath'
/** What a deck offers a controller: its keys, plus what keys cannot do. */
export interface DeckMidi extends DeckShortcuts {
toggleSizeLoop(): void
loopIn(): void
loopOut(): void
toggleLoop(): void
toggleSync(): void
/** Make this deck the tempo master (performance mode). */
makeMaster(): void
toggleKeylock(): void
/** The pitch fader, -1..1. */
pitch: number
/** A hand move of the pitch fader (releases SYNC). */
setPitch(v: number): void
jogTouch(on: boolean, sensitivity: number): void
jogTurn(ticks: number, sensitivity: number): void
scrub(ticks: number, sensitivity: number): void
}
export interface MidiTargets {
performance: boolean
/** The deck loads go to. */
focused: DeckId
decks: Record<DeckId, DeckMidi | null>
togglePerformance: (() => void) | null
/** Load the track list's highlighted row into `deck`. */
load: ((deck: DeckId) => void) | null
/** Move the track list's highlight by `ticks` rows. */
browse: ((ticks: number) => void) | null
/** The track list's highlighted row (what `load` loads). */
lead: (() => Track | null) | null
/** The sidebar's playlist tree. */
tree: { step(ticks: number): void; press(): void } | null
}
export const EMPTY_TARGETS: MidiTargets = {
performance: false,
focused: 'A',
decks: { A: null, B: null },
togglePerformance: null,
load: null,
browse: null,
lead: null,
tree: null,
}
/** Messages a learn capture waits for before guessing an encoding. */
const LEARN_SAMPLES = 12
/** …or this long after the first one. */
const LEARN_WINDOW_MS = 800
/** A CC learned for a button waits this long: for a note-on (a touch jog sends
* both), or for more messages showing it is an encoder being turned. */
const LEARN_CC_BUTTON_MS = 400
/** A fast encoder turn may report several ticks at once; never more repeats. */
const MAX_TURN_REPEAT = 8
const learnKind = (k: ActionKind | 'shift'): LearnKind =>
k === 'continuous' ? 'continuous' : k === 'jog' ? 'jog' : 'button'
interface Capture {
target: LearnTarget
kind: LearnKind
port: string | null
source: SourceKey | null
samples: MidiMessage[]
layer: Layer
timer: ReturnType<typeof setTimeout> | null
}
export class MidiRouter {
/** Per port, the Shift controls held now (two may be mapped). */
private shiftHeld = new Map<string, Set<SourceKey>>()
private decoders = new Map<string, Decoder>()
private held = new Map<string, string>()
private capture: Capture | null = null
private lastActivity = 0
private targets: () => MidiTargets
constructor(targets: () => MidiTargets) {
this.targets = targets
}
/** Raw bytes from `port`. */
receive(port: string, bytes: ArrayLike<number>): void {
const m = parseMessage(bytes)
if (m) this.handle(port, m)
}
handle(port: string, m: MidiMessage): void {
const key = sourceKey(m)
const st = getMidiState()
// The settings dialog's activity line: a jog sends hundreds a second.
const now = performance.now()
if (now - this.lastActivity > 50) {
this.lastActivity = now
patchMidi({ activity: { port, source: key, value: m.value, at: now } })
}
const mapping = st.mappings[port]
// Shift: tracked always, and never an action of its own.
if (mapping && isShift(mapping, key) && !(st.armed?.action === 'shift')) {
const held = this.shiftHeld.get(port) ?? new Set<SourceKey>()
if (m.value > 0) held.add(key)
else held.delete(key)
this.shiftHeld.set(port, held)
return
}
if (st.armed) {
this.learn(port, m, key, st.armed)
return
}
if (!mapping) return
const shift = this.isShifted(port)
const hit = resolveBinding(mapping, key)
// An encoder whose turns are bound by direction. The plain binding wins
// where it has an action for this layer; else the turns do.
const plus = mapping.bindings[turnSource(key, '+')]
const minus = mapping.bindings[turnSource(key, '-')]
if (plus || minus) {
const plainHere = hit && (shift ? hit.binding.shift : hit.binding.normal)
const turnHere = shift ? (plus?.shift ?? minus?.shift) : (plus?.normal ?? minus?.normal)
if (!plainHere && (turnHere || !hit)) return this.turn(port, m, key, plus ?? minus!, shift, mapping)
}
if (!hit) return
const { binding, isLsb } = hit
const decKey = `${port}|${hit.key}`
let dec = this.decoders.get(decKey)
if (!dec || dec.encoding !== binding.encoding || dec.invert !== !!binding.invert) {
dec = new Decoder(binding.encoding, !!binding.invert)
this.decoders.set(decKey, dec)
}
const d = dec.feed(m, isLsb)
if (!d) return
const heldKey = `${port}|${hit.key}`
// A release goes where its press went.
if (d.type === 'press' && !d.down) {
const action = this.held.get(heldKey)
if (action) {
this.held.delete(heldKey)
this.run(action, d, mapping.jogSensitivity, mapping.scrubSpeed)
}
return
}
const action = shift ? (binding.shift ?? binding.normal) : binding.normal
if (!action) return
if (d.type === 'press' && actionDef(action)?.kind === 'hold') this.held.set(heldKey, action)
this.run(action, d, mapping.jogSensitivity, mapping.scrubSpeed)
}
/** One message from an encoder bound by direction: each tick fires that
* direction's action once (a hold is pressed and released). */
private turn(port: string, m: MidiMessage, key: SourceKey, any: Binding, shift: boolean, mapping: Mapping): void {
const decKey = `${port}|${key}~turn`
let dec = this.decoders.get(decKey)
if (!dec || dec.encoding !== any.encoding) {
dec = new Decoder(any.encoding)
this.decoders.set(decKey, dec)
}
const d = dec.feed(m)
if (!d || d.type !== 'delta') return
const b = mapping.bindings[turnSource(key, d.ticks > 0 ? '+' : '-')]
const action = b && (shift ? (b.shift ?? b.normal) : b.normal)
if (!action) return
const hold = actionDef(action)?.kind === 'hold'
for (let i = 0; i < Math.min(Math.abs(d.ticks), MAX_TURN_REPEAT); i++) {
this.run(action, { type: 'press', down: true }, mapping.jogSensitivity, mapping.scrubSpeed)
if (hold) this.run(action, { type: 'press', down: false }, mapping.jogSensitivity, mapping.scrubSpeed)
}
}
private isShifted(port: string): boolean {
return (this.shiftHeld.get(port)?.size ?? 0) > 0
}
/** Forget held controls and decoder state (a controller unplugged). */
forget(port: string): void {
this.shiftHeld.delete(port)
for (const k of [...this.decoders.keys()]) if (k.startsWith(`${port}|`)) this.decoders.delete(k)
for (const k of [...this.held.keys()]) if (k.startsWith(`${port}|`)) this.held.delete(k)
}
// ---- actions -----------------------------------------------------------------
private run(action: string, d: Decoded, sensitivity: number, scrubSpeed: number): void {
const t = this.targets()
if (performanceOnly(action) && !t.performance) return
const def = actionDef(action)
if (!def) return
// A press as the action's kind wants it; a position on a button = pressed past halfway.
const down = d.type === 'press' ? d.down : d.type === 'abs' ? d.unit > 0.5 : null
if (action.startsWith('mixer.')) return this.mixer(action, d, down)
if (action === 'app.performance') return void (down && t.togglePerformance?.())
if (action === 'library.browse') return void (d.type === 'delta' && t.browse?.(d.ticks))
if (action === 'library.tree') return void (d.type === 'delta' && t.tree?.step(d.ticks))
if (action === 'library.browsePress') return void (down && t.load?.(t.focused))
if (action === 'library.treePress') return void (down && t.tree?.press())
const deckId = actionDeck(action)
const deck = deckId && t.decks[deckId]
if (!deck || !deckId) return
const op = action.slice('deck.A.'.length)
if (def.kind === 'continuous') {
if (op !== 'pitch') return
if (d.type === 'abs') deck.setPitch(d.bipolar)
else if (d.type === 'delta') deck.setPitch(Math.max(-1, Math.min(1, deck.pitch + d.ticks / 512)))
return
}
if (def.kind === 'jog') {
if (d.type !== 'delta') return
if (op === 'jog') deck.jogTurn(d.ticks, sensitivity)
else if (op === 'scrub') deck.scrub(d.ticks, sensitivity * scrubSpeed)
return
}
if (down == null) return
if (def.kind === 'hold') {
const slot = op.match(/^hotcue\.(\d+)$/)
if (slot) {
const s = Number(slot[1]) - 1
if (s >= deck.slotCount) return
return void (down ? deck.onSlotPress(s) : deck.onSlotRelease(s))
}
if (op === 'cue') return down ? deck.onCuePress() : deck.onCueRelease()
if (op === 'jogTouch') return deck.jogTouch(down, sensitivity)
return
}
if (!down) return
const n = op.match(/^(hotcueErase|stem|stemSolo)\.(\d+)$/)
if (n) {
const i = Number(n[2]) - 1
if (n[1] === 'hotcueErase') return void (i < deck.slotCount && deck.deleteHotcueSlot(i))
return deck.toggleStem(i, n[1] === 'stemSolo')
}
switch (op) {
case 'play':
return deck.toggle()
case 'sync':
return deck.toggleSync()
case 'master':
return deck.makeMaster()
case 'keylock':
return deck.toggleKeylock()
case 'jumpBack':
return deck.moveOrJump(-1)
case 'jumpFwd':
return deck.moveOrJump(1)
case 'markerPrev':
return deck.prevMarker()
case 'markerNext':
return deck.nextMarker()
case 'sizeDown':
return deck.stepSize(-1)
case 'sizeUp':
return deck.stepSize(1)
case 'sizeLoop':
return deck.toggleSizeLoop()
case 'loopIn':
return deck.loopIn()
case 'loopOut':
return deck.loopOut()
case 'loopToggle':
return deck.toggleLoop()
case 'load':
return void t.load?.(deckId)
}
}
private mixer(action: string, d: Decoded, down: boolean | null): void {
const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v))
if (action === 'mixer.crossfader') {
const x = getMixerState().crossfader
if (d.type === 'abs') setMixer({ crossfader: d.bipolar })
else if (d.type === 'delta') setMixer({ crossfader: clamp(x + d.ticks / 64, -1, 1) })
return
}
const m = action.match(/^mixer\.([AB])\.(\w+)$/)
if (!m) return
const ch = m[1] as DeckId
const op = m[2]
const s = getMixerState()[ch]
if (op === 'fxNext' || op === 'fxPrev') {
if (!down) return
const i = FX_TYPES.indexOf(s.fx)
const n = FX_TYPES.length
return setChannel(ch, { fx: FX_TYPES[(i + (op === 'fxNext' ? 1 : n - 1)) % n] })
}
const field: Record<string, keyof ChannelState> = { gain: 'trim', high: 'high', mid: 'mid', low: 'low', filter: 'color', fader: 'fader' }
const f = field[op]
if (!f) return
// Gain is ±TRIM_RANGE_DB, the fader 0..1, the rest -1..1 (centre flat).
const [lo, hi] = f === 'trim' ? [-TRIM_RANGE_DB, TRIM_RANGE_DB] : f === 'fader' ? [0, 1] : [-1, 1]
let v: number
if (d.type === 'abs') v = f === 'fader' ? d.unit : d.bipolar * hi
else if (d.type === 'delta') v = clamp((s[f] as number) + (d.ticks * (hi - lo)) / 128, lo, hi)
else return
setChannel(ch, { [f]: v })
}
// ---- learn ---------------------------------------------------------------------
private learn(port: string, m: MidiMessage, key: SourceKey, target: LearnTarget): void {
const kind = learnKind(target.action === 'shift' ? 'shift' : (actionDef(target.action)?.kind ?? 'button'))
let c = this.capture
if (!c || c.target !== target) {
if (c?.timer) clearTimeout(c.timer)
const layer: Layer = 'layer' in target ? (this.isShifted(port) ? 'shift' : target.layer) : 'normal'
c = this.capture = { target, kind, port: null, source: null, samples: [], layer, timer: null }
}
if (c.port && c.port !== port) return // one controller at a time
if (kind === 'button') {
if (m.kind === 'note') {
if (m.value > 0) this.commit(c, port, key, 'button')
return
}
if (m.kind !== 'cc') return
// A CC is either a button or an ENCODER turned for this action's
// direction: wait and see what else it sends (and whether a note-on
// follows — a touch jog sends both).
if (!c.source) {
if (m.value === 0) return
c.port = port
c.source = key
c.timer = setTimeout(() => this.finishButton(), LEARN_CC_BUTTON_MS)
}
if (key === c.source) c.samples.push(m)
return
}
// A position or ticks: notes (a jog's touch sensor, a stray pad) do not count.
if (m.kind === 'note') return
if (!c.source) {
c.port = port
c.source = key
c.timer = setTimeout(() => this.finish(), LEARN_WINDOW_MS)
} else if (m.kind === 'cc' && c.source.startsWith('cc:')) {
// The MSB of a 14-bit pair is the lower number, whichever came first.
const first = Number(c.source.split(':')[2])
if (m.channel === Number(c.source.split(':')[1]) && m.number === first - 32) c.source = key
}
c.samples.push(m)
if (c.samples.length >= LEARN_SAMPLES) this.finish()
}
/**
* A CC learned for a button action: a press (one message, or a press and a
* release to 0) binds as a button; several non-zero messages are an encoder
* TURNED, bound to the direction it went (decided 2026-11-03: controllers
* put beat jump and loop size on encoders).
*/
private finishButton(): void {
const c = this.capture
if (!c || !c.port || !c.source) return
const vals = c.samples
if (vals.length < 2 || vals.some((v) => v.value === 0)) return this.commit(c, c.port, c.source, 'button')
const enc = detectEncoding(vals, 'jog')
const dec = new Decoder(enc)
let ticks = 0
for (const v of vals) {
const d = dec.feed(v)
if (d?.type === 'delta') ticks += d.ticks
}
if (ticks === 0) return this.commit(c, c.port, c.source, 'button')
this.commit(c, c.port, turnSource(c.source, ticks > 0 ? '+' : '-'), enc)
}
/** Commit a continuous / jog capture now (its window ran out). */
finish(): void {
const c = this.capture
if (!c || !c.port || !c.source) return
const src = c.source
// The bound control's own message first: the guess reads its kind and number.
const lead = c.samples.find((s) => sourceKey(s) === src)
const ordered = lead ? [lead, ...c.samples.filter((s) => s !== lead)] : c.samples
// A 14-bit pair binds on its MSB; anything else on the control that moved.
this.commit(c, c.port, src, detectEncoding(ordered, c.kind))
}
private commit(c: Capture, port: string, source: SourceKey, encoding: Encoding): void {
if (c.timer) clearTimeout(c.timer)
if (this.capture !== c) return
this.capture = null
const t = c.target
if ('slot' in t) updateMapping(port, (m) => bindShift(m, source, t.slot))
else {
updateMapping(port, (m) => bind(m, source, encoding, c.layer, t.action))
patchMidi({ learned: { port, action: t.action, layer: c.layer, at: performance.now() } })
}
this.decoders.delete(`${port}|${source}`)
this.decoders.delete(`${port}|${splitSource(source).base}~turn`)
armLearn(null)
}
}
+88
View File
@@ -0,0 +1,88 @@
// MIDI state the UI shows and the router reads, in one small external store
// read through useSyncExternalStore (as lib/audio/mixerState.ts is): the
// connected controllers, every controller's mapping, what is being learned and
// the last message seen (the settings dialog's activity line).
//
// Mappings are persisted by whoever installs `setPersist` (useMidi, through
// the shared prefs writer); everything else lives for the session.
import { useSyncExternalStore } from 'react'
import type { Layer, Mapping, Mappings } from './mapping'
import { emptyMapping } from './mapping'
import type { SourceKey } from './messages'
/** What Learn is waiting for: an action in a layer, or the Shift control itself. */
export type LearnTarget = { action: string; layer: Layer } | { action: 'shift'; slot: 0 | 1 }
export interface MidiState {
/** Whether this build can read MIDI at all (desktop app, or a Web MIDI browser). */
available: boolean
/** Why MIDI could not be read (a browser refused access), else null. */
blocked: string | null
/** Connected controllers, by port name. */
ports: string[]
mappings: Mappings
/** Armed: the next control moved is bound to this. */
armed: LearnTarget | null
/** On-screen learn mode: clicking a control arms it. */
onScreen: boolean
/** The last binding learned (the on-screen mode flashes it). */
learned: { port: string; action: string; layer: Layer; at: number } | null
activity: { port: string; source: SourceKey; value: number; at: number } | null
}
let state: MidiState = {
available: false,
blocked: null,
ports: [],
mappings: {},
armed: null,
onScreen: false,
learned: null,
activity: null,
}
const listeners = new Set<() => void>()
let persist: ((m: Mappings) => void) | null = null
export function getMidiState(): MidiState {
return state
}
export function subscribeMidi(fn: () => void): () => void {
listeners.add(fn)
return () => listeners.delete(fn)
}
export function patchMidi(patch: Partial<MidiState>): void {
state = { ...state, ...patch }
for (const fn of listeners) fn()
}
export function setPersist(fn: ((m: Mappings) => void) | null): void {
persist = fn
}
/** Change one controller's mapping (created empty on first use) and save. */
export function updateMapping(port: string, fn: (m: Mapping) => Mapping): void {
const mappings = { ...state.mappings, [port]: fn(state.mappings[port] ?? emptyMapping()) }
patchMidi({ mappings })
persist?.(mappings)
}
export function replaceMappings(mappings: Mappings, save = true): void {
patchMidi({ mappings })
if (save) persist?.(mappings)
}
export function armLearn(target: LearnTarget | null): void {
patchMidi({ armed: target })
}
export function setOnScreenLearn(on: boolean): void {
patchMidi({ onScreen: on, armed: null })
}
/** A slice of the MIDI state, re-rendering only when it changes. */
export function useMidiState<T>(select: (s: MidiState) => T): T {
return useSyncExternalStore(subscribeMidi, () => select(state))
}
+29
View File
@@ -0,0 +1,29 @@
// What the router acts on, filled in by whoever is mounted to take it:
// PrepStrip (the decks, performance mode), App (loading), TrackTable (browse)
// and Sidebar (the playlist tree). Assigned on every render — as PrepStrip's
// `keys` ref is — so the router always sees the latest handlers.
//
// Unmounting clears only what THIS component last set: switching views
// renders the new table (which registers) before the old one's cleanup runs,
// and a blanket reset would wipe the newcomer's handlers.
import { useEffect, useRef } from 'react'
import { EMPTY_TARGETS, type MidiTargets } from './router'
export const midiTargets: MidiTargets = { ...EMPTY_TARGETS, decks: { A: null, B: null } }
export function useMidiTargets(patch: Partial<MidiTargets>): void {
Object.assign(midiTargets, patch)
const mine = useRef(patch)
mine.current = patch
useEffect(
() => () => {
const t = midiTargets as unknown as Record<string, unknown>
for (const [k, v] of Object.entries(mine.current)) {
if (t[k] !== v) continue
t[k] = k === 'decks' ? { A: null, B: null } : EMPTY_TARGETS[k as keyof MidiTargets]
}
},
[],
)
}
+89
View File
@@ -0,0 +1,89 @@
// Where MIDI comes from. The desktop app reads ports in the shell
// (src-tauri/src/midi.rs: WKWebView has no Web MIDI); a browser under
// `./dev.sh` uses Web MIDI (Chrome) — same interface, so nothing above here
// knows which. Neither (Safari, Firefox without the permission) = no MIDI.
export type OnBytes = (batch: ArrayLike<number>[]) => void
export interface MidiTransport {
ports(): Promise<string[]>
/** Start receiving; resolves to the function that stops it. */
open(port: string, onBytes: OnBytes): Promise<() => void>
}
/** "X", "X #2" for two identical controllers — the shell names them the same way. */
export function uniqueNames(names: string[]): string[] {
const seen = new Map<string, number>()
return names.map((n) => {
const k = (seen.get(n) ?? 0) + 1
seen.set(n, k)
return k === 1 ? n : `${n} #${k}`
})
}
function tauriTransport(): MidiTransport {
const core = () => import('@tauri-apps/api/core')
return {
ports: async () => (await core()).invoke<string[]>('midi_ports'),
open: async (port, onBytes) => {
const { invoke, Channel } = await core()
// A fresh Channel per open: Tauri ends one whose Rust side was dropped.
const ch = new Channel<{ wall_us: number; bytes: number[] }[]>()
ch.onmessage = (batch) => onBytes(batch.map((p) => p.bytes))
await invoke('midi_open', { port, onMessage: ch })
return () => void invoke('midi_close', { port }).catch(() => {})
},
}
}
function webMidiTransport(): MidiTransport {
// Chrome asks the user first. A refusal is not kept for good: after
// REASK_MS the poll asks again, so allowing MIDI in the site settings takes
// effect without a reload — but a dismissed prompt is not shown again at
// once (every 1.5 s would nag, and Chrome blocks a site after repeats).
const REASK_MS = 20_000
let access: Promise<MIDIAccess> | null = null
let refused: { at: number; error: unknown } | null = null
const get = () => {
if (refused && performance.now() - refused.at < REASK_MS) return Promise.reject(refused.error)
return (access ??= navigator.requestMIDIAccess({ sysex: false }).then(
(a) => ((refused = null), a),
(e: unknown) => {
access = null
refused = { at: performance.now(), error: e }
throw e
},
))
}
const inputs = async () => {
const list = [...(await get()).inputs.values()].filter((i) => i.state === 'connected')
const names = uniqueNames(list.map((i) => i.name ?? 'MIDI input'))
return list.map((input, k) => ({ input, name: names[k] }))
}
return {
ports: async () => (await inputs()).map((i) => i.name),
open: async (port, onBytes) => {
const hit = (await inputs()).find((i) => i.name === port)
if (!hit) throw new Error(`MIDI port not found: ${port}`)
const handler = (e: MIDIMessageEvent) => {
// System messages stay out, as the shell ignores them.
if (e.data && e.data[0] < 0xf0) onBytes([e.data])
}
hit.input.addEventListener('midimessage', handler)
// Only SETTING `onmidimessage` opens a port implicitly; a listener added
// with addEventListener does not, so open it ourselves.
await hit.input.open()
return () => {
hit.input.removeEventListener('midimessage', handler)
void hit.input.close().catch(() => {})
}
},
}
}
export function midiTransport(): MidiTransport | null {
if (typeof window === 'undefined') return null
if ('__TAURI_INTERNALS__' in window) return tauriTransport()
if (typeof navigator.requestMIDIAccess === 'function') return webMidiTransport()
return null
}
+101
View File
@@ -0,0 +1,101 @@
// MIDI for the whole app, mounted once (App): finds controllers as they come
// and go, feeds their messages to the router, and keeps the mappings in
// userprefs (`midiMappings`, through the shared debounced prefs writer).
//
// midir has no connect notifications (nor does every Web MIDI), so the port
// list is polled — cheap, and a newly plugged controller works within ~1.5 s.
import { useEffect, useRef } from 'react'
import { useQuery } from '@tanstack/react-query'
import { api } from '../../api'
import { usePrefsWriter } from '../prefs'
import { sanitizeMappings } from './mapping'
import { MidiRouter } from './router'
import { getMidiState, patchMidi, replaceMappings, setPersist } from './store'
import { midiTargets } from './targets'
import { midiTransport } from './transport'
const POLL_MS = 1500
/** The router every message goes through (one per app). */
export const midiRouter = new MidiRouter(() => midiTargets)
export function useMidi(onNotify: (kind: 'success' | 'warning', msg: string) => void): void {
const writePrefs = usePrefsWriter()
const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }).data
const hydrated = useRef(false)
const notify = useRef(onNotify)
notify.current = onNotify
// Mappings: hydrated once from prefs, then saved on every change.
useEffect(() => {
if (hydrated.current || !prefs) return
hydrated.current = true
replaceMappings(sanitizeMappings((prefs as { midiMappings?: unknown }).midiMappings), false)
setPersist((m) => writePrefs({ midiMappings: m }))
}, [prefs, writePrefs])
useEffect(() => () => setPersist(null), [])
useEffect(() => {
const transport = midiTransport()
if (!transport) return
patchMidi({ available: true })
const open = new Map<string, () => void>()
const opening = new Set<string>()
let first = true
let stopped = false
const poll = async () => {
let ports: string[]
try {
ports = await transport.ports()
if (getMidiState().blocked) patchMidi({ blocked: null })
} catch (e) {
// A browser refusing MIDI access (Chrome asks first): say so in the
// MIDI dialog rather than looking like no controller is plugged in.
const why = e instanceof Error ? e.message : String(e)
if (getMidiState().blocked !== why) patchMidi({ blocked: why })
return
}
if (stopped) return
for (const [port, close] of open) {
if (ports.includes(port)) continue
close()
open.delete(port)
midiRouter.forget(port)
}
for (const port of ports) {
if (open.has(port) || opening.has(port)) continue
opening.add(port)
// Ports present at launch connect quietly; later ones are news.
const announce = !first
transport
.open(port, (batch) => {
for (const bytes of batch) midiRouter.receive(port, bytes)
})
.then((close) => {
if (stopped) return close()
open.set(port, close)
if (!announce) return
const mapped = !!getMidiState().mappings[port]
notify.current(
mapped ? 'success' : 'warning',
mapped ? `${port} connected` : `${port} connected — not mapped yet (Settings ▸ MIDI Controllers…)`,
)
})
.catch(() => {})
.finally(() => opening.delete(port))
}
patchMidi({ ports })
first = false
}
void poll()
const t = setInterval(() => void poll(), POLL_MS)
return () => {
stopped = true
clearInterval(t)
for (const close of open.values()) close()
patchMidi({ ports: [] })
}
}, [])
}
+3
View File
@@ -12,6 +12,7 @@ import { DragLayer } from './lib/drag.tsx'
import { QuitGuard } from './components/QuitGuard.tsx'
import { preventHistoryNavigation } from './lib/noNavigation.ts'
import { StartupGate } from './components/StartupScreen.tsx'
import { MidiLearnOverlay } from './components/MidiLearnOverlay.tsx'
preventHistoryNavigation()
@@ -38,6 +39,8 @@ createRoot(document.getElementById('root')!).render(
<ConfirmHost />
{/* Save · Discard · Cancel when quitting with unsaved changes. */}
<QuitGuard />
{/* MIDI learning by clicking controls (Settings ▸ MIDI Controllers…). */}
<MidiLearnOverlay />
{/* The ghost under the cursor while dragging tracks or playlists. */}
<DragLayer />
</StartupGate>