mkiv.py 36 KB

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