diff --git a/CLAUDE.md b/CLAUDE.md index 14ae576..59d4069 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1502,6 +1502,55 @@ 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, 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). **`router.ts`**: Shift is a learned control (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, scrub while + paused; 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 +1606,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 -- ``` **Tests:** `cd backend && ./run_tests.sh` (runs against a temp copy of the real @@ -1959,6 +2011,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 +2762,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 diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 20e0173..666155c 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -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 `.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, diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 55a1c26..4b18cf0 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -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 diff --git a/backend/run_tests.sh b/backend/run_tests.sh index e69b6de..8bebd6f 100755 --- a/backend/run_tests.sh +++ b/backend/run_tests.sh @@ -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 "──────────────────────────────────────────" diff --git a/backend/test_midi_mappings.py b/backend/test_midi_mappings.py new file mode 100644 index 0000000..805b045 --- /dev/null +++ b/backend/test_midi_mappings.py @@ -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 .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) diff --git a/frontend/src-tauri/Cargo.lock b/frontend/src-tauri/Cargo.lock index 4cc70a0..d2f3b50 100644 --- a/frontend/src-tauri/Cargo.lock +++ b/frontend/src-tauri/Cargo.lock @@ -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", diff --git a/frontend/src-tauri/Cargo.toml b/frontend/src-tauri/Cargo.toml index a7d8e8d..9ed92fb 100644 --- a/frontend/src-tauri/Cargo.toml +++ b/frontend/src-tauri/Cargo.toml @@ -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"] } diff --git a/frontend/src-tauri/examples/midi_flood.rs b/frontend/src-tauri/examples/midi_flood.rs new file mode 100644 index 0000000..93479e8 --- /dev/null +++ b/frontend/src-tauri/examples/midi_flood.rs @@ -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 -- +// +// 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 = 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)."); +} diff --git a/frontend/src-tauri/src/lib.rs b/frontend/src-tauri/src/lib.rs index 5311c2d..16ee18b 100644 --- a/frontend/src-tauri/src/lib.rs +++ b/frontend/src-tauri/src/lib.rs @@ -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 { diff --git a/frontend/src-tauri/src/midi.rs b/frontend/src-tauri/src/midi.rs new file mode 100644 index 0000000..19ae723 --- /dev/null +++ b/frontend/src-tauri/src/midi.rs @@ -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, +} + +/// 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>>); + +fn client() -> Result { + 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 = 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, 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>, +) -> 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::(); + 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(); + } +} + diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 6fdc9d0..db537a3 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -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 diff --git a/frontend/src/api.ts b/frontend/src/api.ts index b2d2809..644f141 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -1140,8 +1140,12 @@ export const api = { // shortcuts and the browsable files are only meaningful inside that answer. collectionOptions: (platform?: string) => getJSON(`/api/library/options${qs({ platform })}`), - listDir: (path?: string, platform?: string) => - getJSON(`/api/fs/list${qs({ path, platform })}`), + listDir: (path?: string, platform?: string, suffix?: string) => + getJSON(`/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(`/api/library/fs/list${qs({ path })}`), diff --git a/frontend/src/components/FileBrowser.tsx b/frontend/src/components/FileBrowser.tsx index 84f63b8..019197e 100644 --- a/frontend/src/components/FileBrowser.tsx +++ b/frontend/src/components/FileBrowser.tsx @@ -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), diff --git a/frontend/src/components/HotcueBar.tsx b/frontend/src/components/HotcueBar.tsx index e3af859..8b2d755 100644 --- a/frontend/src/components/HotcueBar.tsx +++ b/frontend/src/components/HotcueBar.tsx @@ -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 = { * than surfacing the refusal as an error. */ export function HotcueBar({ + midi, cues, slotCount, slotLabel, @@ -74,6 +77,7 @@ export function HotcueBar({ return ( + + , + document.body, + ) +} diff --git a/frontend/src/components/MidiSettings.tsx b/frontend/src/components/MidiSettings.tsx new file mode 100644 index 0000000..64dc47c --- /dev/null +++ b/frontend/src/components/MidiSettings.tsx @@ -0,0 +1,368 @@ +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, + emptyMapping, + sanitizeMapping, + setBinding, + sourcesFor, + unbind, + type Layer, + type Mapping, +} from '../lib/midi/mapping' +import { describeSource, 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 sameTarget = (a: LearnTarget | null, b: LearnTarget) => + a != null && a.action === b.action && ('layer' in a ? a.layer : null) === ('layer' in b ? b.layer : null) + +/** + * 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(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 (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 ( + + ) + } + const sources = sourcesFor(mapping, action.id, layer) + if (sources.length === 0) { + return ( + + ) + } + return ( +
+ {sources.map((src) => { + const enc = mapping.bindings[src]?.encoding + return ( + + ) + })} +
+ ) + } + + 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.shift) { + 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 ( + armLearn(null) : onClose}> +
+
+

MIDI Controllers

+ +
+ + {!available ? ( +
+ MIDI is not available here. The desktop app reads controllers itself; in a browser, use Chrome. +
+ ) : blocked && known.length === 0 ? ( +
+

The browser refused access to MIDI devices.

+

+ Allow it from the site settings (the icon left of the address: MIDI devices → Allow). Konduktor asks again on + its own. ({blocked}) +

+
+ ) : known.length === 0 ? ( +
Plug in a MIDI controller — it shows up here within a couple of seconds.
+ ) : ( + <> +
+
+ + + {activity + ? `${activity.port}: ${describeSource(activity.source)} → ${activity.value}` + : 'Move a control to see it here'} + + + + + {mappings[port ?? ''] && ( + + )} +
+ {note &&
{note.text}
} +
+ Shift button +
+ {sameTarget(armed, { action: 'shift' }) ? ( + + ) : mapping.shift ? ( + <> + {describeSource(mapping.shift)} + + + + ) : ( + + )} + Hold it while moving a control to learn its Shift action. +
+ Jog sensitivity + `×${v.toFixed(2)}`} + onChange={(v) => edit((m) => ({ ...m, jogSensitivity: v }))} + /> + Fast scrub + `×${v} a jog`} + onChange={(v) => edit((m) => ({ ...m, scrubSpeed: v }))} + /> +
+
+ +
+ 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" + /> + Control + With Shift +
+
+ {ACTION_GROUPS.map((g) => { + const rows = shown.filter((a) => a.group === g) + if (rows.length === 0) return null + return ( +
+

+ {g} + {g === 'Deck B' || g === 'Mixer' ? — performance mode only : null} +

+ {rows.map((a) => ( +
+ {a.label} +
{cell(a, 'normal')}
+
{cell(a, 'shift')}
+
+ ))} +
+ ) + })} +
+ + )} +
+ {menu && setMenu(null)} />} + {exporting && void doExport(dir)} onClose={() => setExporting(false)} />} + {importing && void doImport(p)} onClose={() => setImporting(false)} />} +
+ ) +} + +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 ( +
+ onChange(Number(e.target.value))} + onDoubleClick={() => onChange(reset)} + className="w-48" + /> + {format(value)} +
+ ) +} + +/** Pick a `.konduktor-midi.json` file. */ +function ImportPicker({ onPick, onClose }: { onPick: (path: string) => void; onClose: () => void }) { + const [dir, setDir] = useState(undefined) + return ( + +
+
+

Import a MIDI mapping

+
+ +
+ +
+
+
+ ) +} diff --git a/frontend/src/components/PrepStrip.tsx b/frontend/src/components/PrepStrip.tsx index db6abb5..7d9cbca 100644 --- a/frontend/src/components/PrepStrip.tsx +++ b/frontend/src/components/PrepStrip.tsx @@ -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,43 @@ 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)!) + }, + 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({ focused: null, other: null }) keys.current = { focused: deckOf(lead).shortcuts, diff --git a/frontend/src/components/SettingsMenu.tsx b/frontend/src/components/SettingsMenu.tsx index a419b29..fc0ad43 100644 --- a/frontend/src/components/SettingsMenu.tsx +++ b/frontend/src/components/SettingsMenu.tsx @@ -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(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) { Performance mode… The second deck, the mixer and its effects + ({ + 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('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 = { 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' +} diff --git a/frontend/src/lib/midi/encoding.test.ts b/frontend/src/lib/midi/encoding.test.ts new file mode 100644 index 0000000..3a967c9 --- /dev/null +++ b/frontend/src/lib/midi/encoding.test.ts @@ -0,0 +1,103 @@ +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') + }) +}) + +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') + }) +}) diff --git a/frontend/src/lib/midi/encoding.ts b/frontend/src/lib/midi/encoding.ts new file mode 100644 index 0000000..9c8ff52 --- /dev/null +++ b/frontend/src/lib/midi/encoding.ts @@ -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 = { + 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' +} diff --git a/frontend/src/lib/midi/mapping.test.ts b/frontend/src/lib/midi/mapping.test.ts new file mode 100644 index 0000000..18af052 --- /dev/null +++ b/frontend/src/lib/midi/mapping.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it } from 'vitest' +import { ACTIONS, shiftDefault } from './actions' +import { bind, bindShift, emptyMapping, resolveBinding, sanitizeMapping, 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.shift).toBe('note:1:63') + expect(m.bindings['note:1:63']).toBeUndefined() + m = bind(m, 'note:1:63', 'button', 'normal', 'deck.A.cue') + expect(m.shift).toBeNull() + }) + 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('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?.shift).toBe('note:1:63') + expect(m?.jogSensitivity).toBe(10) + expect(Object.keys(m!.bindings)).toEqual(['note:1:0']) + expect(sanitizeMapping({ version: 2 })).toBeNull() + }) +}) diff --git a/frontend/src/lib/midi/mapping.ts b/frontend/src/lib/midi/mapping.ts new file mode 100644 index 0000000..78808ce --- /dev/null +++ b/frontend/src/lib/midi/mapping.ts @@ -0,0 +1,143 @@ +// 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, 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 control acting as Shift (itself a learned control). */ + shift: SourceKey | null + bindings: Record + /** 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 + +export const DEFAULT_JOG_SENSITIVITY = 1 +export const DEFAULT_SCRUB_SPEED = 8 + +export function emptyMapping(): Mapping { + return { version: 1, shift: 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 + if (r.version !== 1) return null + const out = emptyMapping() + if (typeof r.shift === 'string' && parseSource(r.shift)) out.shift = r.shift + out.jogSensitivity = num(r.jogSensitivity, 0.1, 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) : {} + for (const [key, b] of Object.entries(bindings)) { + if (!parseSource(key) || !b || typeof b !== 'object') continue + const x = b as Record + 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)) { + 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 = {} + 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 + return { ...cleared, shift: cleared.shift === source ? null : cleared.shift, bindings: { ...cleared.bindings, [source]: next } } +} + +/** Make `source` the Shift control (it then does nothing else). */ +export function bindShift(m: Mapping, source: SourceKey): Mapping { + const bindings = { ...m.bindings } + delete bindings[source] + return { ...m, shift: source, bindings } +} + +export function setBinding(m: Mapping, source: SourceKey, patch: Partial): Mapping { + const b = m.bindings[source] + if (!b) return m + return { ...m, bindings: { ...m.bindings, [source]: { ...b, ...patch } } } +} + +/** + * 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 +} diff --git a/frontend/src/lib/midi/messages.ts b/frontend/src/lib/midi/messages.ts new file mode 100644 index 0000000..0b1cb5d --- /dev/null +++ b/frontend/src/lib/midi/messages.ts @@ -0,0 +1,61 @@ +// 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): 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): SourceKey { + return m.kind === 'pb' ? `pb:${m.channel}` : `${m.kind}:${m.channel}:${m.number}` +} + +export function parseSource(key: SourceKey): Pick | null { + const [kind, ch, num] = key.split(':') + const channel = Number(ch) + if (!(channel >= 1 && channel <= 16)) return null + if (kind === 'pb') return { kind, channel, number: 0 } + const number = Number(num) + if ((kind !== 'note' && kind !== 'cc') || !(number >= 0 && number <= 127)) return null + return { kind, channel, number } +} + +/** "Note 11 · Ch 1", "CC 33 · Ch 2", "Pitch bend · 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}` + return `${what} · Ch ${s.channel}` +} diff --git a/frontend/src/lib/midi/router.test.ts b/frontend/src/lib/midi/router.test.ts new file mode 100644 index 0000000..4ea152b --- /dev/null +++ b/frontend/src/lib/midi/router.test.ts @@ -0,0 +1,192 @@ +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'), + toggleKeylock: log('keylock'), + setPitch: log('pitch'), + jogTouch: log('jogTouch'), + jogTurn: log('jogTurn'), + scrub: log('scrub'), + } +} + +let A: ReturnType +let B: ReturnType +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('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('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('the Shift control itself', () => { + armLearn({ action: 'shift' }) + note(70, 127) + expect(getMidiState().mappings[PORT].shift).toBe('note:1:70') + }) +}) diff --git a/frontend/src/lib/midi/router.ts b/frontend/src/lib/midi/router.ts new file mode 100644 index 0000000..7bbe492 --- /dev/null +++ b/frontend/src/lib/midi/router.ts @@ -0,0 +1,343 @@ +// 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, resolveBinding, type Layer } from './mapping' +import { parseMessage, sourceKey, 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 + 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 + 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 button waits this long for a note-on (a touch-sensitive jog sends both). */ +const LEARN_CC_BUTTON_MS = 250 + +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 | null +} + +export class MidiRouter { + private shiftHeld = new Map() + private decoders = new Map() + private held = new Map() + 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): 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?.shift === key && !(st.armed?.action === 'shift')) { + this.shiftHeld.set(port, m.value > 0) + return + } + if (st.armed) { + this.learn(port, m, key, st.armed) + return + } + if (!mapping) return + const hit = resolveBinding(mapping, key) + 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 = this.shiftHeld.get(port) ? (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) + } + + /** 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 '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 = { 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.shiftHeld.get(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.value === 0) return + if (m.kind === 'note') return this.commit(c, port, key, 'button') + if (m.kind === 'cc' && !c.source) { + // Wait briefly in case a note-on follows (a touch jog sends both). + c.port = port + c.source = key + c.timer = setTimeout(() => this.commit(c!, port, key, 'button'), LEARN_CC_BUTTON_MS) + } + 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() + } + + /** 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 (t.action === 'shift') updateMapping(port, (m) => bindShift(m, source)) + 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}`) + armLearn(null) + } +} diff --git a/frontend/src/lib/midi/store.ts b/frontend/src/lib/midi/store.ts new file mode 100644 index 0000000..04aec4f --- /dev/null +++ b/frontend/src/lib/midi/store.ts @@ -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' } + +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): 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(select: (s: MidiState) => T): T { + return useSyncExternalStore(subscribeMidi, () => select(state)) +} diff --git a/frontend/src/lib/midi/targets.ts b/frontend/src/lib/midi/targets.ts new file mode 100644 index 0000000..21d9408 --- /dev/null +++ b/frontend/src/lib/midi/targets.ts @@ -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): void { + Object.assign(midiTargets, patch) + const mine = useRef(patch) + mine.current = patch + useEffect( + () => () => { + const t = midiTargets as unknown as Record + 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] + } + }, + [], + ) +} diff --git a/frontend/src/lib/midi/transport.ts b/frontend/src/lib/midi/transport.ts new file mode 100644 index 0000000..4e79614 --- /dev/null +++ b/frontend/src/lib/midi/transport.ts @@ -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[]) => void + +export interface MidiTransport { + ports(): Promise + /** 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() + 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('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 | 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 +} diff --git a/frontend/src/lib/midi/useMidi.ts b/frontend/src/lib/midi/useMidi.ts new file mode 100644 index 0000000..6aec9e2 --- /dev/null +++ b/frontend/src/lib/midi/useMidi.ts @@ -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 void>() + const opening = new Set() + 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: [] }) + } + }, []) +} diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index c3f8a45..26e0ac2 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -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( {/* Save · Discard · Cancel when quitting with unsaved changes. */} + {/* MIDI learning by clicking controls (Settings ▸ MIDI Controllers…). */} + {/* The ghost under the cursor while dragging tracks or playlists. */}