mkiv.py 40 KB

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