mkiv.py 11 KB

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