Controllers and musical signals

Use one controller access and learning flow over gamepad and MIDI inputs, map gestures to music and inspect requested MIDI.

Use maruaudio/controllers for one device list and input-learning flow over gamepad and MIDI inputs. A module face consumes the host's face.controllers service. The controller layer supplies device and control data; your instrument owns the musical meaning of each gesture.

The library supplies reusable input and mapping tools. Gamepad Chords is the playable harmony example; Controller MIDI is the separate utility for mapping controls to notes, CC and pitch bend, and transposing MIDI input. Controller inspection belongs in setup rather than the musical performance view. Gamepad Chords consumes a spatial gamepad layout; Controller MIDI learns either input kind through the shared access service.

These exports are part of the source SDK. Use a Maru SDK build that includes them; their presence here does not establish a published npm version or native controller support inside a DAW.

Choose how input reaches the app

A browser can capture a paired gamepad directly; native hosts need their own adapter. MIDI conversion produces messages for an existing destination, rather than creating a virtual port or background service. These focused guides cover the connection, assignment and diagnostic decisions:

Your taskRead
Play the examples and edit your first MIDI assignmentPlay music with a game controller
Choose browser, native or relay inputChoose a controller connection
Connect physical controls, assignments and visualsController mappings and feedback
Diagnose missing input, levels, stuck notes or feedbackTroubleshoot controller input

Open the source examples

From the Maru workspace root, start each example in its own terminal:

sh
pnpm module:dev modules/gamepad-chords --silent --port 0
pnpm module:dev modules/controller-midi --silent --port 0

Each command prepares the shared workbench and prints its local URL. Port 0 chooses a free port without replacing another server. Keep the terminals running, open those URLs and select Unmute when you want audible output. Local workbench preparation needs no website publication. Module app publication is a separate operation described in Publishing.

Choose the import

ts
import {
  createGamepadInput,
  normalizeGamepad,
  identifyGamepad,
  GAMEPAD_BUTTON_IDS,
  type GamepadFrame,
} from "maruaudio/controllers"

createGamepadInput owns browser capture and selection. normalizeGamepad converts a browser-shaped sample to a copied standard frame; it is also useful in tests. identifyGamepad supplies a conservative family hint for labels. GAMEPAD_BUTTON_IDS lists the standard positional button IDs in index order.

Existing MIDI-controller profile and bridge helpers are available through maruaudio/controllers/midi. Use that entry for MIDI device dialects and messages. Gamepads can drive musical actions directly, or use the shared signal-to-MIDI mapper when your destination expects MIDI.

You want to…Use
Connect gamepad and MIDI devices through one host APIcreateControllerInput
Read ordered input and learn controls in a module faceface.controllers, ControllerSignalLearner
Capture a gamepad in a hostcreateGamepadInput
Read a spatial gamepad layout in a module faceface.gamepad
Adapt gamepad, channel MIDI or measured custom inputsgamepadSignalFrame, MidiControllerSignals, ControllerSignalFrame
Show available signal choices or learn a gesturecontrollerSignalDescriptors, ControllerSignalLearner
Turn a press into an application actionControllerSignalEdgeTracker
Send notes, CC or pitch bend through your existing transportControllerSignalMidiMapper
Run module-owned logic against named input rolesControllerInputSession, ControllerInputApp, ControllerInputAssignments
Track final MIDI admission and owned cleanupControllerMidiOutput

Connect either kind of input

ts
import { createControllerInput } from "maruaudio/controllers"

const input = createControllerInput()
const unsubscribe = input.subscribe(({ state, midi }) => {
  // Deliver input to the app here, independently of UI rendering.
  // state.controls describes named signals; state.frame holds their values.
  // midi preserves observed MIDI messages, including identical repeated notes.
})

// In your Connect button's handler:
await input.connect()
input.select(input.state.devices[0]?.id ?? null)

// On teardown:
unsubscribe()
input.dispose()

This code belongs to the host. Faces declare device.controllers/1 and subscribe to face.controllers; they do not open devices themselves. The connection UI can list devices together and offer one Learn action, with the browser's MIDI permission request handled when the person connects. Denied MIDI access does not disable available gamepad input. Names label devices; opaque attachment IDs distinguish same-named units and stay out of presets.

Continuous gamepad travel retains its precision. MIDI signals preserve their channel/address names, such as ch1.note60 or ch16.cc74; they are not given invented gamepad button indices. Snapshots support drawing and learning; subscribe to ordered input for musical dispatch rather than relying on a React render to observe each gesture. Browser polling still limits which gamepad changes can be observed.

Controller MIDI offers 32 editable assignments and uses the same Note/CC/bend editor for both input kinds. Its route parameters share through the host's existing preset menu. Device selection, output destination and arming stay local. MIDI requests enter the module Processor before transposition; local acceptance does not mean an external instrument received the message.

Hosts that already route hardware MIDI must provide the access service with their scoped input reservation, so a selected control does not send both its original and mapped MIDI into the same app. The audio session asks you to release held notes/sustain and center bend before reserving that input; other ports and saved input settings remain independent.

Reuse module logic in a local host

ControllerInputSession borrows an acquired input and feeds a module-owned app. It applies named role assignments, preserves observed MIDI note activity, and resets the app when its source withdraws. It opens no devices or audio engine. The app's handle(event, assigned) receives the ordered original event and a calibrated role frame; reset() releases its output.

ts
import {
  ControllerInputSession,
  type ControllerInputApp,
  type ControllerInputSurface,
} from "maruaudio/controllers"

export function attachPractice(app: ControllerInputApp, input: ControllerInputSurface) {
  const session = new ControllerInputSession(app, {
    south: { signal: "ch1.note60" },
    rightTrigger: { signal: "ch1.cc11" },
    leftStickX: { signal: "ch1.bend" },
  })
  session.attach(input)
  if (!session.state.active) throw new Error(session.state.error ?? "Controller input failed")
  return session // The host calls session.stop() before releasing its output.
}

Role values use 0–1 after calibration. Optional attacks and releases lists identify roles addressed by an observed MIDI note-on/off, including identical repeated attacks and quiet notes. A held connection snapshot contains no such attack; neither do CC or pressure changes. A channel's all-notes-off also withdraws its assigned note roles. Keep those events in the musical handler; React can separately display the latest values.

Controller MIDI's source adapter is createControllerMidiApp; Gamepad Chords supplies createGamepadChordsApp and createGamepadChordsMidiApp. Their source development guides contain exact source imports, host composition and editable configuration examples. They reuse each module's own mapping, harmony and processing behavior; these example adapters are separate from the public SDK import above.

MIDI apps expose a final admission state and bounded settle() operation. Stop input first, settle cleanup, inspect pending/debt, then let the host flush and close its destination. Keep failed cleanup bound to the old destination; a new output cannot discharge it. Local acceptance is separate from an actual receiving instrument's MIDI monitor.

The local source runner supplies supervised SDL3 capture and an independent MIDI worker for these two apps. Its source distribution includes the local controller-app setup and shutdown guide. A packaged standalone instrument still needs its host's own input/audio integration.

Capture a spatial gamepad layout

The following code belongs to a host or independent app. Call its start and stop functions from your own UI. Supply an onFrame function that interprets the controls and a releaseOwnedNotes function that stops notes this input started.

ts
import { createGamepadInput, type GamepadFrame } from "maruaudio/controllers"

export function connectController(
  onFrame: (frame: GamepadFrame) => void,
  releaseOwnedNotes: () => void
) {
  const input = createGamepadInput()
  const unsubscribe = input.subscribe(() => {
    const { frame } = input.state
    if (frame) onFrame(frame)
    else releaseOwnedNotes()
  })

  return {
    start: () => input.setEnabled(true),
    select: (index: number | null) => input.select(index),
    read: () => input.state,
    stop: () => input.setEnabled(false),
    dispose() {
      input.dispose()
      unsubscribe()
      releaseOwnedNotes()
    },
  }
}

Start capture from a person's action. Use HTTPS or localhost, pair the device through the operating system and press a controller button while the page has focus. Browser discovery can wait for that button press. Embedded hosts must permit the browser's gamepad Permissions Policy.

The session lists connected devices and chooses a supported controller automatically. Select a device by its connection index; pass null to return to automatic choice. An index or display name is not a permanent device ID. Dispose the session when its host is removed. Browser sessions share polling; input polling is not an audio sample clock.

Consume input in a module face

Declare the optional device.gamepad/2 UI capability and use the handle your host provides. A host without that capability omits face.gamepad; render an unavailable state rather than opening browser devices from the face.

ts
const input = face.gamepad
input?.setEnabled(true) // from an Enable controller button
input?.select(0) // from the person's device choice

const frame = input?.state.frame
const rightTrigger = frame?.buttons.rightTrigger.value ?? 0
const pitchGesture = frame?.leftStick.x ?? 0

Read fresh state on each update. Do not keep a handle captured from an old render. Route resulting notes through face.onNoteOn and face.onNoteOff; use face.setParam for declared parameter changes. The face does not create an audio engine or a second MIDI device route. Follow Module UI for host-controlled values and shared controls.

Interpret controls

InputMeaning
south, east, west, northPhysical face-button positions
dpadUp, dpadDown, dpadLeft, dpadRightIndependent direction buttons
leftTrigger, rightTriggerProgressive value in 0–1, plus pressed and touched
leftBumper, rightBumperShoulder buttons
leftStick, rightStick in frame.buttonsStick clicks
frame.leftStick, frame.rightStick{ x, y } in −1–1; right and down positive
select, start, homeCenter/system buttons; home can be absent on the device

Use value for trigger expression, rather than converting travel to the pressed boolean. Stick values use a radial 0.12 dead zone and are rescaled continuously outside it. normalizeGamepad(raw, { deadZone: 0.2 }) chooses another value for a standalone normalization call.

Default semantic frames require mapping === "standard", at least sixteen buttons and four axes. An explicit measured profile can interpret a nonstandard layout. Recognizing DualSense, DualShock 4 or Xbox text changes the family hint; it cannot establish that measured mapping. Use spatial names in bindings and familiar printed legends in your artwork. The Gamepad specification defines the browser standard ordering.

React to edges: one press starts one note, one release ends it. Store the actual pitch assigned at note-on. If a D-pad gesture selects a new chord while a tone is held, release the original pitch. Release every note your input owns on a null frame, device change, disconnect, blur, page hide, disable and unmount. Require a fresh press after reconnecting instead of treating an already-held button as a new attack.

Calibrate different controller layouts

GAMEPAD_MAPPING_PRESETS includes browser-standard PlayStation 5, PlayStation 4, Xbox and generic profiles. All use the same W3C positional mapping; they require the browser to report a complete standard layout. Selecting a PlayStation label never guesses an unknown raw HID layout.

Other brands, including Switch-compatible pads, use the generic spatial layout when the browser supplies the same complete standard mapping. A digital trigger remains 0 or 1; progressive expression needs a control that supplies intermediate values. Sparse arcade or accessibility controllers can use an explicit measured profile. Actual device, browser and connection compatibility still needs a physical test.

For a nonstandard controller, inspect the raw values first. Record the index, resting value, direction and full travel of each physical control. Build an explicit profile with that evidence and validate it before applying:

ts
import { decodeGamepadMappingProfile } from "maruaudio/controllers"

const measured = decodeGamepadMappingProfile({
  version: 1,
  id: "my-measured-controller",
  name: "My measured layout",
  deadZone: 0.12,
  buttons: {
    south: { source: "button", index: 3, min: 0, max: 1 },
    leftTrigger: { source: "axis", index: 4, min: -1, max: 1 },
    rightTrigger: {
      source: "axis",
      index: 5,
      min: -1,
      max: 1,
      invert: true,
      deadZone: 0.05,
    },
  },
  sticks: {
    leftStick: {
      x: { source: "axis", index: 1, min: -1, max: 1 },
      y: { source: "axis", index: 0, min: -1, max: 1, invert: true },
    },
  },
})

if (measured) face.gamepad?.setMapping(measured)
// Return to the browser's default interpretation:
face.gamepad?.setMapping(null)

Those indices are examples, not a mapping for a named product. In a standalone host, use the same setMapping methods on the createGamepadInput() session. Read state.mappingProfile to show the accepted profile, and frame.mappingProfileId to identify the interpretation of a frame. The raw device.mapping string remains the browser's actual value.

Profile fieldMeaning
version, id, nameVersion 1, a short stable profile ID and a readable name
buttonsPartial bindings for the seventeen positional button/trigger IDs
sticksOptional leftStick/rightStick, each with x and y bindings
Binding source, indexRaw button or axis, with its zero-based index
Binding min, maxMeasured ordered low/high endpoints; use inversion instead of swapping them
Binding invertReverse the normalized direction
Binding deadZoneRemove and rescale a trigger/button's resting interval after inversion
Binding thresholdButton activation threshold; retains the continuous value
Profile deadZoneRadial dead zone for both sticks
Binding activeValues, toleranceDiscrete observed values for a hat switch and its rounding tolerance

A trigger sent as a signed axis can therefore become a progressive 0–1 trigger. Missing bindings remain neutral. A missing inverted trigger never becomes an accidental full press.

For a combined D-pad hat axis, give each direction the observed values for that direction and its diagonals. For example, if your measured hat produces −1 for up and −0.75 for up-right, the up binding could contain both values and the right binding could also contain −0.75. This allows both directions to activate on a diagonal. These numbers are illustrative; measure your own controller. Check that the neutral value matches no direction.

The profile decoder enforces bounded data: raw button indices 0–63, axes 0–31, button ranges within 0–1, axis ranges within −1–1, thresholds within 0–1 and dead zones within 0–0.95. activeValues contains one to eight finite raw values; tolerance defaults to 0.025 and has a maximum of 0.25. Raw snapshots retain up to 64 buttons and 32 axes. The API exposes what the browser supplies within those bounds; it does not infer sensors or other device-specific interfaces.

Applying a mapping withdraws the old interpretation and cancels its feedback. Changing device selection, disconnecting, disabling capture or replacing the connection's identity/mapping clears it. Store the profile as the person's configuration, then apply it explicitly to the appropriate connection; neither a display name nor a connection index is permanent hardware identity. When the profile changes, release owned notes and require fresh presses even if the framework batches an intermediate null frame.

Inspect input before mapping music

Captured frames and raw snapshots include an identity with an opaque attachmentId and interpretation epoch. Reconnecting the same model in the same browser slot creates a new attachment. Mapping edits and focus suspension advance the epoch; suspension preserves calibration, while disconnecting or disabling capture clears it. state.withdrawal records why input was withdrawn. Compare the identity even when your view skipped the intermediate null frame, release old notes and require a fresh press. gamepadSignalFrame uses these fields for its sourceId, so the shared mapper and learner recognize replacement.

normalizeGamepad is a stateless measurement helper. Use the host's captured GamepadInputFrame and GamepadInputRawSnapshot for musical lifetimes; their identity is validated when it crosses the face bridge.

Show the selected device name and index, mapping and input status. Display normalized sticks and trigger travel beside a log of button transitions. state.raw contains a copied sample of the selected device's raw axes and buttons, including an unsupported layout. Use it for diagnosis; raw indices do not identify semantic controls by themselves. You may explicitly map them to MIDI or calibrate a semantic profile from their observed behavior.

A useful test sequence is press/release, stick centers, full stick travel, gradual trigger travel, unplug while held, device switch and page hide. Keep observed hardware, synthetic tests and manually confirmed behavior separate. A fractional trigger value arriving in a test does not prove the same device works through Bluetooth on another browser.

Use the shared inspector in a module face:

tsx
import { GamepadDebugPanel } from "maruaudio/ui/gamepad-debug"

;<GamepadDebugPanel
  surface={face.gamepad}
  onExport={(report) => saveControllerReport(report)}
  renderController={(frame) => <YourControllerArtwork frame={frame} />}
/>

saveControllerReport and YourControllerArtwork are application-supplied functions/components. Omit those optional props to use the inspector without custom artwork or report handling. Keep simulated test data separate from an observed hardware report.

Your controller SVG can use the same semantic IDs as the bindings. Painting, selection and musical annotations can then change independently of device capture. Keep input indicators distinct from outgoing feedback status: sending a request is different from observing the physical motor move.

Request optional feedback

Inspect input.state.feedback.supported before offering vibration. Start a brief effect from a person's action, and provide a stop control:

ts
const input = face.gamepad
if (input?.state.feedback.supported) {
  input.playFeedback({
    durationMs: 120,
    strongMagnitude: 0.2,
    weakMagnitude: 0.4,
  })
}
// From a Stop feedback action:
input?.stopFeedback()

The same methods are available on createGamepadInput() sessions. Magnitudes are normalized to 0–1; the host bounds duration to one second. Feedback is restricted to the active selected controller and is cancelled by input lifecycle changes. Read state.feedback.status for idle, playing, complete, unsupported or error, with an optional error message.

Capability and delivery depend on browser, OS, driver, controller and connection. A successful request does not establish physical vibration. The baseline does not supply adaptive trigger resistance, controller LEDs, gyroscope, touchpad, controller speaker or a native SDL backend. Those require separate device-aware integration.

For ideas about musical mappings and existing tools, read Create music apps with game controllers.

Configure MIDI without a synth

The source workspace includes the Controller MIDI module, a MIDI-in/MIDI-out configuration tool with no audio output. It monitors each exposed raw button and axis, saves note/CC/pitch-bend assignments with presets, and provides input range, inversion, threshold, channel, velocity and transposition controls.

Use the source workbench commands. Connect a controller, select an input, choose its MIDI action and enable mapping. Route its output into an instrument to hear it. The Unmapped preset is silent; the Buttons to notes · axes to CC preset provides starting assignments. MIDI-only transposition also works with no gamepad attached. This is a source-workspace example, not a claim of a published native plug-in or DAW controller backend.

Calibration & feedback opens the shared tools described above. Physical layout profiles describe what an input is; module mappings describe what musical MIDI message it produces. Preserve that distinction when building another app.

Import the shared signal-to-MIDI library

The mapping engine is reusable outside the configuration module. All source adapters produce ControllerSignalFrame objects: an explicit sourceId and a record of continuous values. gamepadSignalFrame(state) copies available raw and semantic inputs; MidiControllerSignals accumulates channel MIDI messages from a host-owned keyboard, pad, pedal or fader transport. A measured sensor or custom interface can supply the same frame directly.

ts
import {
  ControllerSignalMidiMapper,
  gamepadSignalFrame,
  type ControllerMidiBinding,
} from "maruaudio/controllers"

const routes: ControllerMidiBinding[] = [
  { id: "tone", signal: "semantic_south", output: { type: "note", note: 60 } },
  {
    id: "expression",
    signal: "semantic_rightTrigger",
    output: { type: "cc", controller: 11 },
  },
  {
    id: "bend",
    signal: "semantic_leftStick_x",
    min: -1,
    max: 1,
    output: { type: "pitchBend" },
  },
]
const mapper = new ControllerSignalMidiMapper(existingMidiOutput)
mapper.update(gamepadSignalFrame(controllerState), routes, {
  channel: 1,
  velocity: 100,
})
// On source loss, disable, blur, hide or teardown:
mapper.reset()

existingMidiOutput is the application's {send(status,data1,data2)} port; controllerState is fresh host input state. A module face uses its declared face.midiInput capability as that port and disables mapping when it is absent. This library does not acquire MIDI devices or bypass the Processor. Raw IDs are button0/axis0; spatial IDs include semantic_south and semantic_rightStick_y. Explicit raw routes require the person's measured layout.

Bindings use a unique ownership id, a source signal, optional input min/max and invert, an optional human channel 1–16, and one output:

OutputConfiguration
Notetype: "note", note 0–127, threshold default 0.5, optional fixed velocity or normalized velocitySignal
CCtype: "cc", controller 0–127, optional low/high in 0–127
Pitch bendtype: "pitchBend", optional low/high in 0–16383

The first frame suppresses connection-held presses. Configuration/source changes withdraw old gestures, and duplicate pitches retain ownership until the last binding releases. Cleanup releases notes, owned sustain and bend; ordinary CC values retain their last value. The bounded sent log contains requests, not delivery acknowledgements. Call these allocating helpers on the host/UI side, outside a compiled realtime callback.

MidiControllerSignals accepts handleMidi(status,data1,data2) and returns a copied snapshot(). Keys include ch1.note60, ch1.cc74, ch1.pressure60, ch1.pressure, ch1.program and ch1.bend, all normalized 0–1. Prime the mapper with a resting snapshot before feeding events. For MIDI note routes, use threshold: 1/127 so soft notes trigger and velocitySignal: "ch1.note60" to preserve velocity. Note-off and velocity-zero note-on release; CC120/123 clear that channel's notes. Create a new source identity for a replacement connection and reset the mapper on disconnect. Channel messages are supported; SysEx, system messages and MIDI 2.0 require a separate protocol adapter.

For actions such as shuffle chord set, use ControllerSignalEdgeTracker.update(frame, threshold) and respond to one pressed edge. calibrateControllerSignal(value,{min,max,invert}) converts a measured custom range to 0–1. An arbitrary input can therefore become either a musical action or MIDI through the same transport-independent signal boundary.

Learn an input without guessing its layout

Use controllerSignalDescriptors(frame) to populate a signal picker from the controls actually present. Descriptors contain signal, label, group, kind, min, max and an optional known neutral. A raw axis has no assumed resting position. These values describe the shared signal vocabulary; the selected physical profile still establishes the controller's layout.

ControllerSignalLearner captures the next fresh gesture while your mapping editor is disarmed:

ts
import {
  ControllerSignalLearner,
  gamepadSignalFrame,
} from "maruaudio/controllers"

const learner = new ControllerSignalLearner()
// From the person's Learn click, with routing disabled:
learner.start(gamepadSignalFrame(controllerState), { preference: "semantic" })
// On subsequent host snapshots:
const result = learner.update(gamepadSignalFrame(controllerState))
if (result.status === "learned") {
  const selectedSignal = result.candidates[0]!.signal
  // Present selectedSignal for review before enabling the route.
}
// On Cancel, blur, hide or teardown:
learner.cancel()

controllerState is your current host state, refreshed before each call. Starting with null waits for a resting frame; later disconnect or replacement cancels listening. Initially held buttons and known centered sticks must return to neutral before learning a fresh gesture. Raw axes with unknown neutral use movement from the starting value, so release them before starting or provide a measured neutral.

The default movement threshold is 25% of the signal's full range. Configure threshold, releaseThreshold, a signals allowlist, direction and measured ranges for your controls. Custom frames use normalized 0–1 values unless you provide a range such as {pedal: {min: 100, max: 900, neutral: 100}}. The learner never sends MIDI or changes your mapping automatically.

Preference semantic ignores raw mirrors when semantic controls are present; raw does the reverse. Use all to retain every candidate. Simultaneous eligible movements return ambiguous; show the candidates and resolve the person's choice with select(signal). A learned candidate includes its baseline, latest value, direction and observed min/max. One gesture does not prove full hardware travel. New or reappearing signal IDs establish a baseline before they can trigger learning, so a newly seen MIDI CC needs another movement.