3 # msdi2ly.py -- LilyPond midi import script
5 # source file of the GNU LilyPond music typesetter
7 # (c) 1998--2006 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--2006')
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 via %s.") %
243 "http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs"),
245 map (sys.stdout.write, ls)
249 Create a temporary directory, and return its name.
252 if not keep_temp_dir_p:
253 temp_dir = tempfile.mktemp (program_name)
255 os.mkdir (temp_dir, 0777)
262 def system (cmd, ignore_error = 0):
263 """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
271 progress (_ ("Invoking `%s\'") % cmd)
274 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
275 msg = name + ': ' + _ ("command exited with value %d") % st
277 warning (msg + ' ' + _ ("(ignored)") + ' ')
285 if not keep_temp_dir_p:
287 progress (_ ("Cleaning %s...") % temp_dir)
288 shutil.rmtree (temp_dir)
291 def strip_extension (f, ext):
292 (p, e) = os.path.splitext (f)
297 ################################################################
299 ################################################################
305 allowed_durs = (1, 2, 4, 8, 16, 32, 64, 128)
306 def __init__ (self, clocks):
309 self.clocks = duration_quant_clocks
310 (self.dur, self.num, self.den) = self.dur_num_den (clocks)
312 def dur_num_den (self, clocks):
313 for i in range (len (allowed_tuplet_clocks)):
314 if clocks == allowed_tuplet_clocks[i]:
315 return allowed_tuplets[i]
317 dur = 0; num = 1; den = 1;
318 g = gcd (clocks, clocks_per_1)
320 (dur, num) = (clocks_per_1 / g, clocks / g)
321 if not dur in self.allowed_durs:
322 dur = 4; num = clocks; den = clocks_per_4
323 return (dur, num, den)
329 elif self.num == 3 and self.dur != 1:
330 s = '%d.' % (self.dur / 2)
332 s = '%d*%d' % (self.dur, self.num)
334 s = '%d*%d/%d' % (self.dur, self.num, self.den)
336 global reference_note
337 reference_note.duration = self
341 def compare (self, other):
342 return self.clocks - other.clocks
351 names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
352 alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
353 alteration_names = ('eses', 'es', '', 'is' , 'isis')
354 def __init__ (self, clocks, pitch, velocity):
356 self.velocity = velocity
359 self.duration = Duration (clocks)
360 (self.octave, self.notename, self.alteration) = self.o_n_a ()
364 # minor scale: la-la (= + 5) '''
366 n = self.names[(self.pitch) % 12]
367 a = self.alterations[(self.pitch) % 12]
370 a = - self.alterations[(self.pitch) % 12]
373 # By tradition, all scales now consist of a sequence
374 # of 7 notes each with a distinct name, from amongst
375 # a b c d e f g. But, minor scales have a wide
376 # second interval at the top - the 'leading note' is
377 # sharped. (Why? it just works that way! Anything
378 # else doesn't sound as good and isn't as flexible at
379 # saying things. In medieval times, scales only had 6
380 # notes to avoid this problem - the hexachords.)
382 # So, the d minor scale is d e f g a b-flat c-sharp d
383 # - using d-flat for the leading note would skip the
384 # name c and duplicate the name d. Why isn't c-sharp
385 # put in the key signature? Tradition. (It's also
386 # supposedly based on the Pythagorean theory of the
387 # cycle of fifths, but that really only applies to
388 # major scales...) Anyway, g minor is g a b-flat c d
389 # e-flat f-sharp g, and all the other flat minor keys
390 # end up with a natural leading note. And there you
393 # John Sankey <bf250@freenet.carleton.ca>
395 # Let's also do a-minor: a b c d e f gis a
399 o = self.pitch / 12 - 4
403 if key.sharps == 0 and key.flats == 0 \
404 and n == 5 and a == -1:
407 elif key.flats == 1 and n == 1 and a == -1:
410 elif key.flats == 2 and n == 4 and a == -1:
413 elif key.sharps == 5 and n == 4 and a == 0:
416 elif key.sharps == 6 and n == 1 and a == 0:
419 elif key.sharps == 7 and n == 5 and a == 0:
423 if key.flats >= 6 and n == 6 and a == 0:
424 n = 0; a = -1; o = o + 1
426 if key.flats >= 7 and n == 2 and a == 0:
430 if key.sharps >= 3 and n == 3 and a == 0:
433 if key.sharps >= 4 and n == 0 and a == 0:
434 n = 6; a = 1; o = o - 1
439 s = chr ((self.notename + 2) % 7 + ord ('a'))
440 return 'Note(%s %s)' % (s, self.duration.dump())
442 def dump (self, dump_dur = 1):
443 global reference_note
444 s = chr ((self.notename + 2) % 7 + ord ('a'))
445 s = s + self.alteration_names[self.alteration + 2]
449 delta = self.pitch - reference_note.pitch
450 commas = sign (delta) * (abs (delta) / 12)
452 * (self.notename - reference_note.notename) + 7) \
454 or ((self.notename == reference_note.notename) \
455 and (abs (delta) > 4) and (abs (delta) < 12)):
456 commas = commas + sign (delta)
461 s = s + "," * -commas
463 ## FIXME: compile fix --jcn
464 if dump_dur and (explicit_durations_p \
465 or Duration.compare (self.duration,
466 reference_note.duration)):
467 s = s + self.duration.dump ()
469 reference_note = self
476 def __init__ (self, num, den):
481 def bar_clocks (self):
482 return clocks_per_1 * self.num / self.den
485 return 'Time(%d/%d)' % (self.num, self.den)
490 return '\n ' + '\\time %d/%d ' % (self.num, self.den) + '\n '
493 def __init__ (self, seconds_per_1):
495 self.seconds_per_1 = seconds_per_1
498 return 'Tempo(%d)' % self.bpm ()
501 return 4 * 60 / self.seconds_per_1
504 return '\n ' + '\\tempo 4 = %d ' % (self.bpm()) + '\n '
507 clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
508 def __init__ (self, type):
512 return 'Clef(%s)' % self.clefs[self.type]
515 return '\n \\clef %s\n ' % self.clefs[self.type]
518 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
519 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
521 def __init__ (self, sharps, flats, minor):
532 if self.sharps and self.flats:
536 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
538 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
541 name = chr ((k + 2) % 7 + ord ('a'))
543 name = chr ((k + 2) % 7 + ord ('a'))
545 # fis cis gis dis ais eis bis
546 sharps = (2, 4, 6, 1, 3, 5, 7)
547 # bes es as des ges ces fes
548 flats = (6, 4, 2, 7, 5, 3, 1)
551 if flats[k] <= self.flats:
554 if sharps[k] <= self.sharps:
558 name = name + Note.alteration_names[a + 2]
566 return '\n\n ' + s + '\n '
574 'SEQUENCE_TRACK_NAME',
580 def __init__ (self, type, text):
586 # urg, we should be sure that we're in a lyrics staff
587 if self.type == midi.LYRIC:
588 s = '"%s"' % self.text
589 d = Duration (self.clocks)
590 if explicit_durations_p \
591 or Duration.compare (d,
592 reference_note.duration):
593 s = s + Duration (self.clocks).dump ()
596 s = '\n % [' + self.text_types[self.type] + '] ' + self.text + '\n '
600 return 'Text(%d=%s)' % (self.type, self.text)
604 def split_track (track):
611 if data[0] > 0x7f and data[0] < 0xf0:
613 e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
623 for v in chs.values ():
624 events = events_on_channel (v)
625 thread = unthread_notes (events)
627 threads.append (thread)
631 def quantise_clocks (clocks, quant):
632 q = int (clocks / quant) * quant
634 for tquant in allowed_tuplet_clocks:
635 if int (clocks / tquant) * tquant == clocks:
637 if 2 * (clocks - q) > quant:
641 def end_note (pitches, notes, t, e):
643 (lt, vel) = pitches[e]
653 if duration_quant_clocks:
654 d = quantise_clocks (d, duration_quant_clocks)
656 d = duration_quant_clocks
659 (lt, Note (d, e, vel)))
664 def events_on_channel (channel):
674 if start_quant_clocks:
675 t = quantise_clocks (t, start_quant_clocks)
678 if e[1][0] == midi.NOTE_OFF \
679 or (e[1][0] == midi.NOTE_ON and e[1][2] == 0):
680 end_note (pitches, notes, t, e[1][1])
682 elif e[1][0] == midi.NOTE_ON:
683 if not pitches.has_key (e[1][1]):
684 pitches[e[1][1]] = (t, e[1][2])
686 # all include ALL_NOTES_OFF
687 elif e[1][0] >= midi.ALL_SOUND_OFF \
688 and e[1][0] <= midi.POLY_MODE_ON:
689 for i in pitches.keys ():
690 end_note (pitches, notes, t, i)
692 elif e[1][0] == midi.META_EVENT:
693 if e[1][1] == midi.END_OF_TRACK:
694 for i in pitches.keys ():
695 end_note (pitches, notes, t, i)
698 elif e[1][1] == midi.SET_TEMPO:
699 (u0, u1, u2) = map (ord, e[1][2])
700 us_per_4 = u2 + 256 * (u1 + 256 * u0)
701 seconds_per_1 = us_per_4 * 4 / 1e6
702 events.append ((t, Tempo (seconds_per_1)))
703 elif e[1][1] == midi.TIME_SIGNATURE:
704 (num, dur, clocks4, count32) = map (ord, e[1][2])
706 events.append ((t, Time (num, den)))
707 elif e[1][1] == midi.KEY_SIGNATURE:
708 (alterations, minor) = map (ord, e[1][2])
711 if alterations < 127:
714 flats = 256 - alterations
716 k = Key (sharps, flats, minor)
717 events.append ((t, k))
719 # ugh, must set key while parsing
720 # because Note init uses key
721 # Better do Note.calc () at dump time?
725 elif e[1][1] == midi.LYRIC \
726 or (text_lyrics_p and e[1][1] == midi.TEXT_EVENT):
728 last_lyric.clocks = t - last_time
729 events.append ((last_time, last_lyric))
731 last_lyric = Text (midi.LYRIC, e[1][2])
733 elif e[1][1] >= midi.SEQUENCE_NUMBER \
734 and e[1][1] <= midi.CUE_POINT:
735 events.append ((t, Text (e[1][1], e[1][2])))
738 sys.stderr.write ("SKIP: %s\n" % `e`)
742 sys.stderr.write ("SKIP: %s\n" % `e`)
746 # last_lyric.clocks = t - last_time
748 last_lyric.clocks = clocks_per_4
749 events.append ((last_time, last_lyric))
754 if i < len (events) and notes[0][0] >= events[i][0]:
757 events.insert (i, notes[0])
761 def unthread_notes (channel):
770 if e[1].__class__ == Note \
771 and ((t == start_busy_t \
772 and e[1].clocks + t == end_busy_t) \
776 end_busy_t = t + e[1].clocks
777 elif e[1].__class__ == Time \
778 or e[1].__class__ == Key \
779 or e[1].__class__ == Text \
780 or e[1].__class__ == Tempo:
784 threads.append (thread)
799 def dump_skip (skip, clocks):
800 return skip + Duration (clocks).dump () + ' '
809 if i.__class__ == Note:
814 s = s + dump (notes[0])
815 elif len (notes) > 1:
816 global reference_note
818 s = s + notes[0].dump (dump_dur = 0)
821 s = s + i.dump (dump_dur = 0 )
824 s = s + notes[0].duration.dump() + ' '
828 def dump_bar_line (last_bar_t, t, bar_count):
830 bar_t = time.bar_clocks ()
831 if t - last_bar_t >= bar_t:
832 bar_count = bar_count + (t - last_bar_t) / bar_t
834 if t - last_bar_t == bar_t:
835 s = '|\n %% %d\n ' % bar_count
838 # urg, this will barf at meter changes
839 last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
841 return (s, last_bar_t, bar_count)
844 def dump_channel (thread, skip):
845 global key, reference_note, time
849 # urg LilyPond doesn't start at c4, but
850 # remembers from previous tracks!
851 # reference_note = Note (clocks_per_4, 4*12, 0)
852 reference_note = Note (0, 4*12, 0)
858 if last_e and last_e[0] == e[0]:
862 chs.append ((last_e[0], ch))
869 chs.append ((last_e[0], ch))
879 i = string.rfind (lines[-1], '\n') + 1
880 if len (lines[-1][i:]) > LINE_BELL:
884 lines[-1] = lines[-1] + dump_skip (skip, t-last_t)
886 errorport.write ('BUG: time skew')
888 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
890 lines[-1] = lines[-1] + s
892 lines[-1] = lines[-1] + dump_chord (ch[1])
896 if i.clocks > clocks:
901 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
903 lines[-1] = lines[-1] + s
905 return string.join (lines, '\n ') + '\n'
908 return 'track%c' % (i + ord ('A'))
910 def channel_name (i):
911 return 'channel%c' % (i + ord ('A'))
913 def dump_track (channels, n):
915 track = track_name (n)
916 clef = guess_clef (channels)
918 for i in range (len (channels)):
919 channel = channel_name (i)
920 item = thread_first_item (channels[i])
922 if item and item.__class__ == Note:
924 s = s + '%s = ' % (track + channel)
926 s = s + '\\relative c '
927 elif item and item.__class__ == Text:
929 s = s + '%s = \\lyricmode ' % (track + channel)
932 s = s + '%s = ' % (track + channel)
934 s = s + ' ' + dump_channel (channels[i][0], skip)
937 s = s + '%s = <<\n' % track
940 s = s + clef.dump () + '\n'
942 for i in range (len (channels)):
943 channel = channel_name (i)
944 item = thread_first_item (channels[i])
945 if item and item.__class__ == Text:
946 s = s + ' \\context Lyrics = %s \\%s\n' % (channel,
949 s = s + ' \\context Voice = %s \\%s\n' % (channel,
954 def thread_first_item (thread):
957 if (event[1].__class__ == Note
958 or (event[1].__class__ == Text
959 and event[1].type == midi.LYRIC)):
964 def track_first_item (track):
966 first = thread_first_item (thread)
971 def guess_clef (track):
977 if event[1].__class__ == Note:
979 p = p + event[1].pitch
980 if i and p / i <= 3*12:
982 elif i and p / i <= 5*12:
984 elif i and p / i >= 7*12:
990 def convert_midi (in_file, out_file):
991 global clocks_per_1, clocks_per_4, key
992 global start_quant, start_quant_clocks
993 global duration_quant, duration_quant_clocks
994 global allowed_tuplet_clocks
996 str = open (in_file).read ()
997 midi_dump = midi.parse (str)
999 clocks_per_1 = midi_dump[0][1]
1000 clocks_per_4 = clocks_per_1 / 4
1003 start_quant_clocks = clocks_per_1 / start_quant
1006 duration_quant_clocks = clocks_per_1 / duration_quant
1008 allowed_tuplet_clocks = []
1009 for (dur, num, den) in allowed_tuplets:
1010 allowed_tuplet_clocks.append (clocks_per_1 * num / (dur * den))
1013 for t in midi_dump[1]:
1015 tracks.append (split_track (t))
1017 tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, f)
1021 s = tag + '\n\\version "2.7.18"\n\n'
1022 for i in range (len (tracks)):
1023 s = s + dump_track (tracks[i], i)
1025 s = s + '\n\\score {\n <<\n'
1029 track = track_name (i)
1030 item = track_first_item (t)
1032 if item and item.__class__ == Note:
1033 s = s + ' \\context Staff=%s \\%s\n' % (track, track)
1034 elif item and item.__class__ == Text:
1035 s = s + ' \\context Lyrics=%s \\%s\n' % (track, track)
1040 progress (_ ("%s output to `%s'...") % ('LY', o))
1045 handle = open (out_file, 'w')
1051 (sh, long) = getopt_args (option_definitions)
1053 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
1054 except getopt.error, s:
1055 errorport.write ('\n')
1056 errorport.write (_ ("error: ") + _ ("getopt says: `%s\'" % s))
1057 errorport.write ('\n')
1058 errorport.write ('\n')
1068 elif o == '--help' or o == '-h':
1070 errorport.write ('\n')
1071 errorport.write (_ ("Example:"))
1072 errorport.write (r'''
1073 midi2ly --key=-2:1 --duration-quant=32 \
1074 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
1077 elif o == '--output' or o == '-o':
1079 elif o == '--verbose' or o == '-V':
1081 elif o == '--version' or o == '-v':
1084 elif o == '--warranty' or o == '-w':
1085 status = system ('lilypond -w', ignore_error = 1)
1091 elif o == '--absolute-pitches' or o == '-a':
1093 elif o == '--duration-quant' or o == '-d':
1094 duration_quant = string.atoi (a)
1095 elif o == '--explicit-durations' or o == '-e':
1096 explicit_durations_p = 1
1097 elif o == '--key' or o == '-k':
1098 (alterations, minor) = map (string.atoi, string.split (a + ':0', ':'))[0:2]
1101 if alterations >= 0:
1102 sharps = alterations
1104 flats = - alterations
1105 key = Key (sharps, flats, minor)
1106 elif o == '--start-quant' or o == '-s':
1107 start_quant = string.atoi (a)
1108 elif o == '--allow-tuplet' or o == '-t':
1109 a = string.replace (a, '/', '*')
1110 tuplet = map (string.atoi, string.split (a, '*'))
1111 allowed_tuplets.append (tuplet)
1112 # lots of midi files use plain text for lyric events
1113 elif o == '--text-lyrics' or o == '-x':
1117 if not files or files[0] == '-':
1119 # FIXME: read from stdin when files[0] = '-'
1121 errorport.write (program_name + ":" + _ ("error: ") + _ ("no files specified on command line.") + '\n')
1127 g = strip_extension (g, '.midi')
1128 g = strip_extension (g, '.mid')
1129 g = strip_extension (g, '.MID')
1130 (outdir, outbase) = ('','')
1134 outbase = os.path.basename (g)
1135 o = os.path.join (outdir, outbase + '-midi.ly')
1136 elif output_name[-1] == os.sep:
1137 outdir = output_name
1138 outbase = os.path.basename (g)
1139 os.path.join (outdir, outbase + '-gen.ly')
1142 (outdir, outbase) = os.path.split (o)
1144 if outdir != '.' and outdir != '':
1146 os.mkdir (outdir, 0777)