mkiv.py 34 KB

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