mkiv.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. -Reserve channels by track
  8. -Reserve channels by MIDI channel
  9. -Pitch limits for channels
  10. -MIDI Control events
  11. '''
  12. import xml.etree.ElementTree as ET
  13. import midi
  14. import sys
  15. import os
  16. import optparse
  17. TRACKS = object()
  18. parser = optparse.OptionParser()
  19. parser.add_option('-s', '--channel-split', dest='chansplit', action='store_true', help='Split MIDI channels into independent tracks (as far as -T is concerned)')
  20. parser.add_option('-S', '--split-out', dest='chansfname', help='Store the split-format MIDI back into the specified file')
  21. 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)')
  22. parser.add_option('-T', '--track-split', dest='tracks', action='append_const', const=TRACKS, help='Ensure all tracks are on non-mutual streams')
  23. parser.add_option('-t', '--track', dest='tracks', action='append', help='Reserve an exclusive set of streams for certain conditions (try --help-conds)')
  24. parser.add_option('--help-conds', dest='help_conds', action='store_true', help='Print help on filter conditions for streams')
  25. parser.add_option('-P', '--no-percussion', dest='no_perc', action='store_true', help='Don\'t try to filter percussion events out')
  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.set_defaults(tracks=[], repeaterNumber=1)
  29. options, args = parser.parse_args()
  30. if options.help_conds:
  31. print '''Filter conditions are used to route events to groups of streams.
  32. Every filter is an expression; internally, this expression is evaluated as the body of a "lambda ev: ".
  33. The "ev" object will be a MergeEvent with the following properties:
  34. -ev.tidx: the originating track index (starting at 0)
  35. -ev.abstime: the real time in seconds of this event relative to the beginning of playback
  36. -ev.ev: a midi.NoteOnEvent:
  37. -ev.ev.pitch: the MIDI pitch
  38. -ev.ev.velocity: the MIDI velocity
  39. Specifying a -t <group>=<filter> will group all streams under a filter; if the <group> part is omitted, no group will be added.
  40. For example:
  41. mkiv -t bass=ev.ev.pitch<35 -t treble=ev.ev.pitch>75 -T -t ev.abstime<10
  42. will cause these groups to be made:
  43. -A group "bass" with all notes with pitch less than 35;
  44. -Of those not in "bass", a group in "treble" with pitch>75;
  45. -Of what is not yet consumed, a series of groups "trkN" where N is the track index (starting at 0), which consumes the rest.
  46. -An (unfortunately empty) unnamed group with events prior to ten real seconds.
  47. As can be seen, order of specification is important. Equally important is the location of -T, which should be at the end.
  48. NoteOffEvents are always matched to the stream which has their corresponding NoteOnEvent (in track and pitch), and so are
  49. not affected or observed by filters.
  50. If the filters specified are not a complete cover, an anonymous group will be created with no filter to contain the rest. If
  51. it is desired to force this group to have a name, use -t <group>=True.'''
  52. exit()
  53. if not args:
  54. parser.print_usage()
  55. exit()
  56. if options.fuckit:
  57. import fuckit
  58. midi.read_midifile = fuckit(midi.read_midifile)
  59. for fname in args:
  60. try:
  61. pat = midi.read_midifile(fname)
  62. except Exception:
  63. import traceback
  64. traceback.print_exc()
  65. print fname, ': Exception occurred, skipping...'
  66. continue
  67. if pat is None:
  68. print fname, ': Too fucked to continue'
  69. continue
  70. iv = ET.Element('iv')
  71. iv.set('version', '1')
  72. iv.set('src', os.path.basename(fname))
  73. print fname, ': MIDI format,', len(pat), 'tracks'
  74. if options.chansplit:
  75. print 'Splitting channels...'
  76. old_pat = pat
  77. pat = midi.Pattern(resolution=old_pat.resolution)
  78. for track in old_pat:
  79. chan_map = {}
  80. last_abstick = {}
  81. absticks = 0
  82. for ev in track:
  83. absticks += ev.tick
  84. if isinstance(ev, midi.Event):
  85. tick = absticks - last_abstick.get(ev.channel, 0)
  86. last_abstick[ev.channel] = absticks
  87. if options.chanskeep:
  88. newev = ev.copy(tick = tick)
  89. else:
  90. newev = ev.copy(channel=1, tick = tick)
  91. chan_map.setdefault(ev.channel, midi.Track()).append(newev)
  92. else: # MetaEvent
  93. for trk in chan_map.itervalues():
  94. trk.append(ev)
  95. items = chan_map.items()
  96. items.sort(key=lambda pair: pair[0])
  97. for chn, trk in items:
  98. pat.append(trk)
  99. print 'Split', len(old_pat), 'tracks into', len(pat), 'tracks by channel'
  100. if options.chansfname:
  101. midi.write_midifile(options.chansfname, pat)
  102. ##### Merge events from all tracks into one master list, annotated with track and absolute times #####
  103. print 'Merging events...'
  104. class MergeEvent(object):
  105. __slots__ = ['ev', 'tidx', 'abstime']
  106. def __init__(self, ev, tidx, abstime):
  107. self.ev = ev
  108. self.tidx = tidx
  109. self.abstime = abstime
  110. def __repr__(self):
  111. return '<ME %r in %d @%f>'%(self.ev, self.tidx, self.abstime)
  112. events = []
  113. bpm_at = {0: 120}
  114. for tidx, track in enumerate(pat):
  115. abstime = 0
  116. absticks = 0
  117. for ev in track:
  118. if isinstance(ev, midi.SetTempoEvent):
  119. absticks += ev.tick
  120. bpm_at[absticks] = ev.bpm
  121. else:
  122. if isinstance(ev, midi.NoteOnEvent) and ev.velocity == 0:
  123. ev.__class__ = midi.NoteOffEvent #XXX Oww
  124. bpm = filter(lambda pair: pair[0] <= absticks, sorted(bpm_at.items(), key=lambda pair: pair[0]))[-1][1]
  125. abstime += (60.0 * ev.tick) / (bpm * pat.resolution)
  126. absticks += ev.tick
  127. events.append(MergeEvent(ev, tidx, abstime))
  128. print 'Sorting events...'
  129. events.sort(key = lambda ev: ev.abstime)
  130. ##### Use merged events to construct a set of streams with non-overlapping durations #####
  131. print 'Generating streams...'
  132. class DurationEvent(MergeEvent):
  133. __slots__ = ['duration']
  134. def __init__(self, me, dur):
  135. MergeEvent.__init__(self, me.ev, me.tidx, me.abstime)
  136. self.duration = dur
  137. class NoteStream(object):
  138. __slots__ = ['history', 'active']
  139. def __init__(self):
  140. self.history = []
  141. self.active = None
  142. def IsActive(self):
  143. return self.active is not None
  144. def Activate(self, mev):
  145. self.active = mev
  146. def Deactivate(self, mev):
  147. self.history.append(DurationEvent(self.active, mev.abstime - self.active.abstime))
  148. self.active = None
  149. def WouldDeactivate(self, mev):
  150. if not self.IsActive():
  151. return False
  152. return mev.ev.pitch == self.active.ev.pitch and mev.tidx == self.active.tidx
  153. class NSGroup(object):
  154. __slots__ = ['streams', 'filter', 'name']
  155. def __init__(self, filter=None, name=None):
  156. self.streams = []
  157. self.filter = (lambda mev: True) if filter is None else filter
  158. self.name = name
  159. def Accept(self, mev):
  160. if not self.filter(mev):
  161. return False
  162. for stream in self.streams:
  163. if not stream.IsActive():
  164. stream.Activate(mev)
  165. break
  166. else:
  167. stream = NoteStream()
  168. self.streams.append(stream)
  169. stream.Activate(mev)
  170. return True
  171. notegroups = []
  172. auxstream = []
  173. if not options.no_perc:
  174. notegroups.append(NSGroup(filter = lambda mev: mev.ev.channel == 10, name='perc'))
  175. for spec in options.tracks:
  176. if spec is TRACKS:
  177. for tidx in xrange(len(pat)):
  178. notegroups.append(NSGroup(filter = lambda mev, tidx=tidx: mev.tidx == tidx, name = 'trk%d'%(tidx,)))
  179. else:
  180. if '=' in spec:
  181. name, _, spec = spec.partition('=')
  182. else:
  183. name = None
  184. notegroups.append(NSGroup(filter = eval("lambda ev: "+spec), name = name))
  185. print 'Initial group mappings:'
  186. for group in notegroups:
  187. print ('<anonymous>' if group.name is None else group.name), '<=', group.filter
  188. for mev in events:
  189. if isinstance(mev.ev, midi.NoteOnEvent):
  190. for group in notegroups:
  191. if group.Accept(mev):
  192. break
  193. else:
  194. group = NSGroup()
  195. group.Accept(mev)
  196. notegroups.append(group)
  197. elif isinstance(mev.ev, midi.NoteOffEvent):
  198. for group in notegroups:
  199. found = False
  200. for stream in group.streams:
  201. if stream.WouldDeactivate(mev):
  202. stream.Deactivate(mev)
  203. found = True
  204. break
  205. if found:
  206. break
  207. else:
  208. print 'WARNING: Did not match %r with any stream deactivation.'%(mev,)
  209. else:
  210. auxstream.append(mev)
  211. lastabstime = events[-1].abstime
  212. for group in notegroups:
  213. for ns in group.streams:
  214. if ns.IsActive():
  215. print 'WARNING: Active notes at end of playback.'
  216. ns.Deactivate(MergeEvent(ns.active, ns.active.tidx, lastabstime))
  217. print 'Final group mappings:'
  218. for group in notegroups:
  219. print ('<anonymous>' if group.name is None else group.name), '<=', group.filter, '(', len(group.streams), 'streams)'
  220. print 'Generated %d streams in %d groups'%(sum(map(lambda x: len(x.streams), notegroups)), len(notegroups))
  221. print 'Playtime:', lastabstime, 'seconds'
  222. ##### Write to XML and exit #####
  223. ivmeta = ET.SubElement(iv, 'meta')
  224. ivbpms = ET.SubElement(ivmeta, 'bpms')
  225. abstime = 0
  226. prevticks = 0
  227. prev_bpm = 120
  228. for absticks, bpm in sorted(bpm_at.items(), key = lambda pair: pair[0]):
  229. abstime += ((absticks - prevticks) * 60.0) / (prev_bpm * pat.resolution)
  230. prevticks = absticks
  231. ivbpm = ET.SubElement(ivbpms, 'bpm')
  232. ivbpm.set('bpm', str(bpm))
  233. ivbpm.set('ticks', str(absticks))
  234. ivbpm.set('time', str(abstime))
  235. ivstreams = ET.SubElement(iv, 'streams')
  236. x = 0
  237. while(x<options.repeaterNumber):
  238. for group in notegroups:
  239. for ns in group.streams:
  240. ivns = ET.SubElement(ivstreams, 'stream')
  241. ivns.set('type', 'ns')
  242. if group.name is not None:
  243. ivns.set('group', group.name)
  244. for note in ns.history:
  245. ivnote = ET.SubElement(ivns, 'note')
  246. ivnote.set('pitch', str(note.ev.pitch))
  247. ivnote.set('vel', str(note.ev.velocity))
  248. ivnote.set('time', str(note.abstime))
  249. ivnote.set('dur', str(note.duration))
  250. x+=1
  251. print x
  252. if(x>=options.repeaterNumber and options.repeaterNumber!=1):
  253. break
  254. if(x>=options.repeaterNumber and options.repeaterNumber!=1):
  255. break
  256. if(x>=options.repeaterNumber and options.repeaterNumber!=1):
  257. break
  258. ivaux = ET.SubElement(ivstreams, 'stream')
  259. ivaux.set('type', 'aux')
  260. fw = midi.FileWriter()
  261. fw.RunningStatus = None # XXX Hack
  262. for mev in auxstream:
  263. ivev = ET.SubElement(ivaux, 'ev')
  264. ivev.set('time', str(mev.abstime))
  265. ivev.set('data', repr(fw.encode_midi_event(mev.ev)))
  266. print 'Done.'
  267. open(os.path.splitext(os.path.basename(fname))[0]+'.iv', 'w').write(ET.tostring(iv))