3 # msdi2ly.py -- LilyPond midi import script
5 # source file of the GNU LilyPond music typesetter
7 # (c) 1998--2005 Han-Wen Nienhuys <hanwen@cs.uu.nl>
8 # Jan Nieuwenhuizen <janneke@gnu.org>
13 * test on weird and unquantised midi input (lily-devel)
14 * update doc and manpage
16 * simply insert clef changes whenever too many ledger lines
17 [to avoid tex capacity exceeded]
18 * do not ever quant skips
19 * better lyrics handling
20 * [see if it is feasible to] move ly-classes to library for use in
21 other converters, while leaving midi specific stuff here
30 ################################################################
31 # Users of python modules should include this snippet.
33 libdir = '@local_lilypond_libdir@'
34 if not os.path.isdir (libdir):
35 libdir = '@lilypond_libdir@'
38 if os.environ.has_key ('LILYPONDPREFIX'):
39 datadir = os.environ['LILYPONDPREFIX']
40 while datadir[-1] == os.sep:
42 libdir = datadir.replace ('/share/', '/lib/')
44 if os.path.exists (os.path.join (datadir, 'lib/lilypond/@TOPLEVEL_VERSION@/')):
45 libdir = os.path.join (libdir, 'lib/lilypond/@TOPLEVEL_VERSION@/')
47 if os.path.exists (os.path.join (datadir, 'lib/lilypond/current/')):
48 libdir = os.path.join (libdir, 'lib/lilypond/current/')
50 sys.path.insert (0, os.path.join (libdir, 'python'))
52 ################################################################
57 ################################################################
58 ################ CONSTANTS
63 scale_steps = [0,2,4,5,7,9,11]
71 start_quant_clocks = 0
73 duration_quant_clocks = 0
75 allowed_tuplet_clocks = []
77 explicit_durations_p = 0
82 ################################################################
84 localedir = '@localedir@'
87 gettext.bindtextdomain ('lilypond', localedir)
88 gettext.textdomain ('lilypond')
94 program_name = sys.argv[0]
95 program_version = '@TOPLEVEL_VERSION@'
97 errorport = sys.stderr
100 # temp_dir = os.path.join (original_dir, '%s.dir' % program_name)
101 # original_dir = os.getcwd ()
102 # keep_temp_dir_p = 0
105 help_summary = _ ("Convert MIDI to LilyPond source.")
107 option_definitions = [
108 ('', 'a', 'absolute-pitches', _ ("print absolute pitches")),
109 (_ ("DUR"), 'd', 'duration-quant', _ ("quantise note durations on DUR")),
110 ('', 'e', 'explicit-durations', _ ("print explicit durations")),
111 ('', 'h', 'help', _ ("print this help")),
112 (_ ("ALT[:MINOR]"), 'k', 'key', _ ("set key: ALT=+sharps|-flats; MINOR=1")),
113 (_ ("FILE"), 'o', 'output', _ ("write output to FILE")),
114 (_ ("DUR"), 's', 'start-quant', _ ("quantise note starts on DUR")),
115 (_ ("DUR*NUM/DEN"), 't', 'allow-tuplet', _ ("allow tuplet durations DUR*NUM/DEN")),
116 ('', 'V', 'verbose', _ ("be verbose")),
117 ('', 'v', 'version', _ ("print version number")),
118 ('', 'w', 'warranty', _ ("show warranty and copyright")),
119 ('', 'x', 'text-lyrics', _ ("treat every text as a lyric")),
122 ################################################################
123 # lilylib.py -- options and stuff
125 # source file of the GNU LilyPond music typesetter
131 gettext.bindtextdomain ('lilypond', localedir)
132 gettext.textdomain ('lilypond')
138 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
139 program_version = '1.5.17'
142 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
146 sys.stdout.write ('\n')
147 sys.stdout.write (_ ('Copyright (c) %s by') % ' 2001--2005')
148 sys.stdout.write ('\n')
149 sys.stdout.write (' Han-Wen Nienhuys')
150 sys.stdout.write (' Jan Nieuwenhuizen')
151 sys.stdout.write ('\n\n')
152 sys.stdout.write (_ ("Distributed under terms of the GNU General Public License."))
153 sys.stdout.write (_ ("It comes with NO WARRANTY."))
154 sys.stdout.write ('\n')
157 errorport.write (s + '\n')
160 progress (_ ("warning: ") + s)
165 '''Report the error S. Exit by raising an exception. Please
166 do not abuse by trying to catch this error. If you do not want
167 a stack trace, write to the output directly.
175 progress (_ ("error: ") + s)
176 raise _ ("Exiting ... ")
178 def getopt_args (opts):
179 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
194 def option_help_str (o):
195 '''Transform one option description (4-tuple ) into neatly formatted string'''
213 return ' ' + sh + sep + long + arg
216 def options_help_str (opts):
217 '''Convert a list of options into a neatly formatted string'''
223 s = option_help_str (o)
224 strs.append ((s, o[3]))
230 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
234 ls = [(_ ("Usage: %s [OPTIONS]... FILE") % program_name),
240 (options_help_str (option_definitions)),
242 (_ ("Report bugs to %s.") % 'bug-lilypond@gnu.org'),
244 map (sys.stdout.write, ls)
248 Create a temporary directory, and return its name.
251 if not keep_temp_dir_p:
252 temp_dir = tempfile.mktemp (program_name)
254 os.mkdir (temp_dir, 0777)
261 def system (cmd, ignore_error = 0):
262 """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
270 progress (_ ("Invoking `%s\'") % cmd)
273 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
274 msg = name + ': ' + _ ("command exited with value %d") % st
276 warning (msg + ' ' + _ ("(ignored)") + ' ')
284 if not keep_temp_dir_p:
286 progress (_ ("Cleaning %s...") % temp_dir)
287 shutil.rmtree (temp_dir)
290 def strip_extension (f, ext):
291 (p, e) = os.path.splitext (f)
296 ################################################################
298 ################################################################
304 allowed_durs = (1, 2, 4, 8, 16, 32, 64, 128)
305 def __init__ (self, clocks):
308 self.clocks = duration_quant_clocks
309 (self.dur, self.num, self.den) = self.dur_num_den (clocks)
311 def dur_num_den (self, clocks):
312 for i in range (len (allowed_tuplet_clocks)):
313 if clocks == allowed_tuplet_clocks[i]:
314 return allowed_tuplets[i]
316 dur = 0; num = 1; den = 1;
317 g = gcd (clocks, clocks_per_1)
319 (dur, num) = (clocks_per_1 / g, clocks / g)
320 if not dur in self.allowed_durs:
321 dur = 4; num = clocks; den = clocks_per_4
322 return (dur, num, den)
328 elif self.num == 3 and self.dur != 1:
329 s = '%d.' % (self.dur / 2)
331 s = '%d*%d' % (self.dur, self.num)
333 s = '%d*%d/%d' % (self.dur, self.num, self.den)
335 global reference_note
336 reference_note.duration = self
340 def compare (self, other):
341 return self.clocks - other.clocks
350 names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
351 alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
352 alteration_names = ('eses', 'es', '', 'is' , 'isis')
353 def __init__ (self, clocks, pitch, velocity):
355 self.velocity = velocity
358 self.duration = Duration (clocks)
359 (self.octave, self.notename, self.alteration) = self.o_n_a ()
363 # minor scale: la-la (= + 5) '''
365 n = self.names[(self.pitch) % 12]
366 a = self.alterations[(self.pitch) % 12]
369 a = - self.alterations[(self.pitch) % 12]
372 # By tradition, all scales now consist of a sequence
373 # of 7 notes each with a distinct name, from amongst
374 # a b c d e f g. But, minor scales have a wide
375 # second interval at the top - the 'leading note' is
376 # sharped. (Why? it just works that way! Anything
377 # else doesn't sound as good and isn't as flexible at
378 # saying things. In medieval times, scales only had 6
379 # notes to avoid this problem - the hexachords.)
381 # So, the d minor scale is d e f g a b-flat c-sharp d
382 # - using d-flat for the leading note would skip the
383 # name c and duplicate the name d. Why isn't c-sharp
384 # put in the key signature? Tradition. (It's also
385 # supposedly based on the Pythagorean theory of the
386 # cycle of fifths, but that really only applies to
387 # major scales...) Anyway, g minor is g a b-flat c d
388 # e-flat f-sharp g, and all the other flat minor keys
389 # end up with a natural leading note. And there you
392 # John Sankey <bf250@freenet.carleton.ca>
394 # Let's also do a-minor: a b c d e f gis a
398 o = self.pitch / 12 - 4
402 if key.sharps == 0 and key.flats == 0 \
403 and n == 5 and a == -1:
406 elif key.flats == 1 and n == 1 and a == -1:
409 elif key.flats == 2 and n == 4 and a == -1:
412 elif key.sharps == 5 and n == 4 and a == 0:
415 elif key.sharps == 6 and n == 1 and a == 0:
418 elif key.sharps == 7 and n == 5 and a == 0:
422 if key.flats >= 6 and n == 6 and a == 0:
423 n = 0; a = -1; o = o + 1
425 if key.flats >= 7 and n == 2 and a == 0:
429 if key.sharps >= 3 and n == 3 and a == 0:
432 if key.sharps >= 4 and n == 0 and a == 0:
433 n = 6; a = 1; o = o - 1
438 s = chr ((self.notename + 2) % 7 + ord ('a'))
439 return 'Note(%s %s)' % (s, self.duration.dump())
441 def dump (self, dump_dur = 1):
442 global reference_note
443 s = chr ((self.notename + 2) % 7 + ord ('a'))
444 s = s + self.alteration_names[self.alteration + 2]
448 delta = self.pitch - reference_note.pitch
449 commas = sign (delta) * (abs (delta) / 12)
451 * (self.notename - reference_note.notename) + 7) \
453 or ((self.notename == reference_note.notename) \
454 and (abs (delta) > 4) and (abs (delta) < 12)):
455 commas = commas + sign (delta)
460 s = s + "," * -commas
462 ## FIXME: compile fix --jcn
463 if dump_dur and (explicit_durations_p \
464 or Duration.compare (self.duration,
465 reference_note.duration)):
466 s = s + self.duration.dump ()
468 reference_note = self
475 def __init__ (self, num, den):
480 def bar_clocks (self):
481 return clocks_per_1 * self.num / self.den
484 return 'Time(%d/%d)' % (self.num, self.den)
489 return '\n ' + '\\time %d/%d ' % (self.num, self.den) + '\n '
492 def __init__ (self, seconds_per_1):
494 self.seconds_per_1 = seconds_per_1
497 return 'Tempo(%d)' % self.bpm ()
500 return 4 * 60 / self.seconds_per_1
503 return '\n ' + '\\tempo 4 = %d ' % (self.bpm()) + '\n '
506 clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
507 def __init__ (self, type):
511 return 'Clef(%s)' % self.clefs[self.type]
514 return '\n \\clef %s\n ' % self.clefs[self.type]
517 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
518 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
520 def __init__ (self, sharps, flats, minor):
531 if self.sharps and self.flats:
535 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
537 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
540 name = chr ((k + 2) % 7 + ord ('a'))
542 name = chr ((k + 2) % 7 + ord ('a'))
544 # fis cis gis dis ais eis bis
545 sharps = (2, 4, 6, 1, 3, 5, 7)
546 # bes es as des ges ces fes
547 flats = (6, 4, 2, 7, 5, 3, 1)
550 if flats[k] <= self.flats:
553 if sharps[k] <= self.sharps:
557 name = name + Note.alteration_names[a + 2]
565 return '\n\n ' + s + '\n '
573 'SEQUENCE_TRACK_NAME',
579 def __init__ (self, type, text):
585 # urg, we should be sure that we're in a lyrics staff
586 if self.type == midi.LYRIC:
587 s = '"%s"' % self.text
588 d = Duration (self.clocks)
589 if explicit_durations_p \
590 or Duration.compare (d,
591 reference_note.duration):
592 s = s + Duration (self.clocks).dump ()
595 s = '\n % [' + self.text_types[self.type] + '] ' + self.text + '\n '
599 return 'Text(%d=%s)' % (self.type, self.text)
603 def split_track (track):
610 if data[0] > 0x7f and data[0] < 0xf0:
612 e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
622 for v in chs.values ():
623 events = events_on_channel (v)
624 thread = unthread_notes (events)
626 threads.append (thread)
630 def quantise_clocks (clocks, quant):
631 q = int (clocks / quant) * quant
633 for tquant in allowed_tuplet_clocks:
634 if int (clocks / tquant) * tquant == clocks:
636 if 2 * (clocks - q) > quant:
640 def end_note (pitches, notes, t, e):
642 (lt, vel) = pitches[e]
652 if duration_quant_clocks:
653 d = quantise_clocks (d, duration_quant_clocks)
655 d = duration_quant_clocks
658 (lt, Note (d, e, vel)))
663 def events_on_channel (channel):
673 if start_quant_clocks:
674 t = quantise_clocks (t, start_quant_clocks)
677 if e[1][0] == midi.NOTE_OFF \
678 or (e[1][0] == midi.NOTE_ON and e[1][2] == 0):
679 end_note (pitches, notes, t, e[1][1])
681 elif e[1][0] == midi.NOTE_ON:
682 if not pitches.has_key (e[1][1]):
683 pitches[e[1][1]] = (t, e[1][2])
685 # all include ALL_NOTES_OFF
686 elif e[1][0] >= midi.ALL_SOUND_OFF \
687 and e[1][0] <= midi.POLY_MODE_ON:
688 for i in pitches.keys ():
689 end_note (pitches, notes, t, i)
691 elif e[1][0] == midi.META_EVENT:
692 if e[1][1] == midi.END_OF_TRACK:
693 for i in pitches.keys ():
694 end_note (pitches, notes, t, i)
697 elif e[1][1] == midi.SET_TEMPO:
698 (u0, u1, u2) = map (ord, e[1][2])
699 us_per_4 = u2 + 256 * (u1 + 256 * u0)
700 seconds_per_1 = us_per_4 * 4 / 1e6
701 events.append ((t, Tempo (seconds_per_1)))
702 elif e[1][1] == midi.TIME_SIGNATURE:
703 (num, dur, clocks4, count32) = map (ord, e[1][2])
705 events.append ((t, Time (num, den)))
706 elif e[1][1] == midi.KEY_SIGNATURE:
707 (alterations, minor) = map (ord, e[1][2])
710 if alterations < 127:
713 flats = 256 - alterations
715 k = Key (sharps, flats, minor)
716 events.append ((t, k))
718 # ugh, must set key while parsing
719 # because Note init uses key
720 # Better do Note.calc () at dump time?
724 elif e[1][1] == midi.LYRIC \
725 or (text_lyrics_p and e[1][1] == midi.TEXT_EVENT):
727 last_lyric.clocks = t - last_time
728 events.append ((last_time, last_lyric))
730 last_lyric = Text (midi.LYRIC, e[1][2])
732 elif e[1][1] >= midi.SEQUENCE_NUMBER \
733 and e[1][1] <= midi.CUE_POINT:
734 events.append ((t, Text (e[1][1], e[1][2])))
737 sys.stderr.write ("SKIP: %s\n" % `e`)
741 sys.stderr.write ("SKIP: %s\n" % `e`)
745 # last_lyric.clocks = t - last_time
747 last_lyric.clocks = clocks_per_4
748 events.append ((last_time, last_lyric))
753 if i < len (events) and notes[0][0] >= events[i][0]:
756 events.insert (i, notes[0])
760 def unthread_notes (channel):
769 if e[1].__class__ == Note \
770 and ((t == start_busy_t \
771 and e[1].clocks + t == end_busy_t) \
775 end_busy_t = t + e[1].clocks
776 elif e[1].__class__ == Time \
777 or e[1].__class__ == Key \
778 or e[1].__class__ == Text \
779 or e[1].__class__ == Tempo:
783 threads.append (thread)
798 def dump_skip (skip, clocks):
799 return skip + Duration (clocks).dump () + ' '
808 if i.__class__ == Note:
813 s = s + dump (notes[0])
814 elif len (notes) > 1:
815 global reference_note
817 s = s + notes[0].dump (dump_dur = 0)
820 s = s + i.dump (dump_dur = 0 )
823 s = s + notes[0].duration.dump() + ' '
827 def dump_bar_line (last_bar_t, t, bar_count):
829 bar_t = time.bar_clocks ()
830 if t - last_bar_t >= bar_t:
831 bar_count = bar_count + (t - last_bar_t) / bar_t
833 if t - last_bar_t == bar_t:
834 s = '|\n %% %d\n ' % bar_count
837 # urg, this will barf at meter changes
838 last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
840 return (s, last_bar_t, bar_count)
843 def dump_channel (thread, skip):
844 global key, reference_note, time
848 # urg LilyPond doesn't start at c4, but
849 # remembers from previous tracks!
850 # reference_note = Note (clocks_per_4, 4*12, 0)
851 reference_note = Note (0, 4*12, 0)
857 if last_e and last_e[0] == e[0]:
861 chs.append ((last_e[0], ch))
868 chs.append ((last_e[0], ch))
878 i = string.rfind (lines[-1], '\n') + 1
879 if len (lines[-1][i:]) > LINE_BELL:
883 lines[-1] = lines[-1] + dump_skip (skip, t-last_t)
885 errorport.write ('BUG: time skew')
887 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
889 lines[-1] = lines[-1] + s
891 lines[-1] = lines[-1] + dump_chord (ch[1])
895 if i.clocks > clocks:
900 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
902 lines[-1] = lines[-1] + s
904 return string.join (lines, '\n ') + '\n'
907 return 'track%c' % (i + ord ('A'))
909 def channel_name (i):
910 return 'channel%c' % (i + ord ('A'))
912 def dump_track (channels, n):
914 track = track_name (n)
915 clef = guess_clef (channels)
917 for i in range (len (channels)):
918 channel = channel_name (i)
919 item = thread_first_item (channels[i])
921 if item and item.__class__ == Note:
923 s = s + '%s = ' % (track + channel)
925 s = s + '\\relative c '
926 elif item and item.__class__ == Text:
928 s = s + '%s = \\lyricmode ' % (track + channel)
931 s = s + '%s = ' % (track + channel)
933 s = s + ' ' + dump_channel (channels[i][0], skip)
936 s = s + '%s = <<\n' % track
939 s = s + clef.dump () + '\n'
941 for i in range (len (channels)):
942 channel = channel_name (i)
943 item = thread_first_item (channels[i])
944 if item and item.__class__ == Text:
945 s = s + ' \\context Lyrics = %s \\%s\n' % (channel,
948 s = s + ' \\context Voice = %s \\%s\n' % (channel,
953 def thread_first_item (thread):
956 if (event[1].__class__ == Note
957 or (event[1].__class__ == Text
958 and event[1].type == midi.LYRIC)):
963 def track_first_item (track):
965 first = thread_first_item (thread)
970 def guess_clef (track):
976 if event[1].__class__ == Note:
978 p = p + event[1].pitch
979 if i and p / i <= 3*12:
981 elif i and p / i <= 5*12:
983 elif i and p / i >= 7*12:
989 def convert_midi (in_file, out_file):
990 global clocks_per_1, clocks_per_4, key
991 global start_quant, start_quant_clocks
992 global duration_quant, duration_quant_clocks
993 global allowed_tuplet_clocks
995 str = open (in_file).read ()
996 midi_dump = midi.parse (str)
998 clocks_per_1 = midi_dump[0][1]
999 clocks_per_4 = clocks_per_1 / 4
1002 start_quant_clocks = clocks_per_1 / start_quant
1005 duration_quant_clocks = clocks_per_1 / duration_quant
1007 allowed_tuplet_clocks = []
1008 for (dur, num, den) in allowed_tuplets:
1009 allowed_tuplet_clocks.append (clocks_per_1 * num / (dur * den))
1012 for t in midi_dump[1]:
1014 tracks.append (split_track (t))
1016 tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, f)
1020 s = tag + '\n\\version "2.7.18"\n\n'
1021 for i in range (len (tracks)):
1022 s = s + dump_track (tracks[i], i)
1024 s = s + '\n\\score {\n <<\n'
1028 track = track_name (i)
1029 item = track_first_item (t)
1031 if item and item.__class__ == Note:
1032 s = s + ' \\context Staff=%s \\%s\n' % (track, track)
1033 elif item and item.__class__ == Text:
1034 s = s + ' \\context Lyrics=%s \\%s\n' % (track, track)
1039 progress (_ ("%s output to `%s'...") % ('LY', o))
1044 handle = open (out_file, 'w')
1050 (sh, long) = getopt_args (option_definitions)
1052 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
1053 except getopt.error, s:
1054 errorport.write ('\n')
1055 errorport.write (_ ("error: ") + _ ("getopt says: `%s\'" % s))
1056 errorport.write ('\n')
1057 errorport.write ('\n')
1067 elif o == '--help' or o == '-h':
1069 errorport.write ('\n')
1070 errorport.write (_ ("Example:"))
1071 errorport.write (r'''
1072 midi2ly --key=-2:1 --duration-quant=32 \
1073 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
1076 elif o == '--output' or o == '-o':
1078 elif o == '--verbose' or o == '-V':
1080 elif o == '--version' or o == '-v':
1083 elif o == '--warranty' or o == '-w':
1084 status = system ('lilypond -w', ignore_error = 1)
1090 elif o == '--absolute-pitches' or o == '-a':
1092 elif o == '--duration-quant' or o == '-d':
1093 duration_quant = string.atoi (a)
1094 elif o == '--explicit-durations' or o == '-e':
1095 explicit_durations_p = 1
1096 elif o == '--key' or o == '-k':
1097 (alterations, minor) = map (string.atoi, string.split (a + ':0', ':'))[0:2]
1100 if alterations >= 0:
1101 sharps = alterations
1103 flats = - alterations
1104 key = Key (sharps, flats, minor)
1105 elif o == '--start-quant' or o == '-s':
1106 start_quant = string.atoi (a)
1107 elif o == '--allow-tuplet' or o == '-t':
1108 a = string.replace (a, '/', '*')
1109 tuplet = map (string.atoi, string.split (a, '*'))
1110 allowed_tuplets.append (tuplet)
1111 # lots of midi files use plain text for lyric events
1112 elif o == '--text-lyrics' or o == '-x':
1116 if not files or files[0] == '-':
1118 # FIXME: read from stdin when files[0] = '-'
1120 errorport.write (program_name + ":" + _ ("error: ") + _ ("no files specified on command line.") + '\n')
1126 g = strip_extension (g, '.midi')
1127 g = strip_extension (g, '.mid')
1128 g = strip_extension (g, '.MID')
1129 (outdir, outbase) = ('','')
1133 outbase = os.path.basename (g)
1134 o = os.path.join (outdir, outbase + '-midi.ly')
1135 elif output_name[-1] == os.sep:
1136 outdir = output_name
1137 outbase = os.path.basename (g)
1138 os.path.join (outdir, outbase + '-gen.ly')
1141 (outdir, outbase) = os.path.split (o)
1143 if outdir != '.' and outdir != '':
1145 os.mkdir (outdir, 0777)