mkiv.py 11 KB

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