Metadata-Version: 2.4
Name: minimidi
Version: 0.2.0
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Rust
Classifier: Topic :: Multimedia :: Sound/Audio :: MIDI
Classifier: Typing :: Typed
License-File: LICENSE
Summary: Minimal Linux ALSA Raw MIDI output, with Python bindings via PyO3
Keywords: midi,alsa,linux,rust,pyo3
Author: minimidi authors
License: MIT
Requires-Python: >=3.13
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Changelog, https://github.com/ModularDevicesMalleableAudio/minimidi/blob/main/CHANGELOG.md
Project-URL: Homepage, https://github.com/ModularDevicesMalleableAudio/minimidi
Project-URL: Issues, https://github.com/ModularDevicesMalleableAudio/minimidi/issues

# minimidi

[![CI](https://github.com/ModularDevicesMalleableAudio/minimidi/actions/workflows/ci.yml/badge.svg)](https://github.com/ModularDevicesMalleableAudio/minimidi/actions/workflows/ci.yml)

Minimal Linux ALSA Raw MIDI **output**, written in Rust (PyO3), fully typed for Python 3.13+.

`minimidi` does one thing: open an ALSA Raw MIDI output port (`/dev/snd/midiC*D*`,
any port of a multi-port interface) write-only and send MIDI bytes to it. No input,
no sequencer scheduling, no cross-platform abstraction — just note-on / note-off / CC
helpers, whole-message SysEx, and a raw-bytes escape hatch, shipped as `abi3` wheels
with no system dependencies.

- **Linux only** (ALSA Raw MIDI).
- **Output only.**
- **Typed.** PEP 561 `py.typed` + hand-written stubs; clean under `mypy --strict`.
- **Thread-safe.** One port can be shared across Python threads; each call's bytes go
  out as one unit, and the GIL is released while waiting on the port or the kernel.
- **Never hangs on open.** A port another program holds raises `OSError(EBUSY)`.

See [`AGENTS.md`](./AGENTS.md) for developer / agent workflow instructions.

## Install

```bash
pip install minimidi
# or
uv add minimidi
```

Prebuilt `abi3` wheels (Python ≥3.13) for glibc (manylinux) on x86_64, aarch64,
and armv7 (32-bit Raspberry Pi OS), and for musl (Alpine, musllinux) on x86_64 and
aarch64 — no Rust toolchain or system packages needed. To install from source
instead (needs Rust stable):

```bash
pip install git+https://github.com/ModularDevicesMalleableAudio/minimidi
```

## Quick start

```python
import minimidi

with minimidi.RawMidiOut("VirMIDI", device=0) as port:
    port.note_on(channel=1, note=60, velocity=100)   # middle C on
    port.cc(channel=1, controller=74, value=64)      # filter cutoff
    port.note_off(channel=1, note=60)                # note off (velocity 0)
# port auto-closes on context exit
```

Channels are **1-indexed** (1–16), matching common MIDI convention. Notes,
velocities, controllers, and values are 0–127. Out-of-range arguments raise
`MinimidiError` before anything is written.

## Finding your card

Ports are addressed by ALSA card id (the bracketed name in `/proc/asound/cards`)
plus a raw device number:

```python
import minimidi

minimidi.list_cards()
# [(0, "PCH"), (1, "VirMIDI"), (3, "pisound")]

minimidi.find_card("pisound")
# 3 — raises MinimidiError if not present

port = minimidi.RawMidiOut("pisound", device=0)
# opens /dev/snd/midiC3D0 write-only
```

Card-id matching is exact and case-sensitive (ALSA's bracket padding is trimmed).
`device` is typically 0–3 for `snd-virmidi`; a non-existent device raises
`FileNotFoundError` at open time.

## Multi-port interfaces

A USB MIDI interface with several outputs exposes them as **subdevices** of one
raw device, not as separate devices. List them and pick one with `subdevice`:

```python
# Illustrative: a 4-output interface whose ALSA card id is "Quad".
minimidi.list_subdevices("Quad", device=0)
# [(0, "Quad MIDI 1"), (1, "Quad MIDI 2"), (2, "Quad MIDI 3"), (3, "Quad MIDI 4")]

port = minimidi.RawMidiOut("Quad", device=0, subdevice=2)   # third output
port.subdevice
# 2
```

Without `subdevice`, the kernel opens the first free port and `port.subdevice`
says which. Names come from the driver (`snd-virmidi` leaves them empty). A
`subdevice` beyond the device's port count raises `MinimidiError`.

Opening never blocks: if the port you asked for — or, without `subdevice`, every
port of the device — is open in another program, the constructor raises
`OSError` with `errno.EBUSY` instead of waiting for it to be released.

## Escape hatch: raw bytes

Messages without a first-class helper (pitch bend, program change, aftertouch, ...)
can be written verbatim:

```python
channel = 1
port.send_bytes(bytes([0xE0 | (channel - 1), 0x00, 0x40]))  # pitch bend, centre
```

`send_bytes` accepts only `bytes` (not `bytearray`/`memoryview`/`str`), length
1–1024, and performs **no MIDI semantic validation** — the caller owns correctness.

## SysEx

`send_sysex` writes one complete SysEx message of any length as a single unit, so
another thread's messages can never land inside it (splitting SysEx across
`send_bytes` calls gives no such guarantee):

```python
port.send_sysex(bytes([0xF0, 0x7E, 0x7F, 0x06, 0x01, 0xF7]))  # identity request
```

It must be `bytes` of the form `0xF0`, data bytes `0x00–0x7F`, `0xF7`; anything
else raises `MinimidiError` and writes nothing. Real-time bytes inside SysEx are
legal MIDI but rejected here — send them separately with `send_bytes`.

## Errors and recovery

| Condition | Exception |
|---|---|
| Unknown card id, out-of-range argument (incl. `subdevice`), malformed SysEx, write on closed port | `MinimidiError` |
| Device node missing | `FileNotFoundError` (`errno.ENOENT`) |
| No permission | `PermissionError` (`errno.EACCES`) |
| Port already open in another program | `OSError` (`errno.EBUSY`) |
| Card unplugged or driver unloaded, then written to | `OSError` (`errno.ENODEV`) |
| Non-`bytes` payload to `send_bytes` / `send_sysex` | `TypeError` |

OS errors are raised exactly as Python's own `open()`/`write()` would: the errno's
`OSError` subclass where one exists, with `.errno` always set (and `.filename` on
open). Errnos without a subclass — `EBUSY`, `ENODEV` — arrive as plain `OSError`,
so check `.errno`:

```python
import errno

try:
    port.note_on(channel=1, note=60, velocity=100)
except OSError as e:
    if e.errno == errno.ENODEV:
        port = minimidi.RawMidiOut("pisound")  # device came back? reopen
```

A failed write does **not** close the port: `is_open` means "not explicitly
closed", and a retry raises the same OS error again. After device loss (USB
hot-replug, module reload), construct a *new* `RawMidiOut` — that re-resolves the
card number from `/proc/asound/cards`, which is correct when the kernel may have
re-numbered the card. Closed is final: there is no `open()`/reopen method.

## Testing without hardware

Load the kernel's virtual Raw MIDI card and `minimidi` can talk to it like any
other device:

```bash
sudo modprobe snd-virmidi        # persistent: echo snd-virmidi | sudo tee /etc/modules-load.d/virmidi.conf
```

```python
port = minimidi.RawMidiOut("VirMIDI", device=0)
```

## Development

```bash
uv sync --all-groups               # venv + dev deps
uv run maturin develop --release   # build the Rust extension into the venv
./scripts/test.sh                  # everything CI runs: cargo fmt/clippy/test, ruff, mypy, stubtest, pytest
```

Integration tests (`tests/integration/`) need `snd-virmidi` loaded and `aconnect`
(alsa-utils) installed; they skip cleanly otherwise.

## License

MIT — see [`LICENSE`](./LICENSE).

