mkiv.py 41 KB

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