3 # midi2ly.py -- LilyPond midi import script
5 # source file of the GNU LilyPond music typesetter
7 # convert MIDI to LilyPond source
13 * test on weird and unquantised midi input (lily-devel)
15 * update doc and manpage
17 * simply insert clef changes whenever too many ledger lines
18 [to avoid tex capacity exceeded]
19 * do not ever quant skips
20 * better lyrics handling
21 * [see if it is feasible to] move ly-classes to library for use in
22 other converters, while leaving midi specific stuff here
30 sys.path.append ('@datadir@/python')
31 sys.path.append ('@datadir@/buildscripts/out')
32 sys.path.append ('@datadir@/modules/out')
38 gettext.bindtextdomain ('lilypond', '@localedir@')
39 gettext.textdomain ('lilypond')
45 # Attempt to fix problems with limited stack size set by Python!
46 # Sets unlimited stack size. Note that the resource module only
47 # is available on UNIX.
50 resource.setrlimit (resource.RLIMIT_STACK, (-1, -1))
54 program_name = 'midi2ly [experimental]'
55 package_name = 'lilypond'
56 help_summary = _ ("Convert MIDI to LilyPond source")
58 option_definitions = [
59 ('', 'a', 'absolute-pitches', _ ("print absolute pitches")),
60 (_ ("DUR"), 'd', 'duration-quant', _ ("quantise note durations on DUR")),
61 ('', 'e', 'explicit-durations', _ ("print explicit durations")),
62 ('', 'h', 'help', _ ("this help")),
63 (_ ("ALT[:MINOR]"), 'k', 'key', _ ("set key: ALT=+sharps|-flats; MINOR=1")),
64 (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
65 (_ ("DUR"), 's', 'start-quant', _ ("quantise note starts on DUR")),
66 (_ ("DUR*NUM/DEN"), 't', 'allow-tuplet', _ ("allow tuplet durations DUR*NUM/DEN")),
67 ('', 'V', 'verbose', _ ("verbose")),
68 ('', 'v', 'version', _ ("print version number")),
69 ('', 'w', 'warranty', _ ("show warranty and copyright")),
70 ('', 'x', 'text-lyrics', _ ("treat every text as a lyric")),
77 allowed_durs = (1, 2, 4, 8, 16, 32, 64, 128)
78 def __init__ (self, clocks):
81 self.clocks = duration_quant_clocks
82 (self.dur, self.num, self.den) = self.dur_num_den (clocks)
84 def dur_num_den (self, clocks):
85 for i in range (len (allowed_tuplet_clocks)):
86 if clocks == allowed_tuplet_clocks[i]:
87 return allowed_tuplets[i]
89 dur = 0; num = 1; den = 1;
90 g = gcd (clocks, clocks_per_1)
92 (dur, num) = (clocks_per_1 / g, clocks / g)
93 if not dur in self.allowed_durs:
94 dur = 4; num = clocks; den = clocks_per_4
95 return (dur, num, den)
101 elif self.num == 3 and self.dur != 1:
102 s = '%d.' % (self.dur / 2)
104 s = '%d*%d' % (self.dur, self.num)
106 s = '%d*%d/%d' % (self.dur, self.num, self.den)
108 global reference_note
109 reference_note.duration = self
113 def compare (self, other):
114 return self.clocks - other.clocks
123 names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
124 alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
125 alteration_names = ('eses', 'es', '', 'is' , 'isis')
127 def __init__ (self, clocks, pitch, velocity):
129 self.velocity = velocity
132 self.duration = Duration (clocks)
133 (self.octave, self.notename, self.alteration) = self.o_n_a ()
137 # minor scale: la-la (= + 5) '''
139 n = self.names[(self.pitch) % 12]
140 a = self.alterations[(self.pitch) % 12]
143 a = - self.alterations[(self.pitch) % 12]
146 # By tradition, all scales now consist of a sequence
147 # of 7 notes each with a distinct name, from amongst
148 # a b c d e f g. But, minor scales have a wide
149 # second interval at the top - the 'leading note' is
150 # sharped. (Why? it just works that way! Anything
151 # else doesn't sound as good and isn't as flexible at
152 # saying things. In medieval times, scales only had 6
153 # notes to avoid this problem - the hexachords.)
155 # So, the d minor scale is d e f g a b-flat c-sharp d
156 # - using d-flat for the leading note would skip the
157 # name c and duplicate the name d. Why isn't c-sharp
158 # put in the key signature? Tradition. (It's also
159 # supposedly based on the Pythagorean theory of the
160 # cycle of fifths, but that really only applies to
161 # major scales...) Anyway, g minor is g a b-flat c d
162 # e-flat f-sharp g, and all the other flat minor keys
163 # end up with a natural leading note. And there you
166 # John Sankey <bf250@freenet.carleton.ca>
168 # Let's also do a-minor: a b c d e f gis a
172 o = self.pitch / 12 - 4
176 if key.sharps == 0 and key.flats == 0 \
177 and n == 5 and a == -1:
180 elif key.flats == 1 and n == 1 and a == -1:
183 elif key.flats == 2 and n == 4 and a == -1:
186 elif key.sharps == 5 and n == 4 and a == 0:
189 elif key.sharps == 6 and n == 1 and a == 0:
192 elif key.sharps == 7 and n == 5 and a == 0:
196 if key.flats >= 6 and n == 6 and a == 0:
197 n = 0; a = -1; o = o + 1
199 if key.flats >= 7 and n == 2 and a == 0:
203 if key.sharps >= 3 and n == 3 and a == 0:
206 if key.sharps >= 4 and n == 0 and a == 0:
207 n = 6; a = 1; o = o - 1
212 s = chr ((self.notename + 2) % 7 + ord ('a'))
213 s = s + self.alteration_names[self.alteration + 2]
217 delta = self.pitch - reference_note.pitch
218 commas = sign (delta) * (abs (delta) / 12)
220 * (self.notename - reference_note.notename) + 7) \
222 or ((self.notename == reference_note.notename) \
223 and (abs (delta) > 4) and (abs (delta) < 12)):
224 commas = commas + sign (delta)
229 s = s + "," * -commas
231 if explicit_durations_p \
232 or Duration.compare (self.duration, reference_note.duration):
233 s = s + self.duration.dump ()
235 global reference_note
236 reference_note = self
242 def __init__ (self, num, den):
247 def bar_clocks (self):
248 return clocks_per_1 * self.num / self.den
253 return '\n ' + '\\time %d/%d ' % (self.num, self.den) + '\n '
256 def __init__ (self, seconds_per_1):
258 self.seconds_per_1 = seconds_per_1
261 return '\n ' + '\\tempo 4 = %d ' % (4 * 60 / self.seconds_per_1) + '\n '
264 clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
265 def __init__ (self, type):
269 return '\n \\clef %s\n ' % self.clefs[self.type]
272 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
273 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
275 def __init__ (self, sharps, flats, minor):
286 if self.sharps and self.flats:
287 s = '\\keysignature %s ' % 'TODO'
291 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
293 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
296 name = chr ((k + 2) % 7 + ord ('a'))
298 name = chr ((k + 2) % 7 + ord ('a'))
300 # fis cis gis dis ais eis bis
301 sharps = (2, 4, 6, 1, 3, 5, 7)
302 # bes es as des ges ces fes
303 flats = (6, 4, 2, 7, 5, 3, 1)
306 if flats[k] <= self.flats:
309 if sharps[k] <= self.sharps:
313 name = name + Note.alteration_names[a + 2]
321 return '\n\n ' + s + '\n '
329 'SEQUENCE_TRACK_NAME',
335 def __init__ (self, type, text):
341 # urg, we should be sure that we're in a lyrics staff
342 if self.type == midi.LYRIC:
343 s = '"%s"' % self.text
344 d = Duration (self.clocks)
345 if explicit_durations_p \
346 or Duration.compare (d,
347 reference_note.duration):
348 s = s + Duration (self.clocks).dump ()
351 s = '\n % [' + self.text_types[self.type] + '] ' + self.text + '\n '
357 scale_steps = [0,2,4,5,7,9,11]
365 start_quant_clocks = 0
367 duration_quant_clocks = 0
369 allowed_tuplet_clocks = []
371 explicit_durations_p = 0
374 def split_track (track):
381 if data[0] > 0x7f and data[0] < 0xf0:
383 e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
393 for v in chs.values ():
394 events = events_on_channel (v)
395 thread = unthread_notes (events)
397 threads.append (thread)
401 def quantise_clocks (clocks, quant):
402 q = int (clocks / quant) * quant
404 for tquant in allowed_tuplet_clocks:
405 if int (clocks / tquant) * tquant == clocks:
407 if 2 * (clocks - q) > quant:
411 def end_note (pitches, notes, t, e):
413 (lt, vel) = pitches[e]
423 if duration_quant_clocks:
424 d = quantise_clocks (d, duration_quant_clocks)
426 d = duration_quant_clocks
429 (lt, Note (d, e, vel)))
434 def events_on_channel (channel):
444 if start_quant_clocks:
445 t = quantise_clocks (t, start_quant_clocks)
448 if e[1][0] == midi.NOTE_OFF \
449 or (e[1][0] == midi.NOTE_ON and e[1][2] == 0):
450 end_note (pitches, notes, t, e[1][1])
452 elif e[1][0] == midi.NOTE_ON:
453 if not pitches.has_key (e[1][1]):
454 pitches[e[1][1]] = (t, e[1][2])
456 # all include ALL_NOTES_OFF
457 elif e[1][0] >= midi.ALL_SOUND_OFF \
458 and e[1][0] <= midi.POLY_MODE_ON:
459 for i in pitches.keys ():
460 end_note (pitches, notes, t, i)
462 elif e[1][0] == midi.META_EVENT:
463 if e[1][1] == midi.END_OF_TRACK:
464 for i in pitches.keys ():
465 end_note (pitches, notes, t, i)
468 elif e[1][1] == midi.SET_TEMPO:
469 (u0, u1, u2) = map (ord, e[1][2])
470 us_per_4 = u2 + 256 * (u1 + 256 * u0)
471 seconds_per_1 = us_per_4 * 4 / 1e6
472 events.append ((t, Tempo (seconds_per_1)))
473 elif e[1][1] == midi.TIME_SIGNATURE:
474 (num, dur, clocks4, count32) = map (ord, e[1][2])
476 events.append ((t, Time (num, den)))
477 elif e[1][1] == midi.KEY_SIGNATURE:
478 (alterations, minor) = map (ord, e[1][2])
481 if alterations < 127:
484 flats = 256 - alterations
486 k = Key (sharps, flats, minor)
487 events.append ((t, k))
489 # ugh, must set key while parsing
490 # because Note init uses key
491 # Better do Note.calc () at dump time?
495 elif e[1][1] == midi.LYRIC \
496 or (text_lyrics_p and e[1][1] == midi.TEXT_EVENT):
498 last_lyric.clocks = t - last_time
499 events.append ((last_time, last_lyric))
501 last_lyric = Text (midi.LYRIC, e[1][2])
503 elif e[1][1] >= midi.SEQUENCE_NUMBER \
504 and e[1][1] <= midi.CUE_POINT:
505 events.append ((t, Text (e[1][1], e[1][2])))
508 sys.stderr.write ("SKIP: %s\n" % `e`)
512 sys.stderr.write ("SKIP: %s\n" % `e`)
516 # last_lyric.clocks = t - last_time
518 last_lyric.clocks = clocks_per_4
519 events.append ((last_time, last_lyric))
524 if i < len (events) and notes[0][0] >= events[i][0]:
527 events.insert (i, notes[0])
531 def unthread_notes (channel):
540 if e[1].__class__ == Note \
541 and ((t == start_busy_t \
542 and e[1].clocks + t == end_busy_t) \
546 end_busy_t = t + e[1].clocks
547 elif e[1].__class__ == Time \
548 or e[1].__class__ == Key \
549 or e[1].__class__ == Text \
550 or e[1].__class__ == Tempo:
554 threads.append (thread)
569 def dump_skip (skip, clocks):
570 return skip + Duration (clocks).dump () + ' '
579 if i.__class__ == Note:
584 s = s + dump (notes[0])
585 elif len (notes) > 1:
586 global reference_note
588 s = s + notes[0].dump ()
596 def dump_bar_line (last_bar_t, t, bar_count):
598 bar_t = time.bar_clocks ()
599 if t - last_bar_t >= bar_t:
600 bar_count = bar_count + (t - last_bar_t) / bar_t
602 if t - last_bar_t == bar_t:
603 s = '|\n %% %d\n ' % bar_count
606 # urg, this will barf at meter changes
607 last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
609 return (s, last_bar_t, bar_count)
612 def dump_channel (thread, skip):
613 global key, reference_note, time
617 # urg LilyPond doesn't start at c4, but
618 # remembers from previous tracks!
619 # reference_note = Note (clocks_per_4, 4*12, 0)
620 reference_note = Note (0, 4*12, 0)
626 if last_e and last_e[0] == e[0]:
630 chs.append ((last_e[0], ch))
637 chs.append ((last_e[0], ch))
647 i = string.rfind (lines[-1], '\n') + 1
648 if len (lines[-1][i:]) > LINE_BELL:
652 lines[-1] = lines[-1] + dump_skip (skip, t-last_t)
654 errorport.write ('BUG: time skew')
656 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
658 lines[-1] = lines[-1] + s
660 lines[-1] = lines[-1] + dump_chord (ch[1])
664 if i.clocks > clocks:
669 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
671 lines[-1] = lines[-1] + s
673 return string.join (lines, '\n ') + '\n'
676 return 'track%c' % (i + ord ('A'))
678 def channel_name (i):
679 return 'channel%c' % (i + ord ('A'))
681 def dump_track (channels, n):
683 track = track_name (n)
684 clef = guess_clef (channels)
686 for i in range (len (channels)):
687 channel = channel_name (i)
688 item = thread_first_item (channels[i])
690 if item and item.__class__ == Note:
692 s = s + '%s = \\notes' % (track + channel)
694 s = s + '\\relative c '
695 elif item and item.__class__ == Text:
697 s = s + '%s = \\lyrics ' % (track + channel)
700 # must be in \notes mode for parsing \skip
701 s = s + '%s = \\notes ' % (track + channel)
703 s = s + ' ' + dump_channel (channels[i][0], skip)
706 s = s + '%s = <\n' % track
709 s = s + clef.dump () + '\n'
711 for i in range (len (channels)):
712 channel = channel_name (i)
713 item = thread_first_item (channels[i])
714 if item and item.__class__ == Text:
715 s = s + ' \\context Lyrics = %s \\%s\n' % (channel,
718 s = s + ' \\context Voice = %s \\%s\n' % (channel,
723 def thread_first_item (thread):
726 if event[1].__class__ == Note \
727 or (event[1].__class__ == Text \
728 and event[1].type == midi.LYRIC):
732 def track_first_item (track):
734 return thread_first_item (thread)
736 def guess_clef (track):
742 if event[1].__class__ == Note:
744 p = p + event[1].pitch
745 if i and p / i <= 3*12:
747 elif i and p / i <= 5*12:
749 elif i and p / i >= 7*12:
755 def convert_midi (f, o):
756 global clocks_per_1, clocks_per_4, key
758 str = open (f).read ()
759 midi_dump = midi.parse (str)
761 clocks_per_1 = midi_dump[0][1]
762 clocks_per_4 = clocks_per_1 / 4
764 global start_quant, start_quant_clocks
766 start_quant_clocks = clocks_per_1 / start_quant
768 global duration_quant, duration_quant_clocks
770 duration_quant_clocks = clocks_per_1 / duration_quant
772 global allowed_tuplet_clocks
773 allowed_tuplet_clocks = []
774 for (dur, num, den) in allowed_tuplets:
775 allowed_tuplet_clocks.append (clocks_per_1 * num / (dur * den))
778 for t in midi_dump[1]:
780 tracks.append (split_track (t))
782 tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, f)
786 for i in range (len (tracks)):
787 s = s + dump_track (tracks[i], i)
789 s = s + '\n\\score {\n <\n'
790 for i in range (len (tracks)):
791 track = track_name (i)
792 item = track_first_item (tracks[i])
793 if item and item.__class__ == Note:
794 s = s + ' \\context Staff=%s \\%s\n' % (track, track)
795 elif item and item.__class__ == Text:
796 s = s + ' \\context Lyrics=%s \\%s\n' % (track, track)
799 progress (_ ("%s output to `%s'...") % ('LY', o))
810 (sh, long) = getopt_args (__main__.option_definitions)
812 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
813 except getopt.error, s:
814 errorport.write ('\n')
815 errorport.write (_ ("error: ") + _ ("getopt says: `%s\'" % s))
816 errorport.write ('\n')
817 errorport.write ('\n')
827 elif o == '--help' or o == '-h':
829 errorport.write ('\n')
830 errorport.write (_ ("Example:"))
831 errorport.write (r'''
832 midi2ly --key=-2:1 --duration-quant=32 \
833 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
836 elif o == '--output' or o == '-o':
838 elif o == '--verbose' or o == '-V':
840 elif o == '--version' or o == '-v':
843 elif o == '--warranty' or o == '-w':
844 status = system ('lilypond -w', ignore_error = 1)
850 elif o == '--absolute-pitches' or o == '-a':
853 elif o == '--duration-quant' or o == '-d':
854 global duration_quant
855 duration_quant = string.atoi (a)
856 elif o == '--explicit-durations' or o == '-e':
857 global explicit_durations_p
858 explicit_durations_p = 1
859 elif o == '--key' or o == '-k':
860 (alterations, minor) = map (string.atoi, string.split (a + ':0', ':'))[0:2]
866 flats = - alterations
868 key = Key (sharps, flats, minor)
869 elif o == '--start-quant' or o == '-s':
870 global start_quant, start_quant_clocks
871 start_quant = string.atoi (a)
872 elif o == '--allow-tuplet' or o == '-t':
873 global allowed_tuplets
874 a = string.replace (a, '/', '*')
875 tuplet = map (string.atoi, string.split (a, '*'))
876 allowed_tuplets.append (tuplet)
877 # lots of midi files use plain text for lyric events
878 elif o == '--text-lyrics' or o == '-x':
882 if not files or files[0] == '-':
884 # FIXME: read from stdin when files[0] = '-'
886 errorport.write (program_name + ":" + _ ("error: ") + _ ("no files specified on command line.") + '\n')
893 g = strip_extension (g, '.midi')
894 g = strip_extension (g, '.mid')
895 g = strip_extension (g, '.MID')
896 (outdir, outbase) = ('','')
900 outbase = os.path.basename (g)
901 o = os.path.join (outdir, outbase + '-midi.ly')
902 elif output_name[-1] == os.sep:
904 outbase = os.path.basename (g)
905 os.path.join (outdir, outbase + '-gen.ly')
908 (outdir, outbase) = os.path.split (o)
911 mkdir_p (outdir, 0777)