mkiv.py 21 KB

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