csound_rtmidi.h header defines the interface for implementing real-time MIDI I/O modules in Csound. It provides callbacks for MIDI backends and host application control.
Overview
This header is used by:- MIDI backend module developers
- Custom MIDI I/O implementations
- Host applications providing MIDI routing
API functions
Host MIDI I/O
csoundCreate() and before performance to implement MIDI via callbacks. This disables Csound’s default MIDI handling.
Usage:
Set MIDI module
module- Module name (e.g., “portmidi”, “alsa”, “coremidi”, “winmme”)
MIDI input callbacks
Open MIDI input
csound- Csound instanceuserData- Pointer to store backend-specific datadevName- MIDI device name to open
- 0 on success
- Non-zero error code on failure
Read MIDI input
csound- Csound instanceuserData- Backend-specific data from open callbackbuf- Buffer to fill with MIDI bytesnBytes- Maximum bytes to read
- Number of bytes read
- 0 if no data available
- Negative on error
Close MIDI input
csound- Csound instanceuserData- Backend-specific data
- 0 on success
- Non-zero on error
MIDI output callbacks
Open MIDI output
Write MIDI output
csound- Csound instanceuserData- Backend-specific databuf- Buffer containing MIDI bytes to writenBytes- Number of bytes to write
- Number of bytes written
- Negative on error
Close MIDI output
Error handling callback
errcode- Error code from MIDI operations
- Human-readable error message string
Device enumeration callback
csound- Csound instancelist- Array to fill with device info (NULL to get count)isOutput- 1 for output devices, 0 for input devices
- Number of devices available
csoundGetMIDIDevList() instead.
MIDI message format
MIDI data is passed as raw bytes following standard MIDI protocol:Status bytes
Message lengths
Most messages are 2-3 bytes:- Note On/Off: 3 bytes (status, note, velocity)
- Control Change: 3 bytes (status, controller, value)
- Program Change: 2 bytes (status, program)
- Pitch Bend: 3 bytes (status, LSB, MSB)
Implementing a MIDI backend
Complete example
Usage by host applications
Using default MIDI backend
Custom MIDI I/O
Timing considerations
MIDI callbacks may be called:- At k-rate intervals (control rate)
- From real-time threads
- With strict timing requirements
- Keep callbacks fast and non-blocking
- Buffer MIDI data if necessary
- Use lock-free queues for thread safety
- Timestamp events if latency matters
Thread safety
MIDI callbacks may be called from:- Csound’s performance thread
- Real-time system threads
- MIDI device driver threads
- Use atomic operations
- Implement lock-free buffers
- Avoid blocking operations
- Don’t call blocking Csound API from callbacks
Error handling
Return appropriate error codes:- 0 or positive: Success (bytes read/written)
- Negative: Error occurred
See also
- csound.h - Main API with MIDI device functions
- csound_rtaudio.h - Audio I/O interface
- csoundCore.h - MIDI data structures (MCHNBLK, MEVENT)