mkiv.py 19 KB

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