mkiv.py 21 KB

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