mkiv.py 40 KB

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