Encoder direction can now be mapped to separate controls

This commit is contained in:
patben8 committed 2026-11-03 23:09:16 +01:00
1 parent 8d0817b39e
commit 5d4df2aa52
9 files changed
+216 -25

No files matched your search

+3
View File
@@ -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
})
})
+11 -1
View File
@@ -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)
})
})
+15 -4
View File
@@ -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<string, unknown>) : {}
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<Binding>): 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 }
}
/**
+23 -4
View File
@@ -42,20 +42,39 @@ export function sourceKey(m: Pick<MidiMessage, 'kind' | 'channel' | 'number'>):
return m.kind === 'pb' ? `pb:${m.channel}` : `${m.kind}:${m.channel}:${m.number}`
}
/**
* An encoder's TURN in one direction, bound to a button action (decided
* 2026-11-03: controllers put beat jump and loop size on encoders): the
* source key plus `+` (clockwise / up) or `-`. Each tick fires the action once.
*/
export type TurnDirection = '+' | '-'
export const turnSource = (base: SourceKey, dir: TurnDirection): SourceKey => `${base}${dir}`
/** The physical control of a (possibly directional) source, and its direction. */
export function splitSource(key: SourceKey): { base: SourceKey; dir: TurnDirection | null } {
const last = key.at(-1)
return last === '+' || last === '-' ? { base: key.slice(0, -1), dir: last } : { base: key, dir: null }
}
export function parseSource(key: SourceKey): Pick<MidiMessage, 'kind' | 'channel' | 'number'> | null {
const [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 === '-' ? ' ↺' : ''}`
}
+59
View File
@@ -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)
+74 -10
View File
@@ -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)
}
}