mkiv.py 25 KB

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