Implemented midi support`

This commit is contained in:
patben8 committed 2026-11-03 22:56:19 +01:00
1 parent f55b8f06e4
commit 8d0817b39e
41 files changed
+2827 -26

No files matched your search

+128
View File
@@ -0,0 +1,128 @@
// Everything a controller can be mapped to. Buttons do what the deck keys do
// (lib/deckKeys.ts), so a key and a pad mean the same thing; the rest are the
// controls a keyboard has no equivalent for — pitch, jog, the mixer, browsing.
//
// Kinds: `button` acts on press; `hold` also on release (CUE and hotcue
// previews, jog touch); `continuous` takes a position (or relative ticks from
// an endless knob); `jog` takes ticks.
export type DeckId = 'A' | 'B'
export type ActionKind = 'button' | 'hold' | 'continuous' | 'jog'
export type ActionGroup = 'Deck A' | 'Deck B' | 'Mixer' | 'Library' | 'App'
export interface ActionDef {
id: string
label: string
group: ActionGroup
kind: ActionKind
}
/** Hotcue pads offered per deck (a platform's bank may be smaller: the deck ignores the rest). */
export const HOTCUE_ACTIONS = 8
export const STEM_ACTIONS = 4
function deckActions(d: DeckId): ActionDef[] {
const group: ActionGroup = `Deck ${d}`
const a = (id: string, label: string, kind: ActionKind = 'button'): ActionDef => ({
id: `deck.${d}.${id}`,
label,
group,
kind,
})
const range = (n: number) => Array.from({ length: n }, (_, i) => i + 1)
return [
a('play', 'Play / pause'),
a('cue', 'CUE', 'hold'),
a('sync', 'SYNC'),
a('keylock', 'Keylock'),
a('pitch', 'Pitch fader', 'continuous'),
a('jog', 'Jog wheel', 'jog'),
a('jogTouch', 'Jog touch (scratch)', 'hold'),
a('scrub', 'Fast scrub', 'jog'),
...range(HOTCUE_ACTIONS).map((n) => a(`hotcue.${n}`, `Hotcue ${n}`, 'hold')),
...range(HOTCUE_ACTIONS).map((n) => a(`hotcueErase.${n}`, `Erase hotcue ${n}`)),
a('jumpBack', 'Beat jump / move loop back'),
a('jumpFwd', 'Beat jump / move loop forward'),
a('markerPrev', 'Previous grid marker'),
a('markerNext', 'Next grid marker'),
a('sizeDown', 'Loop / jump size −'),
a('sizeUp', 'Loop / jump size +'),
a('sizeLoop', 'Loop (at size)'),
a('loopIn', 'Loop in'),
a('loopOut', 'Loop out'),
a('loopToggle', 'Loop on / off'),
...range(STEM_ACTIONS).map((n) => a(`stem.${n}`, `Mute stem ${n}`)),
...range(STEM_ACTIONS).map((n) => a(`stemSolo.${n}`, `Solo stem ${n}`)),
a('load', 'Load selected track'),
]
}
function channelActions(c: DeckId): ActionDef[] {
const a = (id: string, label: string, kind: ActionKind = 'continuous'): ActionDef => ({
id: `mixer.${c}.${id}`,
label: `${c}: ${label}`,
group: 'Mixer',
kind,
})
return [
a('gain', 'Gain'),
a('high', 'EQ high'),
a('mid', 'EQ mid'),
a('low', 'EQ low'),
a('filter', 'Filter'),
a('fxNext', 'Next effect', 'button'),
a('fxPrev', 'Previous effect', 'button'),
a('fader', 'Channel fader'),
]
}
export const ACTIONS: ActionDef[] = [
...deckActions('A'),
...deckActions('B'),
...channelActions('A'),
...channelActions('B'),
{ id: 'mixer.crossfader', label: 'Crossfader', group: 'Mixer', kind: 'continuous' },
{ id: 'library.browse', label: 'Browse tracks', group: 'Library', kind: 'jog' },
{ id: 'library.browsePress', label: 'Load to focused deck', group: 'Library', kind: 'button' },
{ id: 'library.tree', label: 'Browse playlists', group: 'Library', kind: 'jog' },
{ id: 'library.treePress', label: 'Open / close folder', group: 'Library', kind: 'button' },
{ id: 'app.performance', label: 'Performance mode on / off', group: 'App', kind: 'button' },
]
export const ACTION_GROUPS: ActionGroup[] = ['Deck A', 'Deck B', 'Mixer', 'Library', 'App']
const BY_ID = new Map(ACTIONS.map((a) => [a.id, a]))
export const actionDef = (id: string): ActionDef | undefined => BY_ID.get(id)
/**
* What a control does under Shift when nothing else is chosen: the keyboard's
* Shift meaning (hotcue -> erase it, stem -> solo it, beat jump -> step
* markers), plus Shift+jog = fast scrub and Shift+browse = the playlist tree
* (decided 2026-11-03). Filled in when the control is learned; overridable.
*/
export function shiftDefault(id: string): string | null {
const m = id.match(/^deck\.([AB])\.(.+)$/)
if (m) {
const [, d, rest] = m
const swap: Record<string, string> = { jumpBack: 'markerPrev', jumpFwd: 'markerNext', jog: 'scrub' }
if (swap[rest]) return `deck.${d}.${swap[rest]}`
const n = rest.match(/^(hotcue|stem)\.(\d+)$/)
if (n) return `deck.${d}.${n[1] === 'hotcue' ? 'hotcueErase' : 'stemSolo'}.${n[2]}`
return null
}
if (id === 'library.browse') return 'library.tree'
if (id === 'library.browsePress') return 'library.treePress'
return null
}
/** The deck an action belongs to, if any (mixer channels count as their deck). */
export function actionDeck(id: string): DeckId | null {
const m = id.match(/^(?:deck|mixer)\.([AB])\./)
return m ? (m[1] as DeckId) : null
}
/** Acts only in performance mode: deck B and the whole mixer (prep mode has
* one deck and plays past the mixer). */
export function performanceOnly(id: string): boolean {
return id.startsWith('mixer.') || actionDeck(id) === 'B'
}
+103
View File
@@ -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')
})
})
+175
View File
@@ -0,0 +1,175 @@
// How a control encodes what it does, and turning its raw values into
// something an action can use: a press, a position, or a number of ticks.
//
// Controllers disagree on everything here, so a binding stores its encoding
// (detected while learning — `detectEncoding` — and overridable in the editor):
// button a note or CC: any value > 0 = down, 0 = up
// abs7 a knob / fader, 0-127
// abs14 a 14-bit knob / fader: CC n (MSB) + CC n+32 (LSB), or pitch bend
// relTwos relative, two's complement: 1.. = +1.., 127.. = -1..
// rel64 relative, centred on 64: 65.. = +1.., 63.. = -1..
// relSignMag relative, sign + magnitude: 1.. = +1.., 65.. = -1..
// jogAbs7 a jog reporting its ABSOLUTE position, 7 bits, wrapping
// jogAbs14 the same at 14 bits (MSB/LSB pair, or pitch bend)
import type { MidiMessage } from './messages'
export const ENCODINGS = ['button', 'abs7', 'abs14', 'relTwos', 'rel64', 'relSignMag', 'jogAbs7', 'jogAbs14'] as const
export type Encoding = (typeof ENCODINGS)[number]
export const ENCODING_LABELS: Record<Encoding, string> = {
button: 'Button',
abs7: 'Absolute',
abs14: 'Absolute 14-bit',
relTwos: 'Relative (01 / 7F)',
rel64: 'Relative (41 / 3F)',
relSignMag: 'Relative (01 / 41)',
jogAbs7: 'Jog position',
jogAbs14: 'Jog position 14-bit',
}
/** Whether a 14-bit encoding pairs this CC with CC number + 32. */
export const isFourteenBit = (e: Encoding) => e === 'abs14' || e === 'jogAbs14'
/** What one message means once decoded. */
export type Decoded =
| { type: 'press'; down: boolean }
/** `unit` 0..1; `bipolar` -1..1 with the control's centre detent exactly 0. */
| { type: 'abs'; unit: number; bipolar: number }
| { type: 'delta'; ticks: number }
/** Two's-complement / centred / sign-magnitude value -> signed ticks. */
export function relativeTicks(encoding: Encoding, v: number): number {
switch (encoding) {
case 'relTwos':
return v < 64 ? v : v - 128
case 'rel64':
return v - 64
case 'relSignMag':
return v < 64 ? v : -(v - 64)
default:
return 0
}
}
/** The shortest signed step from position `prev` to `next` on a wheel of
* `size` positions: 120 -> 3 on a 7-bit jog is +11, not -117. */
export function wrapDelta(prev: number, next: number, size: number): number {
let d = (next - prev) % size
if (d > size / 2) d -= size
if (d < -size / 2) d += size
return d
}
/** A position on 0..max -> unit and bipolar, the centre value (max+1)/2
* mapping to exactly 0 (64 of 0-127: a knob's detent reads flat). */
export function absValue(raw: number, max: number): { unit: number; bipolar: number } {
const c = (max + 1) / 2
return { unit: raw / max, bipolar: raw < c ? (raw - c) / c : (raw - c) / (max - c) }
}
/**
* Decodes one control's messages. Keeps the state an encoding needs between
* them: the other half of a 14-bit pair, and an absolute jog's last position.
* One per bound source (the router keys them by port + source).
*/
export class Decoder {
private msb = 0
private lsb = 0
private lastPos: number | null = null
readonly encoding: Encoding
readonly invert: boolean
constructor(encoding: Encoding, invert = false) {
this.encoding = encoding
this.invert = invert
}
/** `isLsb`: the message is the CC n+32 half of a 14-bit pair. */
feed(m: MidiMessage, isLsb = false): Decoded | null {
const e = this.encoding
const flip = this.invert ? -1 : 1
if (e === 'button') return { type: 'press', down: m.value > 0 }
if (e === 'abs7') {
const v = absValue(m.value, 127)
return this.invert ? { unit: 1 - v.unit, bipolar: -v.bipolar, type: 'abs' } : { type: 'abs', ...v }
}
if (e === 'abs14' || e === 'jogAbs14') {
let pos: number
if (m.kind === 'pb') pos = m.value
else {
if (isLsb) this.lsb = m.value
else this.msb = m.value
pos = (this.msb << 7) | this.lsb
}
if (e === 'abs14') {
const v = absValue(pos, 16383)
return this.invert ? { unit: 1 - v.unit, bipolar: -v.bipolar, type: 'abs' } : { type: 'abs', ...v }
}
return this.jog(pos, 16384, flip)
}
if (e === 'jogAbs7') return this.jog(m.value, 128, flip)
const ticks = relativeTicks(e, m.value) * flip
return ticks === 0 ? null : { type: 'delta', ticks }
}
private jog(pos: number, size: number, flip: number): Decoded | null {
const prev = this.lastPos
this.lastPos = pos
if (prev == null) return null // the first position only sets where we are
const ticks = wrapDelta(prev, pos, size) * flip
return ticks === 0 ? null : { type: 'delta', ticks }
}
}
/** What the action being learned expects, which narrows the guess. */
export type LearnKind = 'button' | 'continuous' | 'jog'
/**
* Guess a control's encoding from the messages it sent while being learned
* (the user was asked to move it both ways). The tells:
* - Pitch bend, or CC n with CC n+32 interleaved, is 14-bit.
* - A relative control REPEATS values (65 65 65 while turning steadily) and
* stays in its zones (near 0 / 127, or near 64); an absolute one changes on
* every message and wanders across its range.
* - Which relative scheme: 63s mean centred on 64; 127s mean two's
* complement; 1s with 65s mean sign-magnitude; one direction only is
* ambiguous between schemes and falls back to the common one.
* Wrong guesses are rare and fixable in the editor.
*/
export function detectEncoding(samples: MidiMessage[], kind: LearnKind): Encoding {
if (kind === 'button' || samples.length === 0) return 'button'
const absolute = kind === 'jog' ? 'jogAbs' : 'abs'
const first = samples[0]
if (first.kind === 'pb') return `${absolute}14` as Encoding
if (first.kind === 'cc' && first.number < 32 && samples.some((m) => m.kind === 'cc' && m.number === first.number + 32)) {
return `${absolute}14` as Encoding
}
const vals = samples.filter((m) => m.kind === first.kind && m.number === first.number).map((m) => m.value)
let repeats = 0
for (let i = 1; i < vals.length; i++) if (vals[i] === vals[i - 1]) repeats++
const inZones = vals.every((v) => v <= 16 || v >= 112 || (v >= 48 && v <= 80))
const distinct = new Set(vals).size
// An absolute control moved both ways turns back once or twice; a relative
// one at varying speed jitters up and down all the time.
let reversals = 0
let lastSign = 0
for (let i = 1; i < vals.length; i++) {
const d = Math.sign(wrapDelta(vals[i - 1], vals[i], 128))
if (d === 0) continue
if (lastSign !== 0 && d !== lastSign) reversals++
lastSign = d
}
const relative = repeats >= 2 || (inZones && (distinct <= 6 || reversals > 2))
if (!relative) return `${absolute}7` as Encoding
const has = (lo: number, hi: number) => vals.some((v) => v >= lo && v <= hi)
if (has(48, 63)) return 'rel64'
if (has(112, 127)) return 'relTwos'
if (has(1, 16) && has(65, 80)) return 'relSignMag'
if (has(65, 80)) return 'rel64'
return 'relTwos'
}
+73
View File
@@ -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()
})
})
+143
View File
@@ -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<SourceKey, Binding>
/** Jog: scratch / nudge / scrub sensitivity (1 = the default feel). */
jogSensitivity: number
/** Fast scrub (Shift + jog) relative to an ordinary scrub. */
scrubSpeed: number
}
export type Mappings = Record<string, Mapping>
export const DEFAULT_JOG_SENSITIVITY = 1
export const DEFAULT_SCRUB_SPEED = 8
export function emptyMapping(): Mapping {
return { version: 1, 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<string, unknown>
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<string, unknown>) : {}
for (const [key, b] of Object.entries(bindings)) {
if (!parseSource(key) || !b || typeof b !== 'object') continue
const x = b as Record<string, unknown>
if (!ENCODINGS.includes(x.encoding as Encoding)) continue
const binding: Binding = { encoding: x.encoding as Encoding }
if (x.invert === true) binding.invert = true
if (typeof x.normal === 'string' && actionDef(x.normal)) binding.normal = x.normal
if (typeof x.shift === 'string' && actionDef(x.shift)) binding.shift = x.shift
if (binding.normal || binding.shift) out.bindings[key] = binding
}
return out
}
export function sanitizeMappings(raw: unknown): Mappings {
const out: Mappings = {}
if (!raw || typeof raw !== 'object') return out
for (const [port, m] of Object.entries(raw as Record<string, unknown>)) {
const clean = sanitizeMapping(m)
if (clean) out[port] = clean
}
return out
}
/** The sources bound to `action` in `layer`. */
export function sourcesFor(m: Mapping, action: string, layer: Layer): SourceKey[] {
return Object.entries(m.bindings)
.filter(([, b]) => b[layer] === action)
.map(([k]) => k)
}
/** Drop `action` from `layer` everywhere (and bindings left empty). */
export function unbind(m: Mapping, action: string, layer: Layer): Mapping {
const bindings: Record<SourceKey, Binding> = {}
for (const [k, b] of Object.entries(m.bindings)) {
const next = b[layer] === action ? { ...b, [layer]: undefined } : b
if (next.normal || next.shift) bindings[k] = next
}
return { ...m, bindings }
}
/**
* Learn: `source` now does `action` in `layer`. It REPLACES the action's
* previous control in that layer (learning means "this is the control for
* X"). Learning a control's normal action fills its Shift layer with the
* keyboard's Shift meaning when the Shift layer is empty. A control that was
* Shift stops being Shift.
*/
export function bind(m: Mapping, source: SourceKey, encoding: Encoding, layer: Layer, action: string): Mapping {
const cleared = unbind(m, action, layer)
const prev = cleared.bindings[source]
// A new encoding (another kind of control) leaves the other layer's action
// only if it still makes sense: same kind of encoding.
const sameKind = prev && (prev.encoding === 'button') === (encoding === 'button')
const next: Binding = { encoding, invert: prev?.invert, normal: sameKind ? prev?.normal : undefined, shift: sameKind ? prev?.shift : undefined }
next[layer] = action
if (layer === 'normal' && !next.shift) {
const d = shiftDefault(action)
if (d && sourcesFor(cleared, d, 'shift').length === 0) next.shift = d
}
if (!next.invert) delete next.invert
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<Binding>): 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
}
+61
View File
@@ -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<number>): MidiMessage | null {
if (bytes.length < 2) return null
const type = bytes[0] & 0xf0
const channel = (bytes[0] & 0x0f) + 1
const d1 = bytes[1] & 0x7f
const d2 = bytes.length > 2 ? bytes[2] & 0x7f : 0
switch (type) {
case 0x80:
return { kind: 'note', channel, number: d1, value: 0 }
case 0x90:
return { kind: 'note', channel, number: d1, value: d2 }
case 0xb0:
return { kind: 'cc', channel, number: d1, value: d2 }
case 0xe0:
return { kind: 'pb', channel, number: 0, value: d1 | (d2 << 7) }
default:
return null
}
}
export function sourceKey(m: Pick<MidiMessage, 'kind' | 'channel' | 'number'>): SourceKey {
return m.kind === 'pb' ? `pb:${m.channel}` : `${m.kind}:${m.channel}:${m.number}`
}
export function parseSource(key: SourceKey): Pick<MidiMessage, 'kind' | 'channel' | 'number'> | 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}`
}
+192
View File
@@ -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<typeof fakeDeck>
let B: ReturnType<typeof fakeDeck>
let targets: MidiTargets
let router: MidiRouter
const note = (n: number, v: number) => router.receive(PORT, [0x90, n, v])
const cc = (n: number, v: number) => router.receive(PORT, [0xb0, n, v])
function map(fn: (m: Mapping) => Mapping) {
replaceMappings({ [PORT]: fn(emptyMapping()) }, false)
}
beforeEach(() => {
A = fakeDeck()
B = fakeDeck()
targets = { ...EMPTY_TARGETS, decks: { A, B }, load: vi.fn(), browse: vi.fn() }
router = new MidiRouter(() => targets)
armLearn(null)
setMixer({ crossfader: 0 })
setChannel('A', { fader: 1, trim: 0, color: 0, fx: 'filter' })
map((m) => {
m = bindShift(m, 'note:1:63')
m = bind(m, 'note:1:11', 'button', 'normal', 'deck.A.play')
m = bind(m, 'note:1:0', 'button', 'normal', 'deck.A.hotcue.1')
m = bind(m, 'note:2:11', 'button', 'normal', 'deck.B.play')
m = bind(m, 'cc:1:33', 'rel64', 'normal', 'deck.A.jog')
m = bind(m, 'note:1:54', 'button', 'normal', 'deck.A.jogTouch')
m = bind(m, 'cc:1:0', 'abs14', 'normal', 'deck.A.pitch')
m = bind(m, 'cc:7:19', 'abs7', 'normal', 'mixer.A.fader')
m = bind(m, 'cc:7:31', 'abs7', 'normal', 'mixer.crossfader')
m = bind(m, 'cc:7:64', 'rel64', 'normal', 'library.browse')
return m
})
})
describe('router', () => {
it('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')
})
})
+343
View File
@@ -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<DeckId, DeckMidi | null>
togglePerformance: (() => void) | null
/** Load the track list's highlighted row into `deck`. */
load: ((deck: DeckId) => void) | null
/** Move the track list's highlight by `ticks` rows. */
browse: ((ticks: number) => void) | null
/** The track list's highlighted row (what `load` loads). */
lead: (() => Track | null) | null
/** The sidebar's playlist tree. */
tree: { step(ticks: number): void; press(): void } | null
}
export const EMPTY_TARGETS: MidiTargets = {
performance: false,
focused: 'A',
decks: { A: null, B: null },
togglePerformance: null,
load: null,
browse: null,
lead: null,
tree: null,
}
/** Messages a learn capture waits for before guessing an encoding. */
const LEARN_SAMPLES = 12
/** …or this long after the first one. */
const LEARN_WINDOW_MS = 800
/** A CC 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<typeof setTimeout> | null
}
export class MidiRouter {
private shiftHeld = new Map<string, boolean>()
private decoders = new Map<string, Decoder>()
private held = new Map<string, string>()
private capture: Capture | null = null
private lastActivity = 0
private targets: () => MidiTargets
constructor(targets: () => MidiTargets) {
this.targets = targets
}
/** Raw bytes from `port`. */
receive(port: string, bytes: ArrayLike<number>): void {
const m = parseMessage(bytes)
if (m) this.handle(port, m)
}
handle(port: string, m: MidiMessage): void {
const key = sourceKey(m)
const st = getMidiState()
// The settings dialog's activity line: a jog sends hundreds a second.
const now = performance.now()
if (now - this.lastActivity > 50) {
this.lastActivity = now
patchMidi({ activity: { port, source: key, value: m.value, at: now } })
}
const mapping = st.mappings[port]
// Shift: tracked always, and never an action of its own.
if (mapping?.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<string, keyof ChannelState> = { gain: 'trim', high: 'high', mid: 'mid', low: 'low', filter: 'color', fader: 'fader' }
const f = field[op]
if (!f) return
// Gain is ±TRIM_RANGE_DB, the fader 0..1, the rest -1..1 (centre flat).
const [lo, hi] = f === 'trim' ? [-TRIM_RANGE_DB, TRIM_RANGE_DB] : f === 'fader' ? [0, 1] : [-1, 1]
let v: number
if (d.type === 'abs') v = f === 'fader' ? d.unit : d.bipolar * hi
else if (d.type === 'delta') v = clamp((s[f] as number) + (d.ticks * (hi - lo)) / 128, lo, hi)
else return
setChannel(ch, { [f]: v })
}
// ---- learn ---------------------------------------------------------------------
private learn(port: string, m: MidiMessage, key: SourceKey, target: LearnTarget): void {
const kind = learnKind(target.action === 'shift' ? 'shift' : (actionDef(target.action)?.kind ?? 'button'))
let c = this.capture
if (!c || c.target !== target) {
if (c?.timer) clearTimeout(c.timer)
const layer: Layer = 'layer' in target ? (this.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)
}
}
+88
View File
@@ -0,0 +1,88 @@
// MIDI state the UI shows and the router reads, in one small external store
// read through useSyncExternalStore (as lib/audio/mixerState.ts is): the
// connected controllers, every controller's mapping, what is being learned and
// the last message seen (the settings dialog's activity line).
//
// Mappings are persisted by whoever installs `setPersist` (useMidi, through
// the shared prefs writer); everything else lives for the session.
import { useSyncExternalStore } from 'react'
import type { Layer, Mapping, Mappings } from './mapping'
import { emptyMapping } from './mapping'
import type { SourceKey } from './messages'
/** What Learn is waiting for: an action in a layer, or the Shift control itself. */
export type LearnTarget = { action: string; layer: Layer } | { action: 'shift' }
export interface MidiState {
/** Whether this build can read MIDI at all (desktop app, or a Web MIDI browser). */
available: boolean
/** Why MIDI could not be read (a browser refused access), else null. */
blocked: string | null
/** Connected controllers, by port name. */
ports: string[]
mappings: Mappings
/** Armed: the next control moved is bound to this. */
armed: LearnTarget | null
/** On-screen learn mode: clicking a control arms it. */
onScreen: boolean
/** The last binding learned (the on-screen mode flashes it). */
learned: { port: string; action: string; layer: Layer; at: number } | null
activity: { port: string; source: SourceKey; value: number; at: number } | null
}
let state: MidiState = {
available: false,
blocked: null,
ports: [],
mappings: {},
armed: null,
onScreen: false,
learned: null,
activity: null,
}
const listeners = new Set<() => void>()
let persist: ((m: Mappings) => void) | null = null
export function getMidiState(): MidiState {
return state
}
export function subscribeMidi(fn: () => void): () => void {
listeners.add(fn)
return () => listeners.delete(fn)
}
export function patchMidi(patch: Partial<MidiState>): void {
state = { ...state, ...patch }
for (const fn of listeners) fn()
}
export function setPersist(fn: ((m: Mappings) => void) | null): void {
persist = fn
}
/** Change one controller's mapping (created empty on first use) and save. */
export function updateMapping(port: string, fn: (m: Mapping) => Mapping): void {
const mappings = { ...state.mappings, [port]: fn(state.mappings[port] ?? emptyMapping()) }
patchMidi({ mappings })
persist?.(mappings)
}
export function replaceMappings(mappings: Mappings, save = true): void {
patchMidi({ mappings })
if (save) persist?.(mappings)
}
export function armLearn(target: LearnTarget | null): void {
patchMidi({ armed: target })
}
export function setOnScreenLearn(on: boolean): void {
patchMidi({ onScreen: on, armed: null })
}
/** A slice of the MIDI state, re-rendering only when it changes. */
export function useMidiState<T>(select: (s: MidiState) => T): T {
return useSyncExternalStore(subscribeMidi, () => select(state))
}
+29
View File
@@ -0,0 +1,29 @@
// What the router acts on, filled in by whoever is mounted to take it:
// PrepStrip (the decks, performance mode), App (loading), TrackTable (browse)
// and Sidebar (the playlist tree). Assigned on every render — as PrepStrip's
// `keys` ref is — so the router always sees the latest handlers.
//
// Unmounting clears only what THIS component last set: switching views
// renders the new table (which registers) before the old one's cleanup runs,
// and a blanket reset would wipe the newcomer's handlers.
import { useEffect, useRef } from 'react'
import { EMPTY_TARGETS, type MidiTargets } from './router'
export const midiTargets: MidiTargets = { ...EMPTY_TARGETS, decks: { A: null, B: null } }
export function useMidiTargets(patch: Partial<MidiTargets>): void {
Object.assign(midiTargets, patch)
const mine = useRef(patch)
mine.current = patch
useEffect(
() => () => {
const t = midiTargets as unknown as Record<string, unknown>
for (const [k, v] of Object.entries(mine.current)) {
if (t[k] !== v) continue
t[k] = k === 'decks' ? { A: null, B: null } : EMPTY_TARGETS[k as keyof MidiTargets]
}
},
[],
)
}
+89
View File
@@ -0,0 +1,89 @@
// Where MIDI comes from. The desktop app reads ports in the shell
// (src-tauri/src/midi.rs: WKWebView has no Web MIDI); a browser under
// `./dev.sh` uses Web MIDI (Chrome) — same interface, so nothing above here
// knows which. Neither (Safari, Firefox without the permission) = no MIDI.
export type OnBytes = (batch: ArrayLike<number>[]) => void
export interface MidiTransport {
ports(): Promise<string[]>
/** Start receiving; resolves to the function that stops it. */
open(port: string, onBytes: OnBytes): Promise<() => void>
}
/** "X", "X #2" for two identical controllers — the shell names them the same way. */
export function uniqueNames(names: string[]): string[] {
const seen = new Map<string, number>()
return names.map((n) => {
const k = (seen.get(n) ?? 0) + 1
seen.set(n, k)
return k === 1 ? n : `${n} #${k}`
})
}
function tauriTransport(): MidiTransport {
const core = () => import('@tauri-apps/api/core')
return {
ports: async () => (await core()).invoke<string[]>('midi_ports'),
open: async (port, onBytes) => {
const { invoke, Channel } = await core()
// A fresh Channel per open: Tauri ends one whose Rust side was dropped.
const ch = new Channel<{ wall_us: number; bytes: number[] }[]>()
ch.onmessage = (batch) => onBytes(batch.map((p) => p.bytes))
await invoke('midi_open', { port, onMessage: ch })
return () => void invoke('midi_close', { port }).catch(() => {})
},
}
}
function webMidiTransport(): MidiTransport {
// Chrome asks the user first. A refusal is not kept for good: after
// REASK_MS the poll asks again, so allowing MIDI in the site settings takes
// effect without a reload — but a dismissed prompt is not shown again at
// once (every 1.5 s would nag, and Chrome blocks a site after repeats).
const REASK_MS = 20_000
let access: Promise<MIDIAccess> | null = null
let refused: { at: number; error: unknown } | null = null
const get = () => {
if (refused && performance.now() - refused.at < REASK_MS) return Promise.reject(refused.error)
return (access ??= navigator.requestMIDIAccess({ sysex: false }).then(
(a) => ((refused = null), a),
(e: unknown) => {
access = null
refused = { at: performance.now(), error: e }
throw e
},
))
}
const inputs = async () => {
const list = [...(await get()).inputs.values()].filter((i) => i.state === 'connected')
const names = uniqueNames(list.map((i) => i.name ?? 'MIDI input'))
return list.map((input, k) => ({ input, name: names[k] }))
}
return {
ports: async () => (await inputs()).map((i) => i.name),
open: async (port, onBytes) => {
const hit = (await inputs()).find((i) => i.name === port)
if (!hit) throw new Error(`MIDI port not found: ${port}`)
const handler = (e: MIDIMessageEvent) => {
// System messages stay out, as the shell ignores them.
if (e.data && e.data[0] < 0xf0) onBytes([e.data])
}
hit.input.addEventListener('midimessage', handler)
// Only SETTING `onmidimessage` opens a port implicitly; a listener added
// with addEventListener does not, so open it ourselves.
await hit.input.open()
return () => {
hit.input.removeEventListener('midimessage', handler)
void hit.input.close().catch(() => {})
}
},
}
}
export function midiTransport(): MidiTransport | null {
if (typeof window === 'undefined') return null
if ('__TAURI_INTERNALS__' in window) return tauriTransport()
if (typeof navigator.requestMIDIAccess === 'function') return webMidiTransport()
return null
}
+101
View File
@@ -0,0 +1,101 @@
// MIDI for the whole app, mounted once (App): finds controllers as they come
// and go, feeds their messages to the router, and keeps the mappings in
// userprefs (`midiMappings`, through the shared debounced prefs writer).
//
// midir has no connect notifications (nor does every Web MIDI), so the port
// list is polled — cheap, and a newly plugged controller works within ~1.5 s.
import { useEffect, useRef } from 'react'
import { useQuery } from '@tanstack/react-query'
import { api } from '../../api'
import { usePrefsWriter } from '../prefs'
import { sanitizeMappings } from './mapping'
import { MidiRouter } from './router'
import { getMidiState, patchMidi, replaceMappings, setPersist } from './store'
import { midiTargets } from './targets'
import { midiTransport } from './transport'
const POLL_MS = 1500
/** The router every message goes through (one per app). */
export const midiRouter = new MidiRouter(() => midiTargets)
export function useMidi(onNotify: (kind: 'success' | 'warning', msg: string) => void): void {
const writePrefs = usePrefsWriter()
const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }).data
const hydrated = useRef(false)
const notify = useRef(onNotify)
notify.current = onNotify
// Mappings: hydrated once from prefs, then saved on every change.
useEffect(() => {
if (hydrated.current || !prefs) return
hydrated.current = true
replaceMappings(sanitizeMappings((prefs as { midiMappings?: unknown }).midiMappings), false)
setPersist((m) => writePrefs({ midiMappings: m }))
}, [prefs, writePrefs])
useEffect(() => () => setPersist(null), [])
useEffect(() => {
const transport = midiTransport()
if (!transport) return
patchMidi({ available: true })
const open = new Map<string, () => void>()
const opening = new Set<string>()
let first = true
let stopped = false
const poll = async () => {
let ports: string[]
try {
ports = await transport.ports()
if (getMidiState().blocked) patchMidi({ blocked: null })
} catch (e) {
// A browser refusing MIDI access (Chrome asks first): say so in the
// MIDI dialog rather than looking like no controller is plugged in.
const why = e instanceof Error ? e.message : String(e)
if (getMidiState().blocked !== why) patchMidi({ blocked: why })
return
}
if (stopped) return
for (const [port, close] of open) {
if (ports.includes(port)) continue
close()
open.delete(port)
midiRouter.forget(port)
}
for (const port of ports) {
if (open.has(port) || opening.has(port)) continue
opening.add(port)
// Ports present at launch connect quietly; later ones are news.
const announce = !first
transport
.open(port, (batch) => {
for (const bytes of batch) midiRouter.receive(port, bytes)
})
.then((close) => {
if (stopped) return close()
open.set(port, close)
if (!announce) return
const mapped = !!getMidiState().mappings[port]
notify.current(
mapped ? 'success' : 'warning',
mapped ? `${port} connected` : `${port} connected — not mapped yet (Settings ▸ MIDI Controllers…)`,
)
})
.catch(() => {})
.finally(() => opening.delete(port))
}
patchMidi({ ports })
first = false
}
void poll()
const t = setInterval(() => void poll(), POLL_MS)
return () => {
stopped = true
clearInterval(t)
for (const close of open.values()) close()
patchMidi({ ports: [] })
}
}, [])
}