From 5d4df2aa5271850a24aadaebdaa7666b205a4792 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Tue, 3 Nov 2026 23:09:16 +0100 Subject: [PATCH] Encoder direction can now be mapped to separate controls --- CLAUDE.md | 10 ++- frontend/src/components/MidiLearnOverlay.tsx | 3 +- frontend/src/components/MidiSettings.tsx | 24 +++++- frontend/src/lib/midi/encoding.test.ts | 3 + frontend/src/lib/midi/mapping.test.ts | 12 ++- frontend/src/lib/midi/mapping.ts | 19 ++++- frontend/src/lib/midi/messages.ts | 27 ++++++- frontend/src/lib/midi/router.test.ts | 59 ++++++++++++++ frontend/src/lib/midi/router.ts | 84 +++++++++++++++++--- 9 files changed, 216 insertions(+), 25 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 59d4069..a51687c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1527,7 +1527,15 @@ Two independent apps that talk over HTTP: 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 + default). **Encoders on button actions** (beat jump, loop size — common + on controllers): learning a button action by TURNING an encoder binds + that DIRECTION, a virtual source `cc:1:20+` / `cc:1:20-` (↻ / ↺); each + tick fires the action once (up to 8 per message), both directions share + the encoder's encoding and decoder, and a plain binding on the same + encoder wins only where it has an action for the layer. A CC learned for + a button waits 400 ms: one message, or any 0, = a button; several + non-zero = a turn (so a two's-complement encoder's 127s are not a press). + **`router.ts`**: Shift is a learned control (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 diff --git a/frontend/src/components/MidiLearnOverlay.tsx b/frontend/src/components/MidiLearnOverlay.tsx index efb89ad..00fac5a 100644 --- a/frontend/src/components/MidiLearnOverlay.tsx +++ b/frontend/src/components/MidiLearnOverlay.tsx @@ -92,7 +92,8 @@ export function MidiLearnOverlay() { MIDI learn — plug in a controller ) : armedLabel ? ( - {armedLabel}: move a control on your controller (hold its Shift for the Shift layer) + {armedLabel}: move a control on your controller — an encoder a few clicks in + this action's direction (hold its Shift for the Shift layer) ) : ( MIDI learn — click a control, then move it on your controller diff --git a/frontend/src/components/MidiSettings.tsx b/frontend/src/components/MidiSettings.tsx index 64dc47c..4fd980b 100644 --- a/frontend/src/components/MidiSettings.tsx +++ b/frontend/src/components/MidiSettings.tsx @@ -13,7 +13,7 @@ import { type Layer, type Mapping, } from '../lib/midi/mapping' -import { describeSource, type SourceKey } from '../lib/midi/messages' +import { describeSource, splitSource, type SourceKey } from '../lib/midi/messages' import { armLearn, replaceMappings, setOnScreenLearn, updateMapping, useMidiState, type LearnTarget } from '../lib/midi/store' import { askConfirm } from '../lib/confirm' import { ContextMenu, type MenuItem } from './ContextMenu' @@ -67,7 +67,20 @@ export function MidiSettings({ onClose }: { onClose: () => void }) { if (!b) return const r = e.currentTarget.getBoundingClientRect() const items: MenuItem[] = [{ heading: describeSource(src) }] - if (action.kind !== 'button' && action.kind !== 'hold') { + if (splitSource(src).dir) { + // An encoder turned for a button action: how it counts its clicks. + items.push( + { + label: 'Encoding', + submenu: ENCODINGS.filter((x) => x !== 'button' && x !== 'abs7' && x !== 'abs14').map((x) => ({ + label: ENCODING_LABELS[x], + hint: x === b.encoding ? '✓' : undefined, + onClick: () => edit((m) => setBinding(m, src, { encoding: x })), + })), + }, + { separator: true }, + ) + } else if (action.kind !== 'button' && action.kind !== 'hold') { items.push( { label: 'Encoding', @@ -266,7 +279,7 @@ export function MidiSettings({ onClose }: { onClose: () => void }) { Jog sensitivity void }) { 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 + + Buttons: press it, or turn an encoder a few clicks in this action's direction. + + Control With Shift
diff --git a/frontend/src/lib/midi/encoding.test.ts b/frontend/src/lib/midi/encoding.test.ts index 3a967c9..8090e40 100644 --- a/frontend/src/lib/midi/encoding.test.ts +++ b/frontend/src/lib/midi/encoding.test.ts @@ -21,6 +21,9 @@ describe('messages', () => { expect(parseSource('note:16:127')).toEqual({ kind: 'note', channel: 16, number: 127 }) expect(parseSource('cc:17:1')).toBeNull() expect(describeSource('cc:2:33')).toBe('CC 33 · Ch 2') + expect(describeSource('cc:1:20+')).toBe('CC 20 · Ch 1 ↻') + expect(parseSource('cc:1:20-')).toEqual({ kind: 'cc', channel: 1, number: 20 }) + expect(parseSource('note:1:20+')).toBeNull() // only a control that turns has a direction }) }) diff --git a/frontend/src/lib/midi/mapping.test.ts b/frontend/src/lib/midi/mapping.test.ts index 18af052..7d77155 100644 --- a/frontend/src/lib/midi/mapping.test.ts +++ b/frontend/src/lib/midi/mapping.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { ACTIONS, shiftDefault } from './actions' -import { bind, bindShift, emptyMapping, resolveBinding, sanitizeMapping, sourcesFor, unbind } from './mapping' +import { bind, bindShift, emptyMapping, resolveBinding, sanitizeMapping, setBinding, sourcesFor, unbind } from './mapping' describe('actions', () => { it('have unique ids', () => { @@ -53,6 +53,14 @@ describe('mapping', () => { const seven = bind(emptyMapping(), 'cc:1:0', 'abs7', 'normal', 'deck.A.pitch') expect(resolveBinding(seven, 'cc:1:32')).toBeNull() }) + it("an encoder's two directions share its encoding", () => { + let m = bind(emptyMapping(), 'cc:1:20+', 'rel64', 'normal', 'deck.A.sizeUp') + m = bind(m, 'cc:1:20-', 'relTwos', 'normal', 'deck.A.sizeDown') + expect(m.bindings['cc:1:20+'].encoding).toBe('relTwos') + m = setBinding(m, 'cc:1:20+', { encoding: 'relSignMag' }) + expect(m.bindings['cc:1:20-'].encoding).toBe('relSignMag') + expect(sanitizeMapping(m)?.bindings['cc:1:20-']).toEqual({ encoding: 'relSignMag', normal: 'deck.A.sizeDown' }) + }) it('sanitises what prefs or a file hold', () => { const m = sanitizeMapping({ version: 1, @@ -69,5 +77,7 @@ describe('mapping', () => { expect(m?.jogSensitivity).toBe(10) expect(Object.keys(m!.bindings)).toEqual(['note:1:0']) expect(sanitizeMapping({ version: 2 })).toBeNull() + expect(sanitizeMapping({ version: 1, jogSensitivity: 0.05 })?.jogSensitivity).toBe(0.05) + expect(sanitizeMapping({ version: 1, jogSensitivity: 0.01 })?.jogSensitivity).toBe(0.05) }) }) diff --git a/frontend/src/lib/midi/mapping.ts b/frontend/src/lib/midi/mapping.ts index 78808ce..348da30 100644 --- a/frontend/src/lib/midi/mapping.ts +++ b/frontend/src/lib/midi/mapping.ts @@ -6,7 +6,7 @@ import { actionDef, shiftDefault } from './actions' import { ENCODINGS, isFourteenBit, type Encoding } from './encoding' -import { parseSource, type SourceKey } from './messages' +import { parseSource, splitSource, turnSource, type SourceKey } from './messages' export type Layer = 'normal' | 'shift' @@ -47,7 +47,7 @@ export function sanitizeMapping(raw: unknown): Mapping | null { 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.jogSensitivity = num(r.jogSensitivity, 0.05, 10, DEFAULT_JOG_SENSITIVITY) out.scrubSpeed = num(r.scrubSpeed, 1, 64, DEFAULT_SCRUB_SPEED) const bindings = r.bindings && typeof r.bindings === 'object' ? (r.bindings as Record) : {} for (const [key, b] of Object.entries(bindings)) { @@ -110,7 +110,13 @@ export function bind(m: Mapping, source: SourceKey, encoding: Encoding, layer: L 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 } } + const bindings = { ...cleared.bindings, [source]: next } + // An encoder's two directions are one control, decoded once: they share + // its encoding. + const { base, dir } = splitSource(source) + const other = dir && bindings[turnSource(base, dir === '+' ? '-' : '+')] + if (dir && other) bindings[turnSource(base, dir === '+' ? '-' : '+')] = { ...other, encoding } + return { ...cleared, shift: cleared.shift === source ? null : cleared.shift, bindings } } /** Make `source` the Shift control (it then does nothing else). */ @@ -123,7 +129,12 @@ export function bindShift(m: Mapping, source: SourceKey): Mapping { 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 } } } + const bindings = { ...m.bindings, [source]: { ...b, ...patch } } + // A directional turn's encoding is its encoder's: both directions follow. + const { base, dir } = splitSource(source) + const otherKey = dir && turnSource(base, dir === '+' ? '-' : '+') + if (otherKey && bindings[otherKey] && patch.encoding) bindings[otherKey] = { ...bindings[otherKey], encoding: patch.encoding } + return { ...m, bindings } } /** diff --git a/frontend/src/lib/midi/messages.ts b/frontend/src/lib/midi/messages.ts index 0b1cb5d..39a47ca 100644 --- a/frontend/src/lib/midi/messages.ts +++ b/frontend/src/lib/midi/messages.ts @@ -42,20 +42,39 @@ export function sourceKey(m: Pick): return m.kind === 'pb' ? `pb:${m.channel}` : `${m.kind}:${m.channel}:${m.number}` } +/** + * An encoder's TURN in one direction, bound to a button action (decided + * 2026-11-03: controllers put beat jump and loop size on encoders): the + * source key plus `+` (clockwise / up) or `-`. Each tick fires the action once. + */ +export type TurnDirection = '+' | '-' + +export const turnSource = (base: SourceKey, dir: TurnDirection): SourceKey => `${base}${dir}` + +/** The physical control of a (possibly directional) source, and its direction. */ +export function splitSource(key: SourceKey): { base: SourceKey; dir: TurnDirection | null } { + const last = key.at(-1) + return last === '+' || last === '-' ? { base: key.slice(0, -1), dir: last } : { base: key, dir: null } +} + export function parseSource(key: SourceKey): Pick | null { - const [kind, ch, num] = key.split(':') + const { base, dir } = splitSource(key) + const [kind, ch, num] = base.split(':') const channel = Number(ch) if (!(channel >= 1 && channel <= 16)) return null - if (kind === 'pb') return { kind, channel, number: 0 } + if (kind === 'pb') return dir ? null : { kind, channel, number: 0 } const number = Number(num) if ((kind !== 'note' && kind !== 'cc') || !(number >= 0 && number <= 127)) return null + // Only a control that turns has a direction. + if (dir && kind !== 'cc') return null return { kind, channel, number } } -/** "Note 11 · Ch 1", "CC 33 · Ch 2", "Pitch bend · Ch 1". */ +/** "Note 11 · Ch 1", "CC 33 · Ch 2", "Pitch bend · Ch 1", "CC 20 · Ch 1 ↻". */ export function describeSource(key: SourceKey): string { const s = parseSource(key) if (!s) return key const what = s.kind === 'pb' ? 'Pitch bend' : s.kind === 'note' ? `Note ${s.number}` : `CC ${s.number}` - return `${what} · Ch ${s.channel}` + const dir = splitSource(key).dir + return `${what} · Ch ${s.channel}${dir === '+' ? ' ↻' : dir === '-' ? ' ↺' : ''}` } diff --git a/frontend/src/lib/midi/router.test.ts b/frontend/src/lib/midi/router.test.ts index 4ea152b..03ec9a8 100644 --- a/frontend/src/lib/midi/router.test.ts +++ b/frontend/src/lib/midi/router.test.ts @@ -184,6 +184,65 @@ describe('learning', () => { cc(40, 3) expect(A.calls).toEqual(['jogTurn 5 1']) }) + it('an encoder turned for button actions binds each direction, in either layer', async () => { + vi.useFakeTimers() + try { + const turn = (vals: number[]) => { + for (const v of vals) router.receive(PORT, [0xb0, 20, v]) + vi.advanceTimersByTime(500) + } + armLearn({ action: 'deck.A.sizeUp', layer: 'normal' }) + turn([65, 65, 65]) + armLearn({ action: 'deck.A.sizeDown', layer: 'normal' }) + turn([63, 63]) + armLearn({ action: 'deck.A.jumpFwd', layer: 'normal' }) + note(63, 127) // the controller's Shift held: the Shift layer + turn([65, 66]) + note(63, 0) + const b = getMidiState().mappings[PORT].bindings + expect(b['cc:1:20+']).toMatchObject({ encoding: 'rel64', normal: 'deck.A.sizeUp', shift: 'deck.A.jumpFwd' }) + expect(b['cc:1:20-']).toMatchObject({ encoding: 'rel64', normal: 'deck.A.sizeDown' }) + expect(b['cc:1:20']).toBeUndefined() + + cc(20, 65) // one click up + cc(20, 61) // three clicks down at once + note(63, 127) + cc(20, 65) + cc(20, 63) // Shift + down: no Shift action -> the normal one + expect(A.calls).toEqual(['stepSize 1', 'stepSize -1', 'stepSize -1', 'stepSize -1', 'move 1', 'stepSize -1']) + } finally { + vi.useRealTimers() + } + }) + it("a CC button pressed (and released) while learning stays a button", () => { + vi.useFakeTimers() + try { + armLearn({ action: 'deck.A.loopToggle', layer: 'normal' }) + cc(70, 127) + cc(70, 0) + vi.advanceTimersByTime(500) + armLearn({ action: 'deck.A.loopIn', layer: 'normal' }) + cc(71, 127) // held past the window + vi.advanceTimersByTime(500) + const b = getMidiState().mappings[PORT].bindings + expect(b['cc:1:70']).toMatchObject({ encoding: 'button', normal: 'deck.A.loopToggle' }) + expect(b['cc:1:71']).toMatchObject({ encoding: 'button', normal: 'deck.A.loopIn' }) + } finally { + vi.useRealTimers() + } + }) + it("a two's-complement encoder turned down (127s) is a turn, not a button", () => { + vi.useFakeTimers() + try { + armLearn({ action: 'deck.A.jumpBack', layer: 'normal' }) + cc(72, 127) + cc(72, 127) + vi.advanceTimersByTime(500) + expect(getMidiState().mappings[PORT].bindings['cc:1:72-']).toMatchObject({ encoding: 'relTwos', normal: 'deck.A.jumpBack' }) + } finally { + vi.useRealTimers() + } + }) it('the Shift control itself', () => { armLearn({ action: 'shift' }) note(70, 127) diff --git a/frontend/src/lib/midi/router.ts b/frontend/src/lib/midi/router.ts index 7bbe492..4bcdf45 100644 --- a/frontend/src/lib/midi/router.ts +++ b/frontend/src/lib/midi/router.ts @@ -14,8 +14,8 @@ 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 { bind, bindShift, resolveBinding, type Binding, type Layer, type Mapping } from './mapping' +import { parseMessage, sourceKey, splitSource, turnSource, type MidiMessage, type SourceKey } from './messages' import { armLearn, getMidiState, patchMidi, updateMapping, type LearnTarget } from './store' import type { Track } from '../../api' import type { DeckShortcuts } from '../deckKeys' @@ -70,8 +70,11 @@ export const EMPTY_TARGETS: MidiTargets = { 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 +/** A CC learned for a button waits this long: for a note-on (a touch jog sends + * both), or for more messages showing it is an encoder being turned. */ +const LEARN_CC_BUTTON_MS = 400 +/** A fast encoder turn may report several ticks at once; never more repeats. */ +const MAX_TURN_REPEAT = 8 const learnKind = (k: ActionKind | 'shift'): LearnKind => k === 'continuous' ? 'continuous' : k === 'jog' ? 'jog' : 'button' @@ -126,7 +129,17 @@ export class MidiRouter { return } if (!mapping) return + const shift = !!this.shiftHeld.get(port) const hit = resolveBinding(mapping, key) + // An encoder whose turns are bound by direction. The plain binding wins + // where it has an action for this layer; else the turns do. + const plus = mapping.bindings[turnSource(key, '+')] + const minus = mapping.bindings[turnSource(key, '-')] + if (plus || minus) { + const plainHere = hit && (shift ? hit.binding.shift : hit.binding.normal) + const turnHere = shift ? (plus?.shift ?? minus?.shift) : (plus?.normal ?? minus?.normal) + if (!plainHere && (turnHere || !hit)) return this.turn(port, m, key, plus ?? minus!, shift, mapping) + } if (!hit) return const { binding, isLsb } = hit const decKey = `${port}|${hit.key}` @@ -148,12 +161,33 @@ export class MidiRouter { } return } - const action = this.shiftHeld.get(port) ? (binding.shift ?? binding.normal) : binding.normal + const action = shift ? (binding.shift ?? binding.normal) : binding.normal if (!action) return if (d.type === 'press' && actionDef(action)?.kind === 'hold') this.held.set(heldKey, action) this.run(action, d, mapping.jogSensitivity, mapping.scrubSpeed) } + /** One message from an encoder bound by direction: each tick fires that + * direction's action once (a hold is pressed and released). */ + private turn(port: string, m: MidiMessage, key: SourceKey, any: Binding, shift: boolean, mapping: Mapping): void { + const decKey = `${port}|${key}~turn` + let dec = this.decoders.get(decKey) + if (!dec || dec.encoding !== any.encoding) { + dec = new Decoder(any.encoding) + this.decoders.set(decKey, dec) + } + const d = dec.feed(m) + if (!d || d.type !== 'delta') return + const b = mapping.bindings[turnSource(key, d.ticks > 0 ? '+' : '-')] + const action = b && (shift ? (b.shift ?? b.normal) : b.normal) + if (!action) return + const hold = actionDef(action)?.kind === 'hold' + for (let i = 0; i < Math.min(Math.abs(d.ticks), MAX_TURN_REPEAT); i++) { + this.run(action, { type: 'press', down: true }, mapping.jogSensitivity, mapping.scrubSpeed) + if (hold) this.run(action, { type: 'press', down: false }, mapping.jogSensitivity, mapping.scrubSpeed) + } + } + /** Forget held controls and decoder state (a controller unplugged). */ forget(port: string): void { this.shiftHeld.delete(port) @@ -290,14 +324,21 @@ export class MidiRouter { 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). + if (m.kind === 'note') { + if (m.value > 0) this.commit(c, port, key, 'button') + return + } + if (m.kind !== 'cc') return + // A CC is either a button or an ENCODER turned for this action's + // direction: wait and see what else it sends (and whether a note-on + // follows — a touch jog sends both). + if (!c.source) { + if (m.value === 0) return c.port = port c.source = key - c.timer = setTimeout(() => this.commit(c!, port, key, 'button'), LEARN_CC_BUTTON_MS) + c.timer = setTimeout(() => this.finishButton(), LEARN_CC_BUTTON_MS) } + if (key === c.source) c.samples.push(m) return } // A position or ticks: notes (a jog's touch sensor, a stray pad) do not count. @@ -315,6 +356,28 @@ export class MidiRouter { if (c.samples.length >= LEARN_SAMPLES) this.finish() } + /** + * A CC learned for a button action: a press (one message, or a press and a + * release to 0) binds as a button; several non-zero messages are an encoder + * TURNED, bound to the direction it went (decided 2026-11-03: controllers + * put beat jump and loop size on encoders). + */ + private finishButton(): void { + const c = this.capture + if (!c || !c.port || !c.source) return + const vals = c.samples + if (vals.length < 2 || vals.some((v) => v.value === 0)) return this.commit(c, c.port, c.source, 'button') + const enc = detectEncoding(vals, 'jog') + const dec = new Decoder(enc) + let ticks = 0 + for (const v of vals) { + const d = dec.feed(v) + if (d?.type === 'delta') ticks += d.ticks + } + if (ticks === 0) return this.commit(c, c.port, c.source, 'button') + this.commit(c, c.port, turnSource(c.source, ticks > 0 ? '+' : '-'), enc) + } + /** Commit a continuous / jog capture now (its window ran out). */ finish(): void { const c = this.capture @@ -338,6 +401,7 @@ export class MidiRouter { patchMidi({ learned: { port, action: t.action, layer: c.layer, at: performance.now() } }) } this.decoders.delete(`${port}|${source}`) + this.decoders.delete(`${port}|${splitSource(source).base}~turn`) armLearn(null) } }