mkiv.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  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. '''
  7. import xml.etree.ElementTree as ET
  8. import midi
  9. import sys
  10. import os
  11. import optparse
  12. import math
  13. TRACKS = object()
  14. PROGRAMS = object()
  15. parser = optparse.OptionParser()
  16. parser.add_option('-s', '--channel-split', dest='chansplit', action='store_true', help='Split MIDI channels into independent tracks (as far as -T is concerned)')
  17. parser.add_option('-S', '--split-out', dest='chansfname', help='Store the split-format MIDI back into the specified file')
  18. 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)')
  19. parser.add_option('-T', '--track-split', dest='tracks', action='append_const', const=TRACKS, help='Ensure all tracks are on non-mutual streams')
  20. parser.add_option('-t', '--track', dest='tracks', action='append', help='Reserve an exclusive set of streams for certain conditions (try --help-conds)')
  21. parser.add_option('--help-conds', dest='help_conds', action='store_true', help='Print help on filter conditions for streams')
  22. 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)')
  23. parser.add_option('-P', '--percussion', dest='perc', help='Which percussion standard to use to automatically filter to "perc" (GM, GM2, or none)')
  24. parser.add_option('-f', '--fuckit', dest='fuckit', action='store_true', help='Use the Python Error Steamroller when importing MIDIs (useful for extended formats)')
  25. parser.add_option('-v', '--verbose', dest='verbose', action='store_true', help='Be verbose; show important parts about the MIDI scheduling process')
  26. 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)')
  27. 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)')
  28. 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')
  29. parser.add_option('--modwheel-freq-freq', dest='modffreq', type='float', help='Frequency of modulation periods (sinusoids) of the modwheel acting on the base pitch')
  30. 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')
  31. parser.add_option('--modwheel-amp-freq', dest='modafreq', type='float', help='Frequency of modulation periods (sinusoids) of the modwheel acting on amplitude')
  32. parser.add_option('--modwheel-res', dest='modres', type='float', help='(Fractional) seconds by which to resolve modwheel events (0 to disable)')
  33. parser.add_option('--modwheel-continuous', dest='modcont', action='store_true', help='Keep phase continuous in global time (don\'t reset to 0 for each note)')
  34. parser.add_option('--string-res', dest='stringres', type='float', help='(Fractional) seconds by which to resolve string models (0 to disable)')
  35. parser.add_option('--string-max', dest='stringmax', type='int', help='Maximum number of events to generate per single input event')
  36. parser.add_option('--string-rate-on', dest='stringonrate', type='float', help='Rate (amplitude / sec) by which to exponentially decay in the string model while a note is active')
  37. parser.add_option('--string-rate-off', dest='stringoffrate', type='float', help='Rate (amplitude / sec) by which to exponentially decay in the string model after a note ends')
  38. parser.add_option('--string-threshold', dest='stringthres', type='float', help='Amplitude (as fraction of original) at which point the string model event is terminated')
  39. parser.add_option('--tempo', dest='tempo', help='Adjust interpretation of tempo (try "f1"/"global", "f2"/"track")')
  40. parser.add_option('--epsilon', dest='epsilon', type='float', help='Don\'t consider overlaps smaller than this number of seconds (which regularly happen due to precision loss)')
  41. parser.add_option('--vol-pow', dest='vol_pow', type='float', help='Exponent to raise volume changes (adjusts energy per delta volume)')
  42. parser.add_option('-0', '--keep-empty', dest='keepempty', action='store_true', help='Keep (do not cull) events with 0 duration in the output file')
  43. parser.add_option('--no-text', dest='no_text', action='store_true', help='Disable text streams (useful for unusual text encodings)')
  44. parser.set_defaults(tracks=[], perc='GM', deviation=2, tempo='global', modres=0.005, modfdev=2.0, modffreq=8.0, modadev=0.5, modafreq=8.0, stringres=0, stringmax=1024, stringrateon=0.7, stringrateoff=0.4, stringthres=0.02, epsilon=1e-12, vol_pow=2)
  45. options, args = parser.parse_args()
  46. if options.tempo == 'f1':
  47. options.tempo == 'global'
  48. elif options.tempo == 'f2':
  49. options.tempo == 'track'
  50. if options.help_conds:
  51. print '''Filter conditions are used to route events to groups of streams.
  52. Every filter is an expression; internally, this expression is evaluated as the body of a "lambda ev: ".
  53. The "ev" object will be a MergeEvent with the following properties:
  54. -ev.tidx: the originating track index (starting at 0)
  55. -ev.abstime: the real time in seconds of this event relative to the beginning of playback
  56. -ev.bank: the selected bank (all bits)
  57. -ev.prog: the selected program
  58. -ev.mw: the modwheel value
  59. -ev.ev: a midi.NoteOnEvent:
  60. -ev.ev.pitch: the MIDI pitch
  61. -ev.ev.velocity: the MIDI velocity
  62. -ev.ev.channel: the MIDI channel
  63. All valid Python expressions are accepted. Take care to observe proper shell escaping.
  64. Specifying a -t <group>=<filter> will group all streams under a filter; if the <group> part is omitted, no group will be added.
  65. For example:
  66. mkiv -t bass=ev.ev.pitch<35 -t treble=ev.ev.pitch>75 -T -t ev.abstime<10
  67. will cause these groups to be made:
  68. -A group "bass" with all notes with pitch less than 35;
  69. -Of those not in "bass", a group in "treble" with pitch>75;
  70. -Of what is not yet consumed, a series of groups "trkN" where N is the track index (starting at 0), which consumes the rest.
  71. -An (unfortunately empty) unnamed group with events prior to ten real seconds.
  72. As can be seen, order of specification is important. Equally important is the location of -T, which should be at the end.
  73. NoteOffEvents are always matched to the stream which has their corresponding NoteOnEvent (in track, pitch, and channel), and so are
  74. not affected or observed by filters.
  75. If the filters specified are not a complete cover, an anonymous group will be created with no filter to contain the rest. If
  76. it is desired to force this group to have a name, use -t <group>=True. This should be placed at the end.
  77. -T behaves exactly as if:
  78. -t trk0=ev.tidx==0 -t trk1=ev.tidx==1 -t trk2=ev.tidx==2 [...]
  79. had been specified in its place, though it is automatically sized to the number of tracks. Similarly, -P operates as if
  80. -t prg31=ev.prog==31 -t prg81=ev.prog==81 [...]
  81. had been specified, again containing only the programs that were observed in the piece.
  82. Groups for which no streams are generated are not written to the resulting file.'''
  83. exit()
  84. if not args:
  85. parser.print_usage()
  86. exit()
  87. if options.fuckit:
  88. import fuckit
  89. midi.read_midifile = fuckit(midi.read_midifile)
  90. for fname in args:
  91. try:
  92. pat = midi.read_midifile(fname)
  93. except Exception:
  94. import traceback
  95. traceback.print_exc()
  96. print fname, ': Exception occurred, skipping...'
  97. continue
  98. if pat is None:
  99. print fname, ': Too fucked to continue'
  100. continue
  101. iv = ET.Element('iv')
  102. iv.set('version', '1')
  103. iv.set('src', os.path.basename(fname))
  104. print fname, ': MIDI format,', len(pat), 'tracks'
  105. if options.verbose:
  106. print fname, ': MIDI Parameters:', pat.resolution, 'PPQN,', pat.format, 'format'
  107. if options.chansplit:
  108. print 'Splitting channels...'
  109. old_pat = pat
  110. pat = midi.Pattern(resolution=old_pat.resolution)
  111. for track in old_pat:
  112. chan_map = {}
  113. last_abstick = {}
  114. absticks = 0
  115. for ev in track:
  116. absticks += ev.tick
  117. if isinstance(ev, midi.Event):
  118. tick = absticks - last_abstick.get(ev.channel, 0)
  119. last_abstick[ev.channel] = absticks
  120. if options.chanskeep:
  121. newev = ev.copy(tick = tick)
  122. else:
  123. newev = ev.copy(channel=1, tick = tick)
  124. chan_map.setdefault(ev.channel, midi.Track()).append(newev)
  125. else: # MetaEvent
  126. for trk in chan_map.itervalues():
  127. trk.append(ev)
  128. items = chan_map.items()
  129. items.sort(key=lambda pair: pair[0])
  130. for chn, trk in items:
  131. pat.append(trk)
  132. print 'Split', len(old_pat), 'tracks into', len(pat), 'tracks by channel'
  133. if options.chansfname:
  134. midi.write_midifile(options.chansfname, pat)
  135. ##### Merge events from all tracks into one master list, annotated with track and absolute times #####
  136. print 'Merging events...'
  137. class SortEvent(object):
  138. __slots__ = ['ev', 'tidx', 'abstick']
  139. def __init__(self, ev, tidx, abstick):
  140. self.ev = ev
  141. self.tidx = tidx
  142. self.abstick = abstick
  143. sorted_events = []
  144. for tidx, track in enumerate(pat):
  145. absticks = 0
  146. for ev in track:
  147. absticks += ev.tick
  148. sorted_events.append(SortEvent(ev, tidx, absticks))
  149. sorted_events.sort(key=lambda x: x.abstick)
  150. if options.tempo == 'global':
  151. bpm_at = [{0: 120}]
  152. else:
  153. bpm_at = [{0: 120} for i in pat]
  154. print 'Computing tempos...'
  155. for sev in sorted_events:
  156. if isinstance(sev.ev, midi.SetTempoEvent):
  157. if options.debug:
  158. print fname, ': SetTempo at', sev.abstick, 'to', sev.ev.bpm, ':', sev.ev
  159. bpm_at[sev.tidx if options.tempo == 'track' else 0][sev.abstick] = sev.ev.bpm
  160. if options.verbose:
  161. print fname, ': Events:', len(sorted_events)
  162. print fname, ': Resolved global BPM:', bpm_at
  163. if options.debug:
  164. if options.tempo == 'track':
  165. for tidx, bpms in enumerate(bpm_at):
  166. print fname, ': Tempos in track', tidx
  167. btimes = bpms.keys()
  168. for i in range(len(btimes) - 1):
  169. fev = filter(lambda sev: sev.tidx == tidx and sev.abstick >= btimes[i] and sev.abstick < btimes[i+1], sorted_events)
  170. print fname, ': BPM partition', i, 'contains', len(fev), 'events'
  171. else:
  172. btimes = bpm_at[0].keys()
  173. for i in range(len(btimes) - 1):
  174. fev = filter(lambda sev: sev.abstick >= btimes[i] and sev.abstick < btimes[i+1], sorted_events)
  175. print fname, ': BPM partition', i, 'contains', len(fev), 'events'
  176. def at2rt(abstick, bpms):
  177. bpm_segs = bpms.items()
  178. bpm_segs.sort(key=lambda pair: pair[0])
  179. bpm_segs = filter(lambda pair: pair[0] <= abstick, bpm_segs)
  180. rt = 0
  181. atick = 0
  182. if not bpm_segs:
  183. rt = 0
  184. else:
  185. ctick, bpm = bpm_segs[0]
  186. rt = (60.0 * ctick) / (bpm * pat.resolution)
  187. for idx in range(1, len(bpm_segs)):
  188. dt = bpm_segs[idx][0] - bpm_segs[idx-1][0]
  189. bpm = bpm_segs[idx-1][1]
  190. rt += (60.0 * dt) / (bpm * pat.resolution)
  191. if not bpm_segs:
  192. bpm = 120
  193. ctick = 0
  194. else:
  195. ctick, bpm = bpm_segs[-1]
  196. if options.debug:
  197. print 'seg through', bpm_segs, 'final seg', (abstick - ctick, bpm)
  198. rt += (60.0 * (abstick - ctick)) / (bpm * pat.resolution)
  199. return rt
  200. class MergeEvent(object):
  201. __slots__ = ['ev', 'tidx', 'abstime', 'bank', 'prog', 'mw']
  202. def __init__(self, ev, tidx, abstime, bank=0, prog=0, mw=0):
  203. self.ev = ev
  204. self.tidx = tidx
  205. self.abstime = abstime
  206. self.bank = bank
  207. self.prog = prog
  208. self.mw = mw
  209. def copy(self, **kwargs):
  210. args = {'ev': self.ev, 'tidx': self.tidx, 'abstime': self.abstime, 'bank': self.bank, 'prog': self.prog, 'mw': self.mw}
  211. args.update(kwargs)
  212. return MergeEvent(**args)
  213. def __repr__(self):
  214. return '<ME %r in %d on (%d:%d) MW:%d @%f>'%(self.ev, self.tidx, self.bank, self.prog, self.mw, self.abstime)
  215. vol_at = [[{0: 0x3FFF} for i in range(16)] for j in range(len(pat))]
  216. events = []
  217. cur_mw = [[0 for i in range(16)] for j in range(len(pat))]
  218. cur_bank = [[0 for i in range(16)] for j in range(len(pat))]
  219. cur_prog = [[0 for i in range(16)] for j in range(len(pat))]
  220. chg_mw = [[0 for i in range(16)] for j in range(len(pat))]
  221. chg_bank = [[0 for i in range(16)] for j in range(len(pat))]
  222. chg_prog = [[0 for i in range(16)] for j in range(len(pat))]
  223. chg_vol = [[0 for i in range(16)] for j in range(len(pat))]
  224. ev_cnts = [[0 for i in range(16)] for j in range(len(pat))]
  225. tnames = [''] * len(pat)
  226. progs = set([0])
  227. for tidx, track in enumerate(pat):
  228. abstime = 0
  229. absticks = 0
  230. lastbpm = 120
  231. for ev in track:
  232. absticks += ev.tick
  233. abstime = at2rt(absticks, bpm_at[tidx if options.tempo == 'track' else 0])
  234. if options.debug:
  235. print 'tick', absticks, 'realtime', abstime
  236. if isinstance(ev, midi.TrackNameEvent):
  237. tnames[tidx] = ev.text
  238. if isinstance(ev, midi.ProgramChangeEvent):
  239. cur_prog[tidx][ev.channel] = ev.value
  240. progs.add(ev.value)
  241. chg_prog[tidx][ev.channel] += 1
  242. elif isinstance(ev, midi.ControlChangeEvent):
  243. if ev.control == 0: # Bank -- MSB
  244. cur_bank[tidx][ev.channel] = (0x3F & cur_bank[tidx][ev.channel]) | (ev.value << 7)
  245. chg_bank[tidx][ev.channel] += 1
  246. elif ev.control == 32: # Bank -- LSB
  247. cur_bank[tidx][ev.channel] = (0x3F80 & cur_bank[tidx][ev.channel]) | ev.value
  248. chg_bank[tidx][ev.channel] += 1
  249. elif ev.control == 1: # ModWheel -- MSB
  250. cur_mw[tidx][ev.channel] = (0x3F & cur_mw[tidx][ev.channel]) | (ev.value << 7)
  251. chg_mw[tidx][ev.channel] += 1
  252. elif ev.control == 33: # ModWheel -- LSB
  253. cur_mw[tidx][ev.channel] = (0x3F80 & cur_mw[tidx][ev.channel]) | ev.value
  254. chg_mw[tidx][ev.channel] += 1
  255. elif ev.control == 7: # Volume -- MSB
  256. lvtime, lvol = sorted(vol_at[tidx][ev.channel].items(), key = lambda pair: pair[0])[-1]
  257. vol_at[tidx][ev.channel][abstime] = (0x3F & lvol) | (ev.value << 7)
  258. chg_vol[tidx][ev.channel] += 1
  259. elif ev.control == 39: # Volume -- LSB
  260. lvtime, lvol = sorted(vol_at[tidx][ev.channel].items(), key = lambda pair: pair[0])[-1]
  261. vol_at[tidx][ev.channel][abstime] = (0x3F80 & lvol) | ev.value
  262. chg_vol[tidx][ev.channel] += 1
  263. events.append(MergeEvent(ev, tidx, abstime, cur_bank[tidx][ev.channel], cur_prog[tidx][ev.channel], cur_mw[tidx][ev.channel]))
  264. ev_cnts[tidx][ev.channel] += 1
  265. elif isinstance(ev, midi.MetaEventWithText):
  266. events.append(MergeEvent(ev, tidx, abstime))
  267. elif isinstance(ev, midi.Event):
  268. if isinstance(ev, midi.NoteOnEvent) and ev.velocity == 0:
  269. ev.__class__ = midi.NoteOffEvent #XXX Oww
  270. events.append(MergeEvent(ev, tidx, abstime, cur_bank[tidx][ev.channel], cur_prog[tidx][ev.channel], cur_mw[tidx][ev.channel]))
  271. ev_cnts[tidx][ev.channel] += 1
  272. print 'Track name, event count, final banks, bank changes, final programs, program changes, final modwheel, modwheel changes, volume changes:'
  273. for tidx, tname in enumerate(tnames):
  274. 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])), ',', ','.join(map(str, cur_mw[tidx])), ',', ','.join(map(str, chg_mw[tidx])), ',', ','.join(map(str, chg_vol[tidx]))
  275. print 'All programs observed:', progs
  276. print 'Sorting events...'
  277. events.sort(key = lambda ev: ev.abstime)
  278. ##### Use merged events to construct a set of streams with non-overlapping durations #####
  279. print 'Generating streams...'
  280. class DurationEvent(MergeEvent):
  281. __slots__ = ['duration', 'pitch', 'modwheel', 'ampl']
  282. def __init__(self, me, pitch, ampl, dur, modwheel=0):
  283. MergeEvent.__init__(self, me.ev, me.tidx, me.abstime, me.bank, me.prog, me.mw)
  284. self.pitch = pitch
  285. self.ampl = ampl
  286. self.duration = dur
  287. self.modwheel = modwheel
  288. def __repr__(self):
  289. return '<NE %s P:%f A:%f D:%f W:%f>'%(MergeEvent.__repr__(self), self.pitch, self.ampl, self.duration, self.modwheel)
  290. class NoteStream(object):
  291. __slots__ = ['history', 'active', 'bentpitch', 'modwheel']
  292. def __init__(self):
  293. self.history = []
  294. self.active = None
  295. self.bentpitch = None
  296. self.modwheel = 0
  297. def IsActive(self):
  298. return self.active is not None
  299. def Activate(self, mev, bentpitch=None, modwheel=None):
  300. if bentpitch is None:
  301. bentpitch = mev.ev.pitch
  302. self.active = mev
  303. self.bentpitch = bentpitch
  304. if modwheel is not None:
  305. self.modwheel = modwheel
  306. def Deactivate(self, mev):
  307. self.history.append(DurationEvent(self.active, self.bentpitch, self.active.ev.velocity / 127.0, mev.abstime - self.active.abstime, self.modwheel))
  308. self.active = None
  309. self.bentpitch = None
  310. self.modwheel = 0
  311. def WouldDeactivate(self, mev):
  312. if not self.IsActive():
  313. return False
  314. if isinstance(mev.ev, midi.NoteOffEvent):
  315. return mev.ev.pitch == self.active.ev.pitch and mev.tidx == self.active.tidx and mev.ev.channel == self.active.ev.channel
  316. if isinstance(mev.ev, midi.PitchWheelEvent):
  317. return mev.tidx == self.active.tidx and mev.ev.channel == self.active.ev.channel
  318. if isinstance(mev.ev, midi.ControlChangeEvent):
  319. return mev.tidx == self.active.tidx and mev.ev.channel == self.active.ev.channel
  320. raise TypeError('Tried to deactivate with bad type %r'%(type(mev.ev),))
  321. class NSGroup(object):
  322. __slots__ = ['streams', 'filter', 'name']
  323. def __init__(self, filter=None, name=None):
  324. self.streams = []
  325. self.filter = (lambda mev: True) if filter is None else filter
  326. self.name = name
  327. def Accept(self, mev):
  328. if not self.filter(mev):
  329. return False
  330. for stream in self.streams:
  331. if not stream.IsActive():
  332. stream.Activate(mev)
  333. break
  334. else:
  335. stream = NoteStream()
  336. self.streams.append(stream)
  337. stream.Activate(mev)
  338. return True
  339. notegroups = []
  340. auxstream = []
  341. textstream = []
  342. if options.perc and options.perc != 'none':
  343. if options.perc == 'GM':
  344. notegroups.append(NSGroup(filter = lambda mev: mev.ev.channel == 9, name='perc'))
  345. elif options.perc == 'GM2':
  346. notegroups.append(NSGroup(filter = lambda mev: mev.bank == 15360, name='perc'))
  347. else:
  348. print 'Unrecognized --percussion option %r; should be GM, GM2, or none'%(options.perc,)
  349. for spec in options.tracks:
  350. if spec is TRACKS:
  351. for tidx in xrange(len(pat)):
  352. notegroups.append(NSGroup(filter = lambda mev, tidx=tidx: mev.tidx == tidx, name = 'trk%d'%(tidx,)))
  353. elif spec is PROGRAMS:
  354. for prog in progs:
  355. notegroups.append(NSGroup(filter = lambda mev, prog=prog: mev.prog == prog, name = 'prg%d'%(prog,)))
  356. else:
  357. if '=' in spec:
  358. name, _, spec = spec.partition('=')
  359. else:
  360. name = None
  361. notegroups.append(NSGroup(filter = eval("lambda ev: "+spec), name = name))
  362. if options.verbose:
  363. print 'Initial group mappings:'
  364. for group in notegroups:
  365. print ('<anonymous>' if group.name is None else group.name)
  366. for mev in events:
  367. if isinstance(mev.ev, midi.MetaEventWithText):
  368. textstream.append(mev)
  369. elif isinstance(mev.ev, midi.NoteOnEvent):
  370. for group in notegroups:
  371. if group.Accept(mev):
  372. break
  373. else:
  374. group = NSGroup()
  375. group.Accept(mev)
  376. notegroups.append(group)
  377. elif isinstance(mev.ev, midi.NoteOffEvent):
  378. for group in notegroups:
  379. found = False
  380. for stream in group.streams:
  381. if stream.WouldDeactivate(mev):
  382. stream.Deactivate(mev)
  383. found = True
  384. break
  385. if found:
  386. break
  387. else:
  388. print 'WARNING: Did not match %r with any stream deactivation.'%(mev,)
  389. if options.verbose:
  390. print ' Current state:'
  391. for group in notegroups:
  392. print ' Group %r:'%(group.name,)
  393. for stream in group.streams:
  394. print ' Stream: %r'%(stream.active,)
  395. elif options.deviation > 0 and isinstance(mev.ev, midi.PitchWheelEvent):
  396. found = False
  397. for group in notegroups:
  398. for stream in group.streams:
  399. if stream.WouldDeactivate(mev):
  400. base = stream.active.copy(abstime=mev.abstime)
  401. stream.Deactivate(mev)
  402. stream.Activate(base, base.ev.pitch + options.deviation * (mev.ev.pitch / float(0x2000)))
  403. found = True
  404. if not found:
  405. print 'WARNING: Did not find any matching active streams for %r'%(mev,)
  406. if options.verbose:
  407. print ' Current state:'
  408. for group in notegroups:
  409. print ' Group %r:'%(group.name,)
  410. for stream in group.streams:
  411. print ' Stream: %r'%(stream.active,)
  412. elif options.modres > 0 and isinstance(mev.ev, midi.ControlChangeEvent):
  413. found = False
  414. for group in notegroups:
  415. for stream in group.streams:
  416. if stream.WouldDeactivate(mev):
  417. base = stream.active.copy(abstime=mev.abstime)
  418. stream.Deactivate(mev)
  419. stream.Activate(base, stream.bentpitch, mev.mw)
  420. found = True
  421. if not found:
  422. print 'WARNING: Did not find any matching active streams for %r'%(mev,)
  423. if options.verbose:
  424. print ' Current state:'
  425. for group in notegroups:
  426. print ' Group %r:'%(group.name,)
  427. for stream in group.streams:
  428. print ' Stream: %r'%(stream.active,)
  429. else:
  430. auxstream.append(mev)
  431. lastabstime = events[-1].abstime
  432. for group in notegroups:
  433. for ns in group.streams:
  434. if ns.IsActive():
  435. print 'WARNING: Active notes at end of playback.'
  436. ns.Deactivate(MergeEvent(ns.active, ns.active.tidx, lastabstime))
  437. if options.modres > 0:
  438. print 'Resolving modwheel events...'
  439. ev_cnt = 0
  440. for group in notegroups:
  441. for ns in group.streams:
  442. i = 0
  443. while i < len(ns.history):
  444. dev = ns.history[i]
  445. if dev.modwheel > 0:
  446. realpitch = dev.pitch
  447. realamp = dev.ampl
  448. mwamp = float(dev.modwheel) / 0x3FFF
  449. dt = 0.0
  450. origtime = dev.abstime
  451. events = []
  452. while dt < dev.duration:
  453. dev.abstime = origtime + dt
  454. if options.modcont:
  455. t = origtime
  456. else:
  457. t = dt
  458. events.append(DurationEvent(dev, realpitch + mwamp * options.modfdev * math.sin(2 * math.pi * options.modffreq * t), realamp + mwamp * options.modadev * (math.sin(2 * math.pi * options.modafreq * t) - 1.0) / 2.0, min(options.modres, dev.duration - dt), dev.modwheel))
  459. dt += options.modres
  460. ns.history[i:i+1] = events
  461. i += len(events)
  462. ev_cnt += len(events)
  463. if options.verbose:
  464. print 'Event', i, 'note', dev, 'in group', group.name, 'resolved to', len(events), 'events'
  465. if options.debug:
  466. for ev in events:
  467. print '\t', ev
  468. else:
  469. i += 1
  470. print '...resolved', ev_cnt, 'events'
  471. if options.stringres:
  472. print 'Resolving string models...'
  473. st_cnt = sum(sum(len(ns.history) for ns in group.streams) for group in notegroups)
  474. in_cnt = 0
  475. ex_cnt = 0
  476. ev_cnt = 0
  477. dev_grps = []
  478. for group in notegroups:
  479. for ns in group.streams:
  480. i = 0
  481. while i < len(ns.history):
  482. dev = ns.history[i]
  483. ntime = float('inf')
  484. if i + 1 < len(ns.history):
  485. ntime = ns.history[i+1].abstime
  486. dt = 0.0
  487. ampf = 1.0
  488. origtime = dev.abstime
  489. events = []
  490. while dt < dev.duration and ampf * dev.ampl >= options.stringthres:
  491. dev.abstime = origtime + dt
  492. events.append(DurationEvent(dev, dev.pitch, ampf * dev.ampl, min(options.stringres, dev.duration - dt), dev.modwheel))
  493. if len(events) > options.stringmax:
  494. print 'WARNING: Exceeded maximum string model events for event', i
  495. if options.verbose:
  496. print 'Final ampf', ampf, 'dt', dt
  497. break
  498. ampf *= options.stringrateon ** options.stringres
  499. dt += options.stringres
  500. in_cnt += 1
  501. dt = dev.duration
  502. while ampf * dev.ampl >= options.stringthres:
  503. dev.abstime = origtime + dt
  504. events.append(DurationEvent(dev, dev.pitch, ampf * dev.ampl, options.stringres, dev.modwheel))
  505. if len(events) > options.stringmax:
  506. print 'WARNING: Exceeded maximum string model events for event', i
  507. if options.verbose:
  508. print 'Final ampf', ampf, 'dt', dt
  509. break
  510. ampf *= options.stringrateoff ** options.stringres
  511. dt += options.stringres
  512. ex_cnt += 1
  513. if events:
  514. for j in xrange(len(events) - 1):
  515. cur, next = events[j], events[j + 1]
  516. if abs(cur.abstime + cur.duration - next.abstime) > options.epsilon:
  517. print 'WARNING: String model events cur: ', cur, 'next:', next, 'have gap/overrun of', next.abstime - (cur.abstime + cur.duration)
  518. dev_grps.append(events)
  519. else:
  520. print 'WARNING: Event', i, 'note', dev, ': No events?'
  521. if options.verbose:
  522. print 'Event', i, 'note', dev, 'in group', group.name, 'resolved to', len(events), 'events'
  523. if options.debug:
  524. for ev in events:
  525. print '\t', ev
  526. i += 1
  527. ev_cnt += len(events)
  528. print '...resolved', ev_cnt, 'events (+', ev_cnt - st_cnt, ',', in_cnt, 'inside', ex_cnt, 'extra), resorting streams...'
  529. for group in notegroups:
  530. group.streams = []
  531. dev_grps.sort(key = lambda evg: evg[0].abstime)
  532. for devgr in dev_grps:
  533. dev = devgr[0]
  534. for group in notegroups:
  535. if group.filter(dev):
  536. grp = group
  537. break
  538. else:
  539. grp = NSGroup()
  540. notegroups.append(grp)
  541. for ns in grp.streams:
  542. if not ns.history:
  543. ns.history.extend(devgr)
  544. break
  545. last = ns.history[-1]
  546. if dev.abstime >= last.abstime + last.duration - 1e-3:
  547. ns.history.extend(devgr)
  548. break
  549. else:
  550. ns = NoteStream()
  551. grp.streams.append(ns)
  552. ns.history.extend(devgr)
  553. scnt = 0
  554. for group in notegroups:
  555. for ns in group.streams:
  556. scnt += 1
  557. print 'Final sort:', len(notegroups), 'groups with', scnt, 'streams'
  558. if not options.keepempty:
  559. print 'Culling empty events...'
  560. ev_cnt = 0
  561. for group in notegroups:
  562. for ns in group.streams:
  563. i = 0
  564. while i < len(ns.history):
  565. if ns.history[i].duration == 0.0:
  566. del ns.history[i]
  567. ev_cnt += 1
  568. else:
  569. i += 1
  570. print '...culled', ev_cnt, 'events'
  571. if options.verbose:
  572. print 'Final group mappings:'
  573. for group in notegroups:
  574. print ('<anonymous>' if group.name is None else group.name), '<=', '(', len(group.streams), 'streams)'
  575. print 'Final volume resolution...'
  576. for group in notegroups:
  577. for ns in group.streams:
  578. for ev in ns.history:
  579. t, vol = sorted(filter(lambda pair: pair[0] <= ev.abstime, vol_at[ev.tidx][ev.ev.channel].items()), key=lambda pair: pair[0])[-1]
  580. ev.ampl *= (float(vol) / 0x3FFF) ** options.vol_pow
  581. print 'Checking consistency...'
  582. for group in notegroups:
  583. if options.verbose:
  584. print 'Group', '<None>' if group.name is None else group.name, 'with', len(group.streams), 'streams...',
  585. ecnt = 0
  586. for ns in group.streams:
  587. for i in xrange(len(ns.history) - 1):
  588. cur, next = ns.history[i], ns.history[i + 1]
  589. if cur.abstime + cur.duration > next.abstime + options.epsilon:
  590. print 'WARNING: event', i, 'collides with next event (@', cur.abstime, '+', cur.duration, 'next @', next.abstime, ';', next.abstime - (cur.abstime + cur.duration), 'overlap)'
  591. ecnt += 1
  592. if cur.abstime > next.abstime:
  593. print 'WARNING: event', i + 1, 'out of sort order (@', cur.abstime, 'next @', next.abstime, ';', cur.abstime - next.abstime, 'underlap)'
  594. ecnt += 1
  595. if options.verbose:
  596. if ecnt > 0:
  597. print '...', ecnt, 'errors occured'
  598. else:
  599. print 'ok'
  600. print 'Generated %d streams in %d groups'%(sum(map(lambda x: len(x.streams), notegroups)), len(notegroups))
  601. print 'Playtime:', lastabstime, 'seconds'
  602. ##### Write to XML and exit #####
  603. ivmeta = ET.SubElement(iv, 'meta')
  604. abstime = 0
  605. prevticks = 0
  606. prev_bpm = 120
  607. for tidx, bpms in enumerate(bpm_at):
  608. ivbpms = ET.SubElement(ivmeta, 'bpms', track=str(tidx))
  609. for absticks, bpm in sorted(bpms.items(), key = lambda pair: pair[0]):
  610. abstime += ((absticks - prevticks) * 60.0) / (prev_bpm * pat.resolution)
  611. prevticks = absticks
  612. ivbpm = ET.SubElement(ivbpms, 'bpm')
  613. ivbpm.set('bpm', str(bpm))
  614. ivbpm.set('ticks', str(absticks))
  615. ivbpm.set('time', str(abstime))
  616. ivstreams = ET.SubElement(iv, 'streams')
  617. for group in notegroups:
  618. for ns in group.streams:
  619. ivns = ET.SubElement(ivstreams, 'stream')
  620. ivns.set('type', 'ns')
  621. if group.name is not None:
  622. ivns.set('group', group.name)
  623. for note in ns.history:
  624. ivnote = ET.SubElement(ivns, 'note')
  625. ivnote.set('pitch', str(note.pitch))
  626. ivnote.set('vel', str(int(note.ampl * 127.0)))
  627. ivnote.set('ampl', str(note.ampl))
  628. ivnote.set('time', str(note.abstime))
  629. ivnote.set('dur', str(note.duration))
  630. if not options.no_text:
  631. ivtext = ET.SubElement(ivstreams, 'stream', type='text')
  632. for tev in textstream:
  633. text = tev.ev.text
  634. text = text.decode('utf8')
  635. ivev = ET.SubElement(ivtext, 'text', time=str(tev.abstime), type=type(tev.ev).__name__, text=text)
  636. ivaux = ET.SubElement(ivstreams, 'stream')
  637. ivaux.set('type', 'aux')
  638. fw = midi.FileWriter()
  639. fw.RunningStatus = None # XXX Hack
  640. for mev in auxstream:
  641. ivev = ET.SubElement(ivaux, 'ev')
  642. ivev.set('time', str(mev.abstime))
  643. ivev.set('data', repr(fw.encode_midi_event(mev.ev)))
  644. print 'Done.'
  645. txt = ET.tostring(iv, 'UTF-8')
  646. open(os.path.splitext(os.path.basename(fname))[0]+'.iv', 'wb').write(txt)