midi: move python src to server folder to be as consistent as possible with the build result

This commit is contained in:
jean-emmanuel 2025-09-12 11:45:21 +02:00
parent 18568d40c6
commit 34de7420e2
11 changed files with 9 additions and 7 deletions

View file

@ -4,7 +4,9 @@ import path from 'path'
import * as settings from './settings'
var scriptPath = path.resolve(__dirname, '../python')
var scriptPath = __dirname.includes('server/node') ?
path.resolve(__dirname, '../python') : // src folder structure
path.resolve(__dirname, './python') // app folder structure with rollup chunking
var midiBinaries = {
x64: {
@ -17,7 +19,7 @@ var midiBinaries = {
}
}
var expectMidiBinaries = fs.existsSync(path.resoluve(scriptPath, '/.expect-midi-bin')),
var expectMidiBinaries = fs.existsSync(path.resolve(scriptPath, './.expect-midi-bin')),
expectMidiBinariesError = false
var pythonPathOverride
@ -36,7 +38,7 @@ class MidiConverter {
if (expectMidiBinariesError) MidiConverter.midiBinariesError()
this.py = new PythonShell('python/midi.py', Object.assign({
this.py = new PythonShell('midi.py', Object.assign({
args: [
'--params',
settings.read('debug') ? 'debug' : '',
@ -124,7 +126,7 @@ class MidiConverter {
if (expectMidiBinariesError) MidiConverter.midiBinariesError()
PythonShell.run('python/midi.py', Object.assign({pythonPath: MidiConverter.getPythonPath(), args: ['--params', 'list-only']}, {scriptPath, mode:'text'}), function(e, results) {
PythonShell.run('midi.py', Object.assign({pythonPath: MidiConverter.getPythonPath(), args: ['--params', 'list-only']}, {scriptPath, mode:'text'}), function(e, results) {
if (e) {
if (e.code === 'ENOENT') {
console.error(`(ERROR, MIDI) Could not find python binary: ${e.message.replace(/spawn (.*) ENOENT/, '$1')}`)

53
src/server/python/head.py Normal file
View file

@ -0,0 +1,53 @@
from sys import argv, stdin, stdout, version_info, version, exit, platform
from binascii import hexlify, unhexlify
import traceback
import json as JSON
import re
def ipc_send(name, data):
print(JSON.dumps([name, data]))
stdout.flush()
prebuilt_bin = 'osc-midi' in argv[0]
try:
import rtmidi
from rtmidi.midiconstants import *
API = rtmidi.API_UNIX_JACK if 'jack' in argv else rtmidi.API_UNSPECIFIED
if API == rtmidi.API_UNIX_JACK and rtmidi.API_UNIX_JACK not in rtmidi.get_compiled_api():
API = rtmidi.API_UNSPECIFIED
ipc_send('log', '(ERROR, MIDI) python-rtmidi was not compiled with jack midi support, falling back to default API')
JACK = API == rtmidi.API_UNIX_JACK
in_dev = rtmidi.MidiIn(API, 'MIDI->OSC probe')
out_dev = rtmidi.MidiOut(API, 'OSC->MIDI probe')
except Exception as e:
if prebuilt_bin:
ipc_send('log', '(ERROR, MIDI) error while loading MIDI bridge program:\n %s' % (e.message if hasattr(e, 'message') else e))
else:
ipc_send('log', '(ERROR, MIDI) error while loading python-rtmidi library (running with python %s):\n %s' % (".".join(map(str, version_info[:3])), e.message if hasattr(e, 'message') else e))
exit()
if version_info.major == 3:
raw_input = input
# option: print debug messages
debug = 'debug' in argv
# option: act as if displayed program is between 1-128 instead of 0-127
program_change_offset = 'pc_offset' in argv
# option: parse sysex
ignore_sysex = 'sysex' not in argv
# option: parse mtc
ignore_mtc = 'mtc' not in argv
# option: parse (n)rpn
ignore_rpn = 'rpn' not in argv and 'nrpn' not in argv
# option: parse active sensing
ignore_active_sensing = 'active_sensing' not in argv
# option: note off velocity
note_off_velocity = 'note_off_velocity' in argv
# option: list midi ports
list_midi = 'list' in argv
list_midi_exit = 'list-only' in argv

24
src/server/python/list.py Normal file
View file

@ -0,0 +1,24 @@
from head import *
def list():
message = []
message.append('(INFO, MIDI) Inputs')
message.append(' -1: Void (bypass)')
for i in range(in_dev.get_port_count()):
message.append(' %i: %s' % (i, in_dev.get_port_name(i)))
message.append('(INFO, MIDI) Outputs')
message.append(' -1: Void (bypass)')
for i in range(out_dev.get_port_count()):
message.append(' %i: %s' % (i, out_dev.get_port_name(i)))
ipc_send('log', '\n'.join(message))
if __name__ == '__main__':
list()

297
src/server/python/main.py Normal file
View file

@ -0,0 +1,297 @@
from head import *
from list import *
from utils import *
from mtc import *
from rpn import *
argv = argv[argv.index('--params') + 1:]
if list_midi or list_midi_exit:
list()
if list_midi_exit:
exit()
inputs = {}
outputs = {}
for arg in argv:
if type(arg) == str and ':' in arg:
name, *ports = arg.split(':')
ports = ':'.join(ports) # port names may contain colons
inputs[name] = rtmidi.MidiIn(API, name if not JACK else name + '_in')
outputs[name] = rtmidi.MidiOut(API, name if not JACK else name + '_out')
if debug:
ipc_send('debug','device "%s" created' % name)
if ports == 'virtual':
try:
if platform == 'darwin':
inputs[name].open_virtual_port('%s-in' % name)
outputs[name].open_virtual_port('%s-out' % name)
else:
inputs[name].open_virtual_port('midi_in')
outputs[name].open_virtual_port('midi_out')
if debug:
ipc_send('debug','virtual ports opened for device "%s"' % name)
except:
ipc_send('error', 'failed to open virtual ports for device "%s"' % name)
ipc_send('error', traceback.format_exc())
inputs[name] = None
outputs[name] = None
elif ',' in ports:
in_port, out_port = ports.split(',')
if in_port.isdigit() or in_port == '-1':
in_port = int(in_port)
else:
for i in range(in_dev.get_port_count()):
if in_port.lower() in in_dev.get_port_name(i).lower():
in_port = i
break
if out_port.isdigit() or out_port == '-1':
out_port = int(out_port)
else:
for i in range(out_dev.get_port_count()):
if out_port.lower() in out_dev.get_port_name(i).lower():
out_port = i
break
if in_port != -1:
try:
inputs[name].open_port(in_port, 'midi_in')
if debug:
ipc_send('debug','device "%s" connected to input port %s (%s)' % (name, in_port, in_dev.get_port_name(in_port)))
except:
if type(in_port) != int or in_port >= in_dev.get_port_count():
ipc_send('error', 'can\'t connect "%s" to input port "%s" (port not in list)' % (name, in_port))
else:
ipc_send('error', 'failed to connect "%s" to input port %s' % (name, in_port))
ipc_send('error', traceback.format_exc())
inputs[name] = None
if out_port != -1:
try:
outputs[name].open_port(out_port, 'midi_out')
if debug:
ipc_send('debug','device "%s" connected to output port %s (%s)' % (name, out_port, out_dev.get_port_name(out_port)))
except:
if type(out_port) != int or out_port >= out_dev.get_port_count():
ipc_send('error', 'can\'t connect "%s" to output port "%s" (port not in list)' % (name, out_port))
else:
ipc_send('error', 'failed to connect "%s" to output port %s' % (name, out_port))
ipc_send('error', traceback.format_exc())
outputs[name] = None
def create_callback(name):
def receive_midi(event, data):
osc = {}
osc['args'] = []
osc['host'] = 'midi'
osc['port'] = name
message, deltatime = event
mtype = message[0] & 0xF0
if mtype in MIDI_TO_OSC:
osc['address'] = MIDI_TO_OSC[mtype]
if not ignore_mtc and is_mtc(message):
mtc = mtc_decode(message, name)
if mtc == None:
return
else:
osc['address'] = MIDI_TO_OSC[MIDI_TIME_CODE]
osc['args'].append({'type': 'string', 'value': mtc})
elif mtype == SYSTEM_EXCLUSIVE:
# Parse the provided data into a hex MIDI data string of the form 'f0 7e 7f 06 01 f7'.
v = ' '.join([hex(x).replace('0x', '').zfill(2) for x in message])
osc['args'].append({'type': 'string', 'value': v})
elif mtype == CONTROL_CHANGE and not ignore_rpn and is_rpn(message):
rpn = rpn_decode(message, name)
if rpn is not None:
osc['address'] = MIDI_TO_OSC[rpn[0]]
osc['args'].append({'type': 'i', 'value': rpn[1]})
osc['args'].append({'type': 'i', 'value': rpn[2]})
osc['args'].append({'type': 'i', 'value': rpn[3]})
ipc_send('osc', osc)
if debug:
t = 'NRPN' if rpn[0] == NRPN else 'RPN'
s = '%s: channel=%i, parameter=%i, value=%i'% (t, rpn[1], rpn[2], rpn[3])
ipc_send('debug','in: %s From: midi:%s' % (s, name))
# bypass (n)rpn CCs
return
else:
status = message[0]
channel = (status & 0x0F) + 1
osc['args'].append({'type': 'i', 'value': channel})
if mtype == NOTE_OFF:
if not note_off_velocity:
message[2] = 0
elif mtype == PITCH_BEND:
message = message[:1] + [message[1] + message[2] * 128] # convert 0-127 pair -> 0-16384 ->
elif mtype == PROGRAM_CHANGE and program_change_offset:
message[-1] = message[-1] + 1
for data in message[1:]:
osc['args'].append({'type': 'i', 'value': data})
if debug:
ipc_send('debug','in: %s From: midi:%s' % (midi_str(message, name), name))
ipc_send('osc', osc)
def callback_error_wrapper(event, data):
try:
receive_midi(event, data)
except:
ipc_send('error', traceback.format_exc())
return callback_error_wrapper
for name in inputs:
if inputs[name] != None:
inputs[name].set_callback(create_callback(name))
# sysex / mtc / active sensing support
inputs[name].ignore_types(ignore_sysex, ignore_mtc, ignore_active_sensing)
def midi_message(status, channel, data1=None, data2=None):
msg = [(status & 0xF0) | (channel - 1 & 0x0F)]
if data1 != None:
msg.append(data1 & 0x7F)
if data2 != None:
msg.append(data2 & 0x7F)
return msg
sysexRegex = re.compile(r'([^0-9A-Fa-f])\1(\1\1)*')
def send_midi(name, event, *args):
if name not in outputs:
ipc_send('error','unknown device "%s"' % name)
return
if outputs[name] == None:
ipc_send('error','device "%s" has no opened output port' % name)
return
if event not in OSC_TO_MIDI:
ipc_send('error','invalid address (%s)' % event)
return
m = None
mtype = OSC_TO_MIDI[event]
if mtype == SYSTEM_EXCLUSIVE or mtype == MIDI_TIME_CODE:
if mtype == MIDI_TIME_CODE:
m = mtc_encode(args)
else:
try:
m = []
for arg in args:
if type(arg) is str:
arg = arg.replace(' ', '') # remove spaces
arg = [arg[i:i+2] for i in range(0, len(arg), 2)] # split in 2 chars bytes
arg = [int(x, 16) for x in arg] # parse hex bytes
for x in arg:
m.append(x)
else:
m.append(int(arg) & 0x7F)
except:
pass
elif mtype == NRPN or mtype == RPN:
m = rpn_encode(mtype, args)
if m is not None:
for x in m:
outputs[name].send_message(x)
if debug:
t = 'NRPN' if mtype == NRPN else 'RPN'
s = '%s: channel=%i, parameter=%i, value=%i'% (t, args[0], args[1], args[2])
ipc_send('debug','out: %s To: midi:%s' % (s, name))
return
else:
args = [int(round(x)) for x in args]
m = [mtype, args[0]]
if mtype == NOTE_ON:
if args[2] == 0:
mtype = NOTE_OFF
elif mtype == PITCH_BEND:
args = args[:1] + [args[1] & 0x7F, (args[1] >> 7) & 0x7F] # convert 0-16383 -> 0-127 pair
elif mtype == PROGRAM_CHANGE and program_change_offset:
args[-1] = args[-1] - 1
m = midi_message(mtype, *args)
if m == None:
ipc_send('error','could not convert osc to midi (%s %s)' % (event, " ".join([str(x) for x in args])))
else:
outputs[name].send_message(m)
if debug:
ipc_send('debug','out: %s To: midi:%s' % (midi_str(m, name), name))
while True:
try:
msg = raw_input()
except:
break
try:
msg = JSON.loads(msg)
msg[1] = msg[1].lower()
send_midi(*msg)
except:
ipc_send('error', traceback.format_exc())

17
src/server/python/midi.py Normal file
View file

@ -0,0 +1,17 @@
# python script for freezing dependencies but not the runtime code
import os
import importlib
import sys
# import all libs used at runtime
# pyinstaller will freeze it
import head
if getattr(sys, 'frozen', False):
VAR_CWD = os.path.dirname(sys.executable)
sys.path.insert(1, VAR_CWD)
sys.path.insert(1, os.getcwd())
# dynamically import runtime code
importlib.import_module('main')

59
src/server/python/mtc.py Normal file
View file

@ -0,0 +1,59 @@
from head import *
def is_mtc(message):
return message[0] == MIDI_TIME_CODE or (message[0] == SYSTEM_EXCLUSIVE and len(message) == 10 and message[1:5] == [0x7F, 0x7F, 0x01, 0x01])
# quarter frame accumulator
mtc = {}
def mtc_decode(message, port):
# with bits ©jeffmikels @ https://github.com/jeffmikels/timecode_tools/blob/master/tools.py (MIT)
# TODO: backward playback ?
if message[0] == MIDI_TIME_CODE:
if port not in mtc:
mtc[port] = [0, 0, 0, 0, 0, 0 ,0 ,0]
piece = (message[1] >> 4) & 0xF
data = message[1] & 0xF
mtc[port][piece] = data
if piece == 7:
mtc_bytes = [0, 0, 0, 0]
for i in range(8):
mtc_index = 3 - i // 2
if i % 2 == 0:
# 'even' pieces came from the low nibble
mtc_bytes[mtc_index] += mtc[port][i]
else:
# 'odd' pieces came from the high nibble
mtc_bytes[mtc_index] += mtc[port][i] * 16
else:
return None
else:
mtc_bytes = message[5:-1]
mtc_bytes[0] = mtc_bytes[0] & 31
return ":".join([str(x).zfill(2) for x in mtc_bytes])
def mtc_encode(args):
if len(args) != 1:
return None
timecode = args[0]
data = str(timecode).split(':')
if len(data) != 4:
return None
else:
return [0xF0, 0x7F, 0x7F, 0x01, 0x01] + [int(x) & 0x7F for x in data] + [0xF7]

View file

@ -0,0 +1,2 @@
python-rtmidi == 1.4.9
pyinstaller

109
src/server/python/rpn.py Normal file
View file

@ -0,0 +1,109 @@
from head import *
NRPN = 256
RPN = 257
RPN_REGISTER = {}
def is_rpn(message):
return (
message[1] == DATA_ENTRY_MSB or
message[1] == DATA_ENTRY_LSB or
message[1] == RPN_MSB or
message[1] == RPN_LSB or
message[1] == NRPN_MSB or
message[1] == NRPN_LSB
)
def rpn_decode(message, port):
if port not in RPN_REGISTER:
RPN_REGISTER[port] = []
for i in range(16):
RPN_REGISTER[port].append({
'type': '',
'control_msb': -1,
'control_lsb': -1,
'value_msb': 0,
'value_lsb': 0
})
status = message[0]
channel = (status & 0x0F)# + 1
send = False
check_reset = False
if message[1] == NRPN_MSB:
RPN_REGISTER[port][channel]['type'] = NRPN
RPN_REGISTER[port][channel]['control_msb'] = message[2]
elif message[1] == NRPN_LSB:
RPN_REGISTER[port][channel]['type'] = NRPN
RPN_REGISTER[port][channel]['control_lsb'] = message[2]
check_reset = True
elif message[1] == RPN_MSB:
RPN_REGISTER[port][channel]['type'] = RPN
RPN_REGISTER[port][channel]['control_msb'] = message[2]
elif message[1] == RPN_LSB:
RPN_REGISTER[port][channel]['type'] = RPN
RPN_REGISTER[port][channel]['control_lsb'] = message[2]
check_reset = True
elif message[1] == DATA_ENTRY_MSB:
RPN_REGISTER[port][channel]['value_msb'] = message[2]
RPN_REGISTER[port][channel]['value_lsb'] = 0
send = True
elif message[1] == DATA_ENTRY_LSB:
RPN_REGISTER[port][channel]['value_lsb'] = message[2]
send = True
if check_reset:
# (n)rpn null value
if (
RPN_REGISTER[port][channel]['control_msb'] == 127 and
RPN_REGISTER[port][channel]['control_lsb'] == 127
):
RPN_REGISTER[port][channel]['control_msb'] = -1
if send and RPN_REGISTER[port][channel]['control_msb'] != -1:
return [
RPN_REGISTER[port][channel]['type'],
channel + 1,
RPN_REGISTER[port][channel]['control_msb'] * 128 + RPN_REGISTER[port][channel]['control_lsb'],
RPN_REGISTER[port][channel]['value_msb'] * 128 + RPN_REGISTER[port][channel]['value_lsb']
]
return None
def rpn_encode(mtype, args):
if len(args) != 3:
return None
channel, control, value = args
status = CONTROL_CHANGE | (channel - 1 & 0x0F)
return (
[status, 99 if mtype == NRPN else 101, control >> 7],
[status, 98 if mtype == NRPN else 100, control & 0x7F],
[status, 6, value >> 7],
[status, 38, value & 0x7F]
)
# rtmidi doesn't support running status
# return [
# 0xF0,0xF7,
# CONTROL_CHANGE | (channel - 1 & 0x0F),
# 99 if mtype == NRPN else 101,
# control >> 7,
# 98 if mtype == NRPN else 100,
# control & 0x7F,
# 6,
# value >> 7,
# 38,
# value & 0x7F
# ]

View file

@ -0,0 +1,79 @@
from head import *
from mtc import *
from rpn import *
MIDI_TO_OSC = {
NOTE_ON: '/note',
NOTE_OFF: '/note',
CONTROL_CHANGE: '/control',
PROGRAM_CHANGE: '/program',
PITCH_BEND: '/pitch',
SYSTEM_EXCLUSIVE: '/sysex',
MIDI_TIME_CODE: '/mtc',
CHANNEL_PRESSURE: '/channel_pressure',
POLY_PRESSURE: '/key_pressure'
}
OSC_TO_MIDI = {
'/note': NOTE_ON,
'/note_off': NOTE_OFF,
'/control': CONTROL_CHANGE,
'/program': PROGRAM_CHANGE,
'/pitch': PITCH_BEND,
'/sysex': SYSTEM_EXCLUSIVE,
'/mtc': MIDI_TIME_CODE,
'/channel_pressure': CHANNEL_PRESSURE,
'/key_pressure': POLY_PRESSURE
}
if note_off_velocity:
MIDI_TO_OSC[NOTE_OFF] = '/note_off'
if not ignore_rpn:
MIDI_TO_OSC[NRPN] = '/nrpn'
MIDI_TO_OSC[RPN] = '/rpn'
OSC_TO_MIDI['/nrpn'] = NRPN
OSC_TO_MIDI['/rpn'] = RPN
def midi_str(message, port):
mtype = message[0] & 0xF0
s = 'UNKNOWN'
if is_mtc(message):
s = 'MTC: timecode=%s' % mtc_decode(message, None)
elif mtype == SYSTEM_EXCLUSIVE:
s = 'SYSTEM_EXCLUSIVE: sysex=%s' % ' '.join([hex(x).replace('0x', '').zfill(2) for x in message])
else:
status = message[0]
channel = (status & 0x0F) + 1
try:
if mtype == NOTE_ON:
s = 'NOTE_ON: channel=%i, note=%i, velocity=%i' % (channel, message[1], message[2])
elif mtype == NOTE_OFF:
s = 'NOTE_OFF: channel=%i, note=%i, velocity=%i' % (channel, message[1], message[2])
elif mtype == CONTROL_CHANGE:
s = 'CONTROL_CHANGE: channel=%i, cc=%i, value=%i'% (channel, message[1], message[2])
elif mtype == PROGRAM_CHANGE:
s = 'PROGRAM_CHANGE: channel=%i, program=%i' % (channel, message[1])
elif mtype == PITCH_BEND:
s = 'PITCH_BEND: channel=%i, pitch=%i' % (channel, message[1] + message[2] * 128 if len(message) == 3 else message[1])
elif mtype == CHANNEL_PRESSURE:
s = 'CHANNEL_PRESSURE: channel=%i, pressure=%i' % (channel, message[1])
elif mtype == POLY_PRESSURE:
s = 'KEY_PRESSURE: channel=%i, note=%i, pressure=%i' % (channel, message[1], message[2])
except IndexError:
s = 'NONE (ERROR: wrong number of argument for %s)' % MIDI_TO_OSC[mtype]
return s