mkiv.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. '''
  2. itl_chorus -- ITL Chorus Suite
  3. mkiv -- Make Intervals
  4. This simple script (using python-midi) reads a MIDI file and makes an interval
  5. (.iv) file (actually XML) that contains non-overlapping notes.
  6. TODO:
  7. -MIDI Control events
  8. -Percussion
  9. '''
  10. import xml.etree.ElementTree as ET
  11. import midi
  12. import sys
  13. import os
  14. import optparse
  15. TRACKS = object()
  16. PROGRAMS = object()
  17. parser = optparse.OptionParser()
  18. parser.add_option('-s', '--channel-split', dest='chansplit', action='store_true', help='Split MIDI channels into independent tracks (as far as -T is concerned)')
  19. parser.add_option('-S', '--split-out', dest='chansfname', help='Store the split-format MIDI back into the specified file')
  20. parser.add_option('-c', '--preserve-channels', dest='chanskeep', action='store_true', help='Keep the channel number when splitting channels to tracks (default is to set it to 1)')
  21. parser.add_option('-T', '--track-split', dest='tracks', action='append_const', const=TRACKS, help='Ensure all tracks are on non-mutual streams')
  22. parser.add_option('-t', '--track', dest='tracks', action='append', help='Reserve an exclusive set of streams for certain conditions (try --help-conds)')
  23. parser.add_option('--help-conds', dest='help_conds', action='store_true', help='Print help on filter conditions for streams')
  24. parser.add_option('-p', '--program-split', dest='tracks', action='append_const', const=PROGRAMS, help='Ensure all programs are on non-mutual streams (overrides -T presently)')
  25. parser.add_option('-P', '--percussion', dest='perc', help='Which percussion standard to use to automatically filter to "perc" (GM, GM2, or none)')
  26. parser.add_option('-f', '--fuckit', dest='fuckit', action='store_true', help='Use the Python Error Steamroller when importing MIDIs (useful for extended formats)')
  27. parser.add_option('-n', '--target-num', dest='repeaterNumber', type='int', help='Target count of devices')
  28. parser.add_option('-v', '--verbose', dest='verbose', action='store_true', help='Be verbose; show important parts about the MIDI scheduling process')
  29. parser.add_option('-d', '--debug', dest='debug', action='store_true', help='Debugging output; show excessive output about the MIDI scheduling process')
  30. parser.add_option('-D', '--deviation', dest='deviation', type='int', help='Amount (in semitones/MIDI pitch units) by which a fully deflected pitchbend modifies the base pitch (0 disables pitchbend processing)')
  31. parser.add_option('--tempo', dest='tempo', help='Adjust interpretation of tempo (try "f1"/"global", "f2"/"track")')
  32. parser.set_defaults(tracks=[], repeaterNumber=1, perc='GM', deviation=2, tempo='global')
  33. options, args = parser.parse_args()
  34. if options.tempo == 'f1':
  35. options.tempo == 'global'
  36. elif options.tempo == 'f2':
  37. options.tempo == 'track'
  38. if options.help_conds:
  39. print '''Filter conditions are used to route events to groups of streams.
  40. Every filter is an expression; internally, this expression is evaluated as the body of a "lambda ev: ".
  41. The "ev" object will be a MergeEvent with the following properties:
  42. -ev.tidx: the originating track index (starting at 0)
  43. -ev.abstime: the real time in seconds of this event relative to the beginning of playback
  44. -ev.bank: the selected bank (all bits)
  45. -ev.prog: the selected program
  46. -ev.ev: a midi.NoteOnEvent:
  47. -ev.ev.pitch: the MIDI pitch
  48. -ev.ev.velocity: the MIDI velocity
  49. -ev.ev.channel: the MIDI channel
  50. All valid Python expressions are accepted. Take care to observe proper shell escaping.
  51. Specifying a -t <group>=<filter> will group all streams under a filter; if the <group> part is omitted, no group will be added.
  52. For example:
  53. mkiv -t bass=ev.ev.pitch<35 -t treble=ev.ev.pitch>75 -T -t ev.abstime<10
  54. will cause these groups to be made:
  55. -A group "bass" with all notes with pitch less than 35;
  56. -Of those not in "bass", a group in "treble" with pitch>75;
  57. -Of what is not yet consumed, a series of groups "trkN" where N is the track index (starting at 0), which consumes the rest.
  58. -An (unfortunately empty) unnamed group with events prior to ten real seconds.
  59. As can be seen, order of specification is important. Equally important is the location of -T, which should be at the end.
  60. NoteOffEvents are always matched to the stream which has their corresponding NoteOnEvent (in track, pitch, and channel), and so are
  61. not affected or observed by filters.
  62. If the filters specified are not a complete cover, an anonymous group will be created with no filter to contain the rest. If
  63. it is desired to force this group to have a name, use -t <group>=True. This should be placed at the end.
  64. -T behaves exactly as if:
  65. -t trk0=ev.tidx==0 -t trk1=ev.tidx==1 -t trk2=ev.tidx==2 [...]
  66. had been specified in its place, though it is automatically sized to the number of tracks. Similarly, -P operates as if
  67. -t prg31=ev.prog==31 -t prg81=ev.prog==81 [...]
  68. had been specified, again containing only the programs that were observed in the piece.
  69. Groups for which no streams are generated are not written to the resulting file.'''
  70. exit()
  71. if not args:
  72. parser.print_usage()
  73. exit()
  74. if options.fuckit:
  75. import fuckit
  76. midi.read_midifile = fuckit(midi.read_midifile)
  77. for fname in args:
  78. try:
  79. pat = midi.read_midifile(fname)
  80. except Exception:
  81. import traceback
  82. traceback.print_exc()
  83. print fname, ': Exception occurred, skipping...'
  84. continue
  85. if pat is None:
  86. print fname, ': Too fucked to continue'
  87. continue
  88. iv = ET.Element('iv')
  89. iv.set('version', '1')
  90. iv.set('src', os.path.basename(fname))
  91. print fname, ': MIDI format,', len(pat), 'tracks'
  92. if options.verbose:
  93. print fname, ': MIDI Parameters:', pat.resolution, 'PPQN,', pat.format, 'format'
  94. if options.chansplit:
  95. print 'Splitting channels...'
  96. old_pat = pat
  97. pat = midi.Pattern(resolution=old_pat.resolution)
  98. for track in old_pat:
  99. chan_map = {}
  100. last_abstick = {}
  101. absticks = 0
  102. for ev in track:
  103. absticks += ev.tick
  104. if isinstance(ev, midi.Event):
  105. tick = absticks - last_abstick.get(ev.channel, 0)
  106. last_abstick[ev.channel] = absticks
  107. if options.chanskeep:
  108. newev = ev.copy(tick = tick)
  109. else:
  110. newev = ev.copy(channel=1, tick = tick)
  111. chan_map.setdefault(ev.channel, midi.Track()).append(newev)
  112. else: # MetaEvent
  113. for trk in chan_map.itervalues():
  114. trk.append(ev)
  115. items = chan_map.items()
  116. items.sort(key=lambda pair: pair[0])
  117. for chn, trk in items:
  118. pat.append(trk)
  119. print 'Split', len(old_pat), 'tracks into', len(pat), 'tracks by channel'
  120. if options.chansfname:
  121. midi.write_midifile(options.chansfname, pat)
  122. ##### Merge events from all tracks into one master list, annotated with track and absolute times #####
  123. print 'Merging events...'
  124. class SortEvent(object):
  125. __slots__ = ['ev', 'tidx', 'abstick']
  126. def __init__(self, ev, tidx, abstick):
  127. self.ev = ev
  128. self.tidx = tidx
  129. self.abstick = abstick
  130. sorted_events = []
  131. for tidx, track in enumerate(pat):
  132. absticks = 0
  133. for ev in track:
  134. absticks += ev.tick
  135. sorted_events.append(SortEvent(ev, tidx, absticks))
  136. sorted_events.sort(key=lambda x: x.abstick)
  137. if options.tempo == 'global':
  138. bpm_at = [{0: 120}]
  139. else:
  140. bpm_at = [{0: 120} for i in pat]
  141. print 'Computing tempos...'
  142. for sev in sorted_events:
  143. if isinstance(sev.ev, midi.SetTempoEvent):
  144. if options.debug:
  145. print fname, ': SetTempo at', sev.abstick, 'to', sev.ev.bpm, ':', sev.ev
  146. bpm_at[sev.tidx if options.tempo == 'track' else 0][sev.abstick] = sev.ev.bpm
  147. if options.verbose:
  148. print fname, ': Events:', len(sorted_events)
  149. print fname, ': Resolved global BPM:', bpm_at
  150. if options.debug:
  151. for tidx, bpms in enumerate(bpm_at):
  152. print fname, ': Tempos in track', tidx
  153. btimes = bpms.keys()
  154. for i in range(len(btimes) - 1):
  155. fev = filter(lambda sev: sev.tidx == tidx and sev.abstick >= btimes[i] and sev.abstick < btimes[i+1], sorted_events)
  156. print fname, ': BPM partition', i, 'contains', len(fev), 'events'
  157. class MergeEvent(object):
  158. __slots__ = ['ev', 'tidx', 'abstime', 'bank', 'prog']
  159. def __init__(self, ev, tidx, abstime, bank, prog):
  160. self.ev = ev
  161. self.tidx = tidx
  162. self.abstime = abstime
  163. self.bank = bank
  164. self.prog = prog
  165. def copy(self, **kwargs):
  166. args = {'ev': self.ev, 'tidx': self.tidx, 'abstime': self.abstime, 'bank': self.bank, 'prog': self.prog}
  167. args.update(kwargs)
  168. return MergeEvent(**args)
  169. def __repr__(self):
  170. return '<ME %r in %d on (%d:%d) @%f>'%(self.ev, self.tidx, self.bank, self.prog, self.abstime)
  171. events = []
  172. cur_bank = [[0 for i in range(16)] for j in range(len(pat))]
  173. cur_prog = [[0 for i in range(16)] for j in range(len(pat))]
  174. chg_bank = [[0 for i in range(16)] for j in range(len(pat))]
  175. chg_prog = [[0 for i in range(16)] for j in range(len(pat))]
  176. ev_cnts = [[0 for i in range(16)] for j in range(len(pat))]
  177. tnames = [''] * len(pat)
  178. progs = set([0])
  179. for tidx, track in enumerate(pat):
  180. abstime = 0
  181. absticks = 0
  182. for ev in track:
  183. bpm = filter(lambda pair: pair[0] <= absticks, sorted(bpm_at[tidx if options.tempo == 'track' else 0].items(), key=lambda pair: pair[0]))[-1][1]
  184. if options.debug:
  185. print ev, ': bpm=', bpm
  186. absticks += ev.tick
  187. if isinstance(ev, midi.ProgramChangeEvent):
  188. cur_prog[tidx][ev.channel] = ev.value
  189. progs.add(ev.value)
  190. chg_prog[tidx][ev.channel] += 1
  191. elif isinstance(ev, midi.ControlChangeEvent):
  192. if ev.control == 0:
  193. cur_bank[tidx][ev.channel] = (0x3F80 & cur_bank[tidx][ev.channel]) | ev.value
  194. chg_bank[tidx][ev.channel] += 1
  195. elif ev.control == 32:
  196. cur_bank[tidx][ev.channel] = (0x3F & cur_bank[tidx][ev.channel]) | (ev.value << 7)
  197. chg_bank[tidx][ev.channel] += 1
  198. elif isinstance(ev, midi.TrackNameEvent):
  199. tnames[tidx] = ev.text
  200. elif isinstance(ev, midi.Event):
  201. if isinstance(ev, midi.NoteOnEvent) and ev.velocity == 0:
  202. ev.__class__ = midi.NoteOffEvent #XXX Oww
  203. abstime += (60.0 * ev.tick) / (bpm * pat.resolution)
  204. events.append(MergeEvent(ev, tidx, abstime, cur_bank[tidx][ev.channel], cur_prog[tidx][ev.channel]))
  205. ev_cnts[tidx][ev.channel] += 1
  206. if options.verbose:
  207. print 'Track name, event count, final banks, bank changes, final programs, program changes:'
  208. for tidx, tname in enumerate(tnames):
  209. print tidx, ':', tname, ',', ','.join(map(str, ev_cnts[tidx])), ',', ','.join(map(str, cur_bank[tidx])), ',', ','.join(map(str, chg_bank[tidx])), ',', ','.join(map(str, cur_prog[tidx])), ',', ','.join(map(str, chg_prog[tidx]))
  210. print 'All programs observed:', progs
  211. print 'Sorting events...'
  212. events.sort(key = lambda ev: ev.abstime)
  213. ##### Use merged events to construct a set of streams with non-overlapping durations #####
  214. print 'Generating streams...'
  215. class DurationEvent(MergeEvent):
  216. __slots__ = ['duration', 'pitch']
  217. def __init__(self, me, pitch, dur):
  218. MergeEvent.__init__(self, me.ev, me.tidx, me.abstime, me.bank, me.prog)
  219. self.pitch = pitch
  220. self.duration = dur
  221. class NoteStream(object):
  222. __slots__ = ['history', 'active', 'realpitch']
  223. def __init__(self):
  224. self.history = []
  225. self.active = None
  226. self.realpitch = None
  227. def IsActive(self):
  228. return self.active is not None
  229. def Activate(self, mev, realpitch = None):
  230. if realpitch is None:
  231. realpitch = mev.ev.pitch
  232. self.active = mev
  233. self.realpitch = realpitch
  234. def Deactivate(self, mev):
  235. self.history.append(DurationEvent(self.active, self.realpitch, mev.abstime - self.active.abstime))
  236. self.active = None
  237. self.realpitch = None
  238. def WouldDeactivate(self, mev):
  239. if not self.IsActive():
  240. return False
  241. if isinstance(mev.ev, midi.NoteOffEvent):
  242. return mev.ev.pitch == self.active.ev.pitch and mev.tidx == self.active.tidx and mev.ev.channel == self.active.ev.channel
  243. if isinstance(mev.ev, midi.PitchWheelEvent):
  244. return mev.tidx == self.active.tidx and mev.ev.channel == self.active.ev.channel
  245. raise TypeError('Tried to deactivate with bad type %r'%(type(mev.ev),))
  246. class NSGroup(object):
  247. __slots__ = ['streams', 'filter', 'name']
  248. def __init__(self, filter=None, name=None):
  249. self.streams = []
  250. self.filter = (lambda mev: True) if filter is None else filter
  251. self.name = name
  252. def Accept(self, mev):
  253. if not self.filter(mev):
  254. return False
  255. for stream in self.streams:
  256. if not stream.IsActive():
  257. stream.Activate(mev)
  258. break
  259. else:
  260. stream = NoteStream()
  261. self.streams.append(stream)
  262. stream.Activate(mev)
  263. return True
  264. notegroups = []
  265. auxstream = []
  266. if options.perc and options.perc != 'none':
  267. if options.perc == 'GM':
  268. notegroups.append(NSGroup(filter = lambda mev: mev.ev.channel == 9, name='perc'))
  269. elif options.perc == 'GM2':
  270. notegroups.append(NSGroup(filter = lambda mev: mev.bank == 15360, name='perc'))
  271. else:
  272. print 'Unrecognized --percussion option %r; should be GM, GM2, or none'%(options.perc,)
  273. for spec in options.tracks:
  274. if spec is TRACKS:
  275. for tidx in xrange(len(pat)):
  276. notegroups.append(NSGroup(filter = lambda mev, tidx=tidx: mev.tidx == tidx, name = 'trk%d'%(tidx,)))
  277. elif spec is PROGRAMS:
  278. for prog in progs:
  279. notegroups.append(NSGroup(filter = lambda mev, prog=prog: mev.prog == prog, name = 'prg%d'%(prog,)))
  280. else:
  281. if '=' in spec:
  282. name, _, spec = spec.partition('=')
  283. else:
  284. name = None
  285. notegroups.append(NSGroup(filter = eval("lambda ev: "+spec), name = name))
  286. if options.verbose:
  287. print 'Initial group mappings:'
  288. for group in notegroups:
  289. print ('<anonymous>' if group.name is None else group.name)
  290. for mev in events:
  291. if isinstance(mev.ev, midi.NoteOnEvent):
  292. for group in notegroups:
  293. if group.Accept(mev):
  294. break
  295. else:
  296. group = NSGroup()
  297. group.Accept(mev)
  298. notegroups.append(group)
  299. elif isinstance(mev.ev, midi.NoteOffEvent):
  300. for group in notegroups:
  301. found = False
  302. for stream in group.streams:
  303. if stream.WouldDeactivate(mev):
  304. stream.Deactivate(mev)
  305. found = True
  306. break
  307. if found:
  308. break
  309. else:
  310. print 'WARNING: Did not match %r with any stream deactivation.'%(mev,)
  311. if options.verbose:
  312. print ' Current state:'
  313. for group in notegroups:
  314. print ' Group %r:'%(group.name,)
  315. for stream in group.streams:
  316. print ' Stream: %r'%(stream.active,)
  317. elif options.deviation > 0 and isinstance(mev.ev, midi.PitchWheelEvent):
  318. for group in notegroups:
  319. found = False
  320. for stream in group.streams:
  321. if stream.WouldDeactivate(mev):
  322. base = stream.active.copy(abstime=mev.abstime)
  323. stream.Deactivate(mev)
  324. stream.Activate(base, base.ev.pitch + options.deviation * (mev.ev.pitch / float(0x2000)))
  325. found = True
  326. break
  327. if found:
  328. break
  329. else:
  330. print 'WARNING: Did not find any matching active streams for %r'%(mev,)
  331. if options.verbose:
  332. print ' Current state:'
  333. for group in notegroups:
  334. print ' Group %r:'%(group.name,)
  335. for stream in group.streams:
  336. print ' Stream: %r'%(stream.active,)
  337. else:
  338. auxstream.append(mev)
  339. lastabstime = events[-1].abstime
  340. for group in notegroups:
  341. for ns in group.streams:
  342. if ns.IsActive():
  343. print 'WARNING: Active notes at end of playback.'
  344. ns.Deactivate(MergeEvent(ns.active, ns.active.tidx, lastabstime, 0, 0))
  345. if options.verbose:
  346. print 'Final group mappings:'
  347. for group in notegroups:
  348. print ('<anonymous>' if group.name is None else group.name), '<=', '(', len(group.streams), 'streams)'
  349. print 'Generated %d streams in %d groups'%(sum(map(lambda x: len(x.streams), notegroups)), len(notegroups))
  350. print 'Playtime:', lastabstime, 'seconds'
  351. ##### Write to XML and exit #####
  352. ivmeta = ET.SubElement(iv, 'meta')
  353. abstime = 0
  354. prevticks = 0
  355. prev_bpm = 120
  356. for tidx, bpms in enumerate(bpm_at):
  357. ivbpms = ET.SubElement(ivmeta, 'bpms', track=str(tidx))
  358. for absticks, bpm in sorted(bpms.items(), key = lambda pair: pair[0]):
  359. abstime += ((absticks - prevticks) * 60.0) / (prev_bpm * pat.resolution)
  360. prevticks = absticks
  361. ivbpm = ET.SubElement(ivbpms, 'bpm')
  362. ivbpm.set('bpm', str(bpm))
  363. ivbpm.set('ticks', str(absticks))
  364. ivbpm.set('time', str(abstime))
  365. ivstreams = ET.SubElement(iv, 'streams')
  366. x = 0
  367. while(x<options.repeaterNumber):
  368. for group in notegroups:
  369. for ns in group.streams:
  370. ivns = ET.SubElement(ivstreams, 'stream')
  371. ivns.set('type', 'ns')
  372. if group.name is not None:
  373. ivns.set('group', group.name)
  374. for note in ns.history:
  375. ivnote = ET.SubElement(ivns, 'note')
  376. ivnote.set('pitch', str(note.pitch))
  377. ivnote.set('vel', str(note.ev.velocity))
  378. ivnote.set('time', str(note.abstime))
  379. ivnote.set('dur', str(note.duration))
  380. x+=1
  381. if(x>=options.repeaterNumber and options.repeaterNumber!=1):
  382. break
  383. if(x>=options.repeaterNumber and options.repeaterNumber!=1):
  384. break
  385. if(x>=options.repeaterNumber and options.repeaterNumber!=1):
  386. break
  387. ivaux = ET.SubElement(ivstreams, 'stream')
  388. ivaux.set('type', 'aux')
  389. fw = midi.FileWriter()
  390. fw.RunningStatus = None # XXX Hack
  391. for mev in auxstream:
  392. ivev = ET.SubElement(ivaux, 'ev')
  393. ivev.set('time', str(mev.abstime))
  394. ivev.set('data', repr(fw.encode_midi_event(mev.ev)))
  395. print 'Done.'
  396. open(os.path.splitext(os.path.basename(fname))[0]+'.iv', 'w').write(ET.tostring(iv))