From 8fbcdce3200ed4aaca322683bf68a1213c367c6f Mon Sep 17 00:00:00 2001 From: jean-emmanuel Date: Fri, 24 Feb 2017 01:06:36 +0100 Subject: [PATCH] midi: implementing midi addon with python-pyo (wip) --- CHANGELOG.md | 2 + app/main/midi.js | 48 ++++++++++++ app/main/midi.py | 173 +++++++++++++++++++++++++++++++++++++++++++ app/main/osc.js | 23 ++++-- app/main/settings.js | 2 + 5 files changed, 241 insertions(+), 7 deletions(-) create mode 100644 app/main/midi.js create mode 100644 app/main/midi.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 376ca2f7..d3dd6f8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## next +- main + - **new** `midi` support - bug fixes - `push` widgets (and `keyboards`) not correctly synchronizing each other (with shared widget ids or between different clients) - widgets diff --git a/app/main/midi.js b/app/main/midi.js new file mode 100644 index 00000000..37cde77b --- /dev/null +++ b/app/main/midi.js @@ -0,0 +1,48 @@ +var PythonShell = require('python-shell'), + path = require('path'), + settings = require('./settings') + + +var py = new PythonShell(path.resolve('/main/midi.py'),{mode:'text', args: settings.read('midi')}) + + + +// py.send('zefezf') +// +// +// py.on('error', function (message) { +// // received a message sent from the Python script (a simple "print" statement) +// console.log('error:' +message); +// }); + +oscToMidi = (data)=>{ + var args = [] + for (i in data.args) { + args.push(data.args[i].value) + } + py.send(JSON.stringify([data.port, data.address, ...args])) +} + +init = (receiveOsc)=>{ + py.on('message', function (message) { + // console.log(message) + + try { + message = JSON.parse(message) + // console.log(JSON.parse(message)) + } catch (err) { + // console.log(err) + } + if (message.log) { + console.log(message.log) + } else if (message.osc) { + receiveOsc(message.osc) + } + }) +} + + +module.exports = { + send: oscToMidi, + init: init +} diff --git a/app/main/midi.py b/app/main/midi.py new file mode 100644 index 00000000..17291ba6 --- /dev/null +++ b/app/main/midi.py @@ -0,0 +1,173 @@ +#encoding: utf-8 + +from sys import argv, stdin, stdout +import json as JSON + +def ipcSend(data): + print(JSON.dumps(data)) + stdout.flush() + +try: + import pyo +except: + raise ImportError('python-pyo module not found') + +version = int(pyo.PYO_VERSION.replace('.','')) + +if version < 83: + raise ImportError('python-pyo >= 8.3.0 module is required (%s found)' % pyo.PYO_VERSION) + +if not pyo.withPortmidi(): + raise ImportError('python-pyo must be built with portmidi support') + + +_midiOutputs = pyo.pm_get_output_devices() +_midiInputs = pyo.pm_get_input_devices() + + +if 'list' in argv: + + message = [] + + message.append('===========') + message.append('MIDI Inputs') + + for k in range(len(_midiInputs[0])): + + message.append('%i: %s' % (_midiInputs[1][k], _midiInputs[0][k])) + + message.append('============') + message.append('MIDI Outputs') + + for k in range(len(_midiOutputs[0])): + + message.append('%i: %s' % (_midiOutputs[1][k], _midiOutputs[0][k])) + + + message.append('============') + + ipcSend({ + 'log': message + }) + + + +class MidiRouter(object): + + def __init__(self, midiDevices): + + self.listener = pyo.MidiListener(self.receiveMidi, 999, True) + self.dispatcher = pyo.MidiDispatcher(999) + + self.listener.start() + self.dispatcher.start() + + self.midiDevicesIn = {} + self.midiDevicesOut = {} + + for pair in midiDevices: + name = str(pair.split(':')[0]) + i = int(pair.split(':')[1].split(',')[0]) + o = int(pair.split(':')[1].split(',')[1]) + + if i not in _midiInputs[1]: + raise ValueError('Invalid midi input %i' % i) + + if o not in _midiOutputs[1]: + raise ValueError('Invalid midi output %i' % o) + + self.midiDevicesIn[i] = name + self.midiDevicesOut[name] = o + + def receiveMidi(self, status, data1, data2, device): + if 127 < status < 144: + event = 'note' + channel = status - 127 + data2 = 0 + + elif 143 < status < 160: + event = 'note' + channel = status - 143 + + elif 175 < status < 192: + event = 'control' + channel = status - 175 + + elif 191 < status < 208: + event = 'program' + channel = status - 191 + + else: + return + + ipcSend({'osc':{ + 'address': '/%s' % event, + 'args': [ + { + 'type': 'i', + 'value': channel + }, + { + 'type': 'i', + 'value': data1 + }, + { + 'type': 'i', + 'value': data2 + } + ], + 'target': ['midi:' + self.midiDevicesIn[device]] + }}) + + + def sendMidi(self, device, event, *args): + + channel = int(min(max(args[0],1), 16)) + + data1 = int(min(max(args[1],0), 127)) + data2 = int(min(max(args[2],0), 127)) + + if 'note' in event: + if data2 == 0: + status = 127 + channel + else: + status = 143 + channel + + elif 'control' in event: + status = 175 + channel + + elif 'program' in event: + status = 191 + channel + + elif 'pitch' in event: + status = 223 + channel + + else: + return + + if device in self.midiDevicesOut: + self.dispatcher.send(status, data1, data2, 0, self.midiDevicesOut[device]) + + elif device == '*': + self.dispatcher.send(status, data1, data2, 0, -1) + + pass + + + +patch = [] +for arg in argv: + if type(arg) == str and ':' in arg and ',' in arg: + patch.append(arg) + +router = MidiRouter(patch) + + +while True: + msg = raw_input() + try: + msg = JSON.loads(msg) + msg[1] = msg[1].lower() # lower midi event type + router.sendMidi(*msg) + except: + pass diff --git a/app/main/osc.js b/app/main/osc.js index 85d9b5d3..0ef2525e 100644 --- a/app/main/osc.js +++ b/app/main/osc.js @@ -8,8 +8,8 @@ var osc = require('osc'), oscInPort = settings.read('oscInPort') || settings.read('httpPort'), debug = settings.read('debug'), vm = require('vm'), - fs = require('fs') - + fs = require('fs'), + midi = settings.read('midi') ? require('./midi') : false var oscServer = new osc.UDPPort({ localAddress: "0.0.0.0", @@ -51,12 +51,20 @@ var sendOsc = function(data){ if (!data) return - oscServer.send({ - address: data.address, - args: data.args - }, data.host, data.port) + if (data.host == 'midi' && midi) { + + midi.send(data) + + } else { + + oscServer.send({ + address: data.address, + args: data.args + }, data.host, data.port) + + if (debug) console.log('OSC sent: ',{address:data.address, args: data.args}, 'To : ' + data.host + ':' + data.port) + } - if (debug) console.log('OSC sent: ',{address:data.address, args: data.args}, 'To : ' + data.host + ':' + data.port) } @@ -149,6 +157,7 @@ if (customModule.init) { customModule.init() } +midi.init(receiveOsc) module.exports = { diff --git a/app/main/settings.js b/app/main/settings.js index 58e85779..20c28685 100644 --- a/app/main/settings.js +++ b/app/main/settings.js @@ -29,6 +29,7 @@ var options = { true : 'Port must be an integer >= 1024' } }, + 'm':{alias:'midi',type:'array',describe:'midi router settings (requires python-pyo)'}, 'd':{alias:'debug',type:'boolean',describe:'log received osc messages in the console'}, 'n':{alias:'no-gui',type:'boolean',describe:'disable default gui', check: (n,argv)=>{ @@ -94,6 +95,7 @@ var makeDefaultConfig = function(argv){ noGui: argv.n || false, guiOnly: typeof argv.g == 'string' ? argv.g.length ? argv.g : true : false, noVsync: argv['disable-vsync'] || false, + midi: argv.m, appAddresses:function(){ var appAddresses = []