mkiv.py 40 KB

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