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 datadir = '@local_lilypond_datadir@'
39 if os.environ.has_key ('LILYPONDPREFIX'):
40 datadir = os.environ['LILYPONDPREFIX']
41 while datadir[-1] == os.sep:
43 libdir = datadir.replace ('/share/', '/lib/')
45 if os.path.exists (os.path.join (datadir, 'lib/lilypond/@TOPLEVEL_VERSION@/')):
46 libdir = os.path.join (libdir, 'lib/lilypond/@TOPLEVEL_VERSION@/')
48 if os.path.exists (os.path.join (datadir, 'lib/lilypond/current/')):
49 libdir = os.path.join (libdir, 'lib/lilypond/current/')
51 sys.path.insert (0, os.path.join (libdir, 'python'))
53 ################################################################
58 ################################################################
59 ################ CONSTANTS
64 scale_steps = [0,2,4,5,7,9,11]
72 start_quant_clocks = 0
74 duration_quant_clocks = 0
76 allowed_tuplet_clocks = []
78 explicit_durations_p = 0
83 ################################################################
85 localedir = '@localedir@'
88 gettext.bindtextdomain ('lilypond', localedir)
89 gettext.textdomain ('lilypond')
95 program_name = sys.argv[0]
96 program_version = '@TOPLEVEL_VERSION@'
98 errorport = sys.stderr
101 # temp_dir = os.path.join (original_dir, '%s.dir' % program_name)
102 # original_dir = os.getcwd ()
103 # keep_temp_dir_p = 0
106 help_summary = _ ("Convert MIDI to LilyPond source.")
108 option_definitions = [
109 ('', 'a', 'absolute-pitches', _ ("print absolute pitches")),
110 (_ ("DUR"), 'd', 'duration-quant', _ ("quantise note durations on DUR")),
111 ('', 'e', 'explicit-durations', _ ("print explicit durations")),
112 ('', 'h', 'help', _ ("print this help")),
113 (_ ("ALT[:MINOR]"), 'k', 'key', _ ("set key: ALT=+sharps|-flats; MINOR=1")),
114 (_ ("FILE"), 'o', 'output', _ ("write output to FILE")),
115 (_ ("DUR"), 's', 'start-quant', _ ("quantise note starts on DUR")),
116 (_ ("DUR*NUM/DEN"), 't', 'allow-tuplet', _ ("allow tuplet durations DUR*NUM/DEN")),
117 ('', 'V', 'verbose', _ ("be verbose")),
118 ('', 'v', 'version', _ ("print version number")),
119 ('', 'w', 'warranty', _ ("show warranty and copyright")),
120 ('', 'x', 'text-lyrics', _ ("treat every text as a lyric")),
123 ################################################################
124 # lilylib.py -- options and stuff
126 # source file of the GNU LilyPond music typesetter
132 gettext.bindtextdomain ('lilypond', localedir)
133 gettext.textdomain ('lilypond')
139 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
140 program_version = '1.5.17'
143 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
147 sys.stdout.write ('\n')
148 sys.stdout.write (_ ('Copyright (c) %s by') % ' 2001--2006')
149 sys.stdout.write ('\n')
150 sys.stdout.write (' Han-Wen Nienhuys')
151 sys.stdout.write (' Jan Nieuwenhuizen')
152 sys.stdout.write ('\n\n')
153 sys.stdout.write (_ ("Distributed under terms of the GNU General Public License."))
154 sys.stdout.write (_ ("It comes with NO WARRANTY."))
155 sys.stdout.write ('\n')
158 errorport.write (s + '\n')
161 progress (_ ("warning: ") + s)
166 '''Report the error S. Exit by raising an exception. Please
167 do not abuse by trying to catch this error. If you do not want
168 a stack trace, write to the output directly.
176 progress (_ ("error: ") + s)
177 raise _ ("Exiting ... ")
179 def getopt_args (opts):
180 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
195 def option_help_str (o):
196 '''Transform one option description (4-tuple ) into neatly formatted string'''
214 return ' ' + sh + sep + long + arg
217 def options_help_str (opts):
218 '''Convert a list of options into a neatly formatted string'''
224 s = option_help_str (o)
225 strs.append ((s, o[3]))
231 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
235 ls = [(_ ("Usage: %s [OPTIONS]... FILE") % program_name),
241 (options_help_str (option_definitions)),
243 (_ ("Report bugs via %s.") %
244 "http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs"),
246 map (sys.stdout.write, ls)
250 Create a temporary directory, and return its name.
253 if not keep_temp_dir_p:
254 temp_dir = tempfile.mktemp (program_name)
256 os.mkdir (temp_dir, 0777)
263 def system (cmd, ignore_error = 0):
264 """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
272 progress (_ ("Invoking `%s\'") % cmd)
275 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
276 msg = name + ': ' + _ ("command exited with value %d") % st
278 warning (msg + ' ' + _ ("(ignored)") + ' ')
286 if not keep_temp_dir_p:
288 progress (_ ("Cleaning %s...") % temp_dir)
289 shutil.rmtree (temp_dir)
292 def strip_extension (f, ext):
293 (p, e) = os.path.splitext (f)
298 ################################################################
300 ################################################################
306 allowed_durs = (1, 2, 4, 8, 16, 32, 64, 128)
307 def __init__ (self, clocks):
310 self.clocks = duration_quant_clocks
311 (self.dur, self.num, self.den) = self.dur_num_den (clocks)
313 def dur_num_den (self, clocks):
314 for i in range (len (allowed_tuplet_clocks)):
315 if clocks == allowed_tuplet_clocks[i]:
316 return allowed_tuplets[i]
318 dur = 0; num = 1; den = 1;
319 g = gcd (clocks, clocks_per_1)
321 (dur, num) = (clocks_per_1 / g, clocks / g)
322 if not dur in self.allowed_durs:
323 dur = 4; num = clocks; den = clocks_per_4
324 return (dur, num, den)
330 elif self.num == 3 and self.dur != 1:
331 s = '%d.' % (self.dur / 2)
333 s = '%d*%d' % (self.dur, self.num)
335 s = '%d*%d/%d' % (self.dur, self.num, self.den)
337 global reference_note
338 reference_note.duration = self
342 def compare (self, other):
343 return self.clocks - other.clocks
352 names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
353 alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
354 alteration_names = ('eses', 'es', '', 'is' , 'isis')
355 def __init__ (self, clocks, pitch, velocity):
357 self.velocity = velocity
360 self.duration = Duration (clocks)
361 (self.octave, self.notename, self.alteration) = self.o_n_a ()
365 # minor scale: la-la (= + 5) '''
367 n = self.names[(self.pitch) % 12]
368 a = self.alterations[(self.pitch) % 12]
371 a = - self.alterations[(self.pitch) % 12]
374 # By tradition, all scales now consist of a sequence
375 # of 7 notes each with a distinct name, from amongst
376 # a b c d e f g. But, minor scales have a wide
377 # second interval at the top - the 'leading note' is
378 # sharped. (Why? it just works that way! Anything
379 # else doesn't sound as good and isn't as flexible at
380 # saying things. In medieval times, scales only had 6
381 # notes to avoid this problem - the hexachords.)
383 # So, the d minor scale is d e f g a b-flat c-sharp d
384 # - using d-flat for the leading note would skip the
385 # name c and duplicate the name d. Why isn't c-sharp
386 # put in the key signature? Tradition. (It's also
387 # supposedly based on the Pythagorean theory of the
388 # cycle of fifths, but that really only applies to
389 # major scales...) Anyway, g minor is g a b-flat c d
390 # e-flat f-sharp g, and all the other flat minor keys
391 # end up with a natural leading note. And there you
394 # John Sankey <bf250@freenet.carleton.ca>
396 # Let's also do a-minor: a b c d e f gis a
400 o = self.pitch / 12 - 4
404 if key.sharps == 0 and key.flats == 0 \
405 and n == 5 and a == -1:
408 elif key.flats == 1 and n == 1 and a == -1:
411 elif key.flats == 2 and n == 4 and a == -1:
414 elif key.sharps == 5 and n == 4 and a == 0:
417 elif key.sharps == 6 and n == 1 and a == 0:
420 elif key.sharps == 7 and n == 5 and a == 0:
424 if key.flats >= 6 and n == 6 and a == 0:
425 n = 0; a = -1; o = o + 1
427 if key.flats >= 7 and n == 2 and a == 0:
431 if key.sharps >= 3 and n == 3 and a == 0:
434 if key.sharps >= 4 and n == 0 and a == 0:
435 n = 6; a = 1; o = o - 1
440 s = chr ((self.notename + 2) % 7 + ord ('a'))
441 return 'Note(%s %s)' % (s, self.duration.dump())
443 def dump (self, dump_dur = 1):
444 global reference_note
445 s = chr ((self.notename + 2) % 7 + ord ('a'))
446 s = s + self.alteration_names[self.alteration + 2]
450 delta = self.pitch - reference_note.pitch
451 commas = sign (delta) * (abs (delta) / 12)
453 * (self.notename - reference_note.notename) + 7) \
455 or ((self.notename == reference_note.notename) \
456 and (abs (delta) > 4) and (abs (delta) < 12)):
457 commas = commas + sign (delta)
462 s = s + "," * -commas
464 ## FIXME: compile fix --jcn
465 if dump_dur and (explicit_durations_p \
466 or Duration.compare (self.duration,
467 reference_note.duration)):
468 s = s + self.duration.dump ()
470 reference_note = self
477 def __init__ (self, num, den):
482 def bar_clocks (self):
483 return clocks_per_1 * self.num / self.den
486 return 'Time(%d/%d)' % (self.num, self.den)
491 return '\n ' + '\\time %d/%d ' % (self.num, self.den) + '\n '
494 def __init__ (self, seconds_per_1):
496 self.seconds_per_1 = seconds_per_1
499 return 'Tempo(%d)' % self.bpm ()
502 return 4 * 60 / self.seconds_per_1
505 return '\n ' + '\\tempo 4 = %d ' % (self.bpm()) + '\n '
508 clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
509 def __init__ (self, type):
513 return 'Clef(%s)' % self.clefs[self.type]
516 return '\n \\clef %s\n ' % self.clefs[self.type]
519 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
520 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
522 def __init__ (self, sharps, flats, minor):
533 if self.sharps and self.flats:
537 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
539 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
542 name = chr ((k + 2) % 7 + ord ('a'))
544 name = chr ((k + 2) % 7 + ord ('a'))
546 # fis cis gis dis ais eis bis
547 sharps = (2, 4, 6, 1, 3, 5, 7)
548 # bes es as des ges ces fes
549 flats = (6, 4, 2, 7, 5, 3, 1)
552 if flats[k] <= self.flats:
555 if sharps[k] <= self.sharps:
559 name = name + Note.alteration_names[a + 2]
567 return '\n\n ' + s + '\n '
575 'SEQUENCE_TRACK_NAME',
581 def __init__ (self, type, text):
587 # urg, we should be sure that we're in a lyrics staff
588 if self.type == midi.LYRIC:
589 s = '"%s"' % self.text
590 d = Duration (self.clocks)
591 if explicit_durations_p \
592 or Duration.compare (d,
593 reference_note.duration):
594 s = s + Duration (self.clocks).dump ()
597 s = '\n % [' + self.text_types[self.type] + '] ' + self.text + '\n '
601 return 'Text(%d=%s)' % (self.type, self.text)
605 def split_track (track):
612 if data[0] > 0x7f and data[0] < 0xf0:
614 e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
624 for v in chs.values ():
625 events = events_on_channel (v)
626 thread = unthread_notes (events)
628 threads.append (thread)
632 def quantise_clocks (clocks, quant):
633 q = int (clocks / quant) * quant
635 for tquant in allowed_tuplet_clocks:
636 if int (clocks / tquant) * tquant == clocks:
638 if 2 * (clocks - q) > quant:
642 def end_note (pitches, notes, t, e):
644 (lt, vel) = pitches[e]
654 if duration_quant_clocks:
655 d = quantise_clocks (d, duration_quant_clocks)
657 d = duration_quant_clocks
660 (lt, Note (d, e, vel)))
665 def events_on_channel (channel):
675 if start_quant_clocks:
676 t = quantise_clocks (t, start_quant_clocks)
679 if e[1][0] == midi.NOTE_OFF \
680 or (e[1][0] == midi.NOTE_ON and e[1][2] == 0):
681 end_note (pitches, notes, t, e[1][1])
683 elif e[1][0] == midi.NOTE_ON:
684 if not pitches.has_key (e[1][1]):
685 pitches[e[1][1]] = (t, e[1][2])
687 # all include ALL_NOTES_OFF
688 elif e[1][0] >= midi.ALL_SOUND_OFF \
689 and e[1][0] <= midi.POLY_MODE_ON:
690 for i in pitches.keys ():
691 end_note (pitches, notes, t, i)
693 elif e[1][0] == midi.META_EVENT:
694 if e[1][1] == midi.END_OF_TRACK:
695 for i in pitches.keys ():
696 end_note (pitches, notes, t, i)
699 elif e[1][1] == midi.SET_TEMPO:
700 (u0, u1, u2) = map (ord, e[1][2])
701 us_per_4 = u2 + 256 * (u1 + 256 * u0)
702 seconds_per_1 = us_per_4 * 4 / 1e6
703 events.append ((t, Tempo (seconds_per_1)))
704 elif e[1][1] == midi.TIME_SIGNATURE:
705 (num, dur, clocks4, count32) = map (ord, e[1][2])
707 events.append ((t, Time (num, den)))
708 elif e[1][1] == midi.KEY_SIGNATURE:
709 (alterations, minor) = map (ord, e[1][2])
712 if alterations < 127:
715 flats = 256 - alterations
717 k = Key (sharps, flats, minor)
718 events.append ((t, k))
720 # ugh, must set key while parsing
721 # because Note init uses key
722 # Better do Note.calc () at dump time?
726 elif e[1][1] == midi.LYRIC \
727 or (text_lyrics_p and e[1][1] == midi.TEXT_EVENT):
729 last_lyric.clocks = t - last_time
730 events.append ((last_time, last_lyric))
732 last_lyric = Text (midi.LYRIC, e[1][2])
734 elif e[1][1] >= midi.SEQUENCE_NUMBER \
735 and e[1][1] <= midi.CUE_POINT:
736 events.append ((t, Text (e[1][1], e[1][2])))
739 sys.stderr.write ("SKIP: %s\n" % `e`)
743 sys.stderr.write ("SKIP: %s\n" % `e`)
747 # last_lyric.clocks = t - last_time
749 last_lyric.clocks = clocks_per_4
750 events.append ((last_time, last_lyric))
755 if i < len (events) and notes[0][0] >= events[i][0]:
758 events.insert (i, notes[0])
762 def unthread_notes (channel):
771 if e[1].__class__ == Note \
772 and ((t == start_busy_t \
773 and e[1].clocks + t == end_busy_t) \
777 end_busy_t = t + e[1].clocks
778 elif e[1].__class__ == Time \
779 or e[1].__class__ == Key \
780 or e[1].__class__ == Text \
781 or e[1].__class__ == Tempo:
785 threads.append (thread)
800 def dump_skip (skip, clocks):
801 return skip + Duration (clocks).dump () + ' '
810 if i.__class__ == Note:
815 s = s + dump (notes[0])
816 elif len (notes) > 1:
817 global reference_note
819 s = s + notes[0].dump (dump_dur = 0)
822 s = s + i.dump (dump_dur = 0 )
825 s = s + notes[0].duration.dump() + ' '
829 def dump_bar_line (last_bar_t, t, bar_count):
831 bar_t = time.bar_clocks ()
832 if t - last_bar_t >= bar_t:
833 bar_count = bar_count + (t - last_bar_t) / bar_t
835 if t - last_bar_t == bar_t:
836 s = '|\n %% %d\n ' % bar_count
839 # urg, this will barf at meter changes
840 last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
842 return (s, last_bar_t, bar_count)
845 def dump_channel (thread, skip):
846 global key, reference_note, time
850 # urg LilyPond doesn't start at c4, but
851 # remembers from previous tracks!
852 # reference_note = Note (clocks_per_4, 4*12, 0)
853 reference_note = Note (0, 4*12, 0)
859 if last_e and last_e[0] == e[0]:
863 chs.append ((last_e[0], ch))
870 chs.append ((last_e[0], ch))
880 i = string.rfind (lines[-1], '\n') + 1
881 if len (lines[-1][i:]) > LINE_BELL:
885 lines[-1] = lines[-1] + dump_skip (skip, t-last_t)
887 errorport.write ('BUG: time skew')
889 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
891 lines[-1] = lines[-1] + s
893 lines[-1] = lines[-1] + dump_chord (ch[1])
897 if i.clocks > clocks:
902 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
904 lines[-1] = lines[-1] + s
906 return string.join (lines, '\n ') + '\n'
909 return 'track%c' % (i + ord ('A'))
911 def channel_name (i):
912 return 'channel%c' % (i + ord ('A'))
914 def dump_track (channels, n):
916 track = track_name (n)
917 clef = guess_clef (channels)
919 for i in range (len (channels)):
920 channel = channel_name (i)
921 item = thread_first_item (channels[i])
923 if item and item.__class__ == Note:
925 s = s + '%s = ' % (track + channel)
927 s = s + '\\relative c '
928 elif item and item.__class__ == Text:
930 s = s + '%s = \\lyricmode ' % (track + channel)
933 s = s + '%s = ' % (track + channel)
935 s = s + ' ' + dump_channel (channels[i][0], skip)
938 s = s + '%s = <<\n' % track
941 s = s + clef.dump () + '\n'
943 for i in range (len (channels)):
944 channel = channel_name (i)
945 item = thread_first_item (channels[i])
946 if item and item.__class__ == Text:
947 s = s + ' \\context Lyrics = %s \\%s\n' % (channel,
950 s = s + ' \\context Voice = %s \\%s\n' % (channel,
955 def thread_first_item (thread):
958 if (event[1].__class__ == Note
959 or (event[1].__class__ == Text
960 and event[1].type == midi.LYRIC)):
965 def track_first_item (track):
967 first = thread_first_item (thread)
972 def guess_clef (track):
978 if event[1].__class__ == Note:
980 p = p + event[1].pitch
981 if i and p / i <= 3*12:
983 elif i and p / i <= 5*12:
985 elif i and p / i >= 7*12:
991 def convert_midi (in_file, out_file):
992 global clocks_per_1, clocks_per_4, key
993 global start_quant, start_quant_clocks
994 global duration_quant, duration_quant_clocks
995 global allowed_tuplet_clocks
997 str = open (in_file).read ()
998 midi_dump = midi.parse (str)
1000 clocks_per_1 = midi_dump[0][1]
1001 clocks_per_4 = clocks_per_1 / 4
1004 start_quant_clocks = clocks_per_1 / start_quant
1007 duration_quant_clocks = clocks_per_1 / duration_quant
1009 allowed_tuplet_clocks = []
1010 for (dur, num, den) in allowed_tuplets:
1011 allowed_tuplet_clocks.append (clocks_per_1 * num / (dur * den))
1014 for t in midi_dump[1]:
1016 tracks.append (split_track (t))
1018 tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, f)
1022 s = tag + '\n\\version "2.7.18"\n\n'
1023 for i in range (len (tracks)):
1024 s = s + dump_track (tracks[i], i)
1026 s = s + '\n\\score {\n <<\n'
1030 track = track_name (i)
1031 item = track_first_item (t)
1033 if item and item.__class__ == Note:
1034 s = s + ' \\context Staff=%s \\%s\n' % (track, track)
1035 elif item and item.__class__ == Text:
1036 s = s + ' \\context Lyrics=%s \\%s\n' % (track, track)
1041 progress (_ ("%s output to `%s'...") % ('LY', o))
1046 handle = open (out_file, 'w')
1052 (sh, long) = getopt_args (option_definitions)
1054 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
1055 except getopt.error, s:
1056 errorport.write ('\n')
1057 errorport.write (_ ("error: ") + _ ("getopt says: `%s\'" % s))
1058 errorport.write ('\n')
1059 errorport.write ('\n')
1069 elif o == '--help' or o == '-h':
1071 errorport.write ('\n')
1072 errorport.write (_ ("Example:"))
1073 errorport.write (r'''
1074 midi2ly --key=-2:1 --duration-quant=32 \
1075 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
1078 elif o == '--output' or o == '-o':
1080 elif o == '--verbose' or o == '-V':
1082 elif o == '--version' or o == '-v':
1085 elif o == '--warranty' or o == '-w':
1086 status = system ('lilypond -w', ignore_error = 1)
1092 elif o == '--absolute-pitches' or o == '-a':
1094 elif o == '--duration-quant' or o == '-d':
1095 duration_quant = string.atoi (a)
1096 elif o == '--explicit-durations' or o == '-e':
1097 explicit_durations_p = 1
1098 elif o == '--key' or o == '-k':
1099 (alterations, minor) = map (string.atoi, string.split (a + ':0', ':'))[0:2]
1102 if alterations >= 0:
1103 sharps = alterations
1105 flats = - alterations
1106 key = Key (sharps, flats, minor)
1107 elif o == '--start-quant' or o == '-s':
1108 start_quant = string.atoi (a)
1109 elif o == '--allow-tuplet' or o == '-t':
1110 a = string.replace (a, '/', '*')
1111 tuplet = map (string.atoi, string.split (a, '*'))
1112 allowed_tuplets.append (tuplet)
1113 # lots of midi files use plain text for lyric events
1114 elif o == '--text-lyrics' or o == '-x':
1118 if not files or files[0] == '-':
1120 # FIXME: read from stdin when files[0] = '-'
1122 errorport.write (program_name + ":" + _ ("error: ") + _ ("no files specified on command line.") + '\n')
1128 g = strip_extension (g, '.midi')
1129 g = strip_extension (g, '.mid')
1130 g = strip_extension (g, '.MID')
1131 (outdir, outbase) = ('','')
1135 outbase = os.path.basename (g)
1136 o = os.path.join (outdir, outbase + '-midi.ly')
1137 elif output_name[-1] == os.sep:
1138 outdir = output_name
1139 outbase = os.path.basename (g)
1140 os.path.join (outdir, outbase + '-gen.ly')
1143 (outdir, outbase) = os.path.split (o)
1145 if outdir != '.' and outdir != '':
1147 os.mkdir (outdir, 0777)