3 # midi2ly.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)
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
31 ################################################################
32 # Users of python modules should include this snippet.
34 # This soon to be removed for: import lilypond.lilylib as ly
35 libdir = '@local_lilypond_libdir@'
36 if not os.path.isdir (libdir):
37 libdir = '@lilypond_libdir@'
38 sys.path.insert (0, os.path.join (libdir, 'python'))
41 ################################################################
46 ################################################################
47 ################ CONSTANTS
52 scale_steps = [0,2,4,5,7,9,11]
60 start_quant_clocks = 0
62 duration_quant_clocks = 0
64 allowed_tuplet_clocks = []
66 explicit_durations_p = 0
71 ################################################################
73 localedir = '@localedir@'
76 gettext.bindtextdomain ('lilypond', localedir)
77 gettext.textdomain ('lilypond')
83 program_name = sys.argv[0]
84 program_version = '@TOPLEVEL_VERSION@'
86 errorport = sys.stderr
89 # temp_dir = os.path.join (original_dir, '%s.dir' % program_name)
90 # original_dir = os.getcwd ()
94 help_summary = _ ("Convert MIDI to LilyPond source.")
96 option_definitions = [
97 ('', 'a', 'absolute-pitches', _ ("print absolute pitches")),
98 (_ ("DUR"), 'd', 'duration-quant', _ ("quantise note durations on DUR")),
99 ('', 'e', 'explicit-durations', _ ("print explicit durations")),
100 ('', 'h', 'help', _ ("print this help")),
101 (_ ("ALT[:MINOR]"), 'k', 'key', _ ("set key: ALT=+sharps|-flats; MINOR=1")),
102 (_ ("FILE"), 'o', 'output', _ ("write output to FILE")),
103 (_ ("DUR"), 's', 'start-quant', _ ("quantise note starts on DUR")),
104 (_ ("DUR*NUM/DEN"), 't', 'allow-tuplet', _ ("allow tuplet durations DUR*NUM/DEN")),
105 ('', 'V', 'verbose', _ ("be verbose")),
106 ('', 'v', 'version', _ ("print version number")),
107 ('', 'w', 'warranty', _ ("show warranty and copyright")),
108 ('', 'x', 'text-lyrics', _ ("treat every text as a lyric")),
111 ################################################################
112 # lilylib.py -- options and stuff
114 # source file of the GNU LilyPond music typesetter
120 gettext.bindtextdomain ('lilypond', localedir)
121 gettext.textdomain ('lilypond')
127 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
128 program_version = '1.5.17'
131 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
135 sys.stdout.write ('\n')
136 sys.stdout.write (_ ('Copyright (c) %s by') % ' 2001--2005')
137 sys.stdout.write ('\n')
138 sys.stdout.write (' Han-Wen Nienhuys')
139 sys.stdout.write (' Jan Nieuwenhuizen')
140 sys.stdout.write ('\n\n')
141 sys.stdout.write (_ ("Distributed under terms of the GNU General Public License."))
142 sys.stdout.write (_ ("It comes with NO WARRANTY."))
143 sys.stdout.write ('\n')
146 errorport.write (s + '\n')
149 progress (_ ("warning: ") + s)
154 '''Report the error S. Exit by raising an exception. Please
155 do not abuse by trying to catch this error. If you do not want
156 a stack trace, write to the output directly.
164 progress (_ ("error: ") + s)
165 raise _ ("Exiting ... ")
167 def getopt_args (opts):
168 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
183 def option_help_str (o):
184 '''Transform one option description (4-tuple ) into neatly formatted string'''
202 return ' ' + sh + sep + long + arg
205 def options_help_str (opts):
206 '''Convert a list of options into a neatly formatted string'''
212 s = option_help_str (o)
213 strs.append ((s, o[3]))
219 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
223 ls = [(_ ("Usage: %s [OPTIONS]... FILE") % program_name),
229 (options_help_str (option_definitions)),
231 (_ ("Report bugs to %s.") % 'bug-lilypond@gnu.org'),
233 map (sys.stdout.write, ls)
237 Create a temporary directory, and return its name.
240 if not keep_temp_dir_p:
241 temp_dir = tempfile.mktemp (program_name)
243 os.mkdir (temp_dir, 0777)
250 def system (cmd, ignore_error = 0):
251 """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
259 progress (_ ("Invoking `%s\'") % cmd)
262 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
263 msg = name + ': ' + _ ("command exited with value %d") % st
265 warning (msg + ' ' + _ ("(ignored)") + ' ')
273 if not keep_temp_dir_p:
275 progress (_ ("Cleaning %s...") % temp_dir)
276 shutil.rmtree (temp_dir)
279 def strip_extension (f, ext):
280 (p, e) = os.path.splitext (f)
285 ################################################################
287 ################################################################
293 allowed_durs = (1, 2, 4, 8, 16, 32, 64, 128)
294 def __init__ (self, clocks):
297 self.clocks = duration_quant_clocks
298 (self.dur, self.num, self.den) = self.dur_num_den (clocks)
300 def dur_num_den (self, clocks):
301 for i in range (len (allowed_tuplet_clocks)):
302 if clocks == allowed_tuplet_clocks[i]:
303 return allowed_tuplets[i]
305 dur = 0; num = 1; den = 1;
306 g = gcd (clocks, clocks_per_1)
308 (dur, num) = (clocks_per_1 / g, clocks / g)
309 if not dur in self.allowed_durs:
310 dur = 4; num = clocks; den = clocks_per_4
311 return (dur, num, den)
317 elif self.num == 3 and self.dur != 1:
318 s = '%d.' % (self.dur / 2)
320 s = '%d*%d' % (self.dur, self.num)
322 s = '%d*%d/%d' % (self.dur, self.num, self.den)
324 global reference_note
325 reference_note.duration = self
329 def compare (self, other):
330 return self.clocks - other.clocks
339 names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
340 alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
341 alteration_names = ('eses', 'es', '', 'is' , 'isis')
343 def __init__ (self, clocks, pitch, velocity):
345 self.velocity = velocity
348 self.duration = Duration (clocks)
349 (self.octave, self.notename, self.alteration) = self.o_n_a ()
353 # minor scale: la-la (= + 5) '''
355 n = self.names[(self.pitch) % 12]
356 a = self.alterations[(self.pitch) % 12]
359 a = - self.alterations[(self.pitch) % 12]
362 # By tradition, all scales now consist of a sequence
363 # of 7 notes each with a distinct name, from amongst
364 # a b c d e f g. But, minor scales have a wide
365 # second interval at the top - the 'leading note' is
366 # sharped. (Why? it just works that way! Anything
367 # else doesn't sound as good and isn't as flexible at
368 # saying things. In medieval times, scales only had 6
369 # notes to avoid this problem - the hexachords.)
371 # So, the d minor scale is d e f g a b-flat c-sharp d
372 # - using d-flat for the leading note would skip the
373 # name c and duplicate the name d. Why isn't c-sharp
374 # put in the key signature? Tradition. (It's also
375 # supposedly based on the Pythagorean theory of the
376 # cycle of fifths, but that really only applies to
377 # major scales...) Anyway, g minor is g a b-flat c d
378 # e-flat f-sharp g, and all the other flat minor keys
379 # end up with a natural leading note. And there you
382 # John Sankey <bf250@freenet.carleton.ca>
384 # Let's also do a-minor: a b c d e f gis a
388 o = self.pitch / 12 - 4
392 if key.sharps == 0 and key.flats == 0 \
393 and n == 5 and a == -1:
396 elif key.flats == 1 and n == 1 and a == -1:
399 elif key.flats == 2 and n == 4 and a == -1:
402 elif key.sharps == 5 and n == 4 and a == 0:
405 elif key.sharps == 6 and n == 1 and a == 0:
408 elif key.sharps == 7 and n == 5 and a == 0:
412 if key.flats >= 6 and n == 6 and a == 0:
413 n = 0; a = -1; o = o + 1
415 if key.flats >= 7 and n == 2 and a == 0:
419 if key.sharps >= 3 and n == 3 and a == 0:
422 if key.sharps >= 4 and n == 0 and a == 0:
423 n = 6; a = 1; o = o - 1
427 def dump (self, dump_dur = 1):
428 global reference_note
429 s = chr ((self.notename + 2) % 7 + ord ('a'))
430 s = s + self.alteration_names[self.alteration + 2]
434 delta = self.pitch - reference_note.pitch
435 commas = sign (delta) * (abs (delta) / 12)
437 * (self.notename - reference_note.notename) + 7) \
439 or ((self.notename == reference_note.notename) \
440 and (abs (delta) > 4) and (abs (delta) < 12)):
441 commas = commas + sign (delta)
446 s = s + "," * -commas
448 ## FIXME: compile fix --jcn
449 if dump_dur and (explicit_durations_p \
450 or Duration.compare (self.duration,
451 reference_note.duration)):
452 s = s + self.duration.dump ()
454 reference_note = self
461 def __init__ (self, num, den):
466 def bar_clocks (self):
467 return clocks_per_1 * self.num / self.den
472 return '\n ' + '\\time %d/%d ' % (self.num, self.den) + '\n '
475 def __init__ (self, seconds_per_1):
477 self.seconds_per_1 = seconds_per_1
480 return '\n ' + '\\tempo 4 = %d ' % (4 * 60 / self.seconds_per_1) + '\n '
483 clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
484 def __init__ (self, type):
488 return '\n \\clef %s\n ' % self.clefs[self.type]
491 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
492 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
494 def __init__ (self, sharps, flats, minor):
505 if self.sharps and self.flats:
509 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
511 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
514 name = chr ((k + 2) % 7 + ord ('a'))
516 name = chr ((k + 2) % 7 + ord ('a'))
518 # fis cis gis dis ais eis bis
519 sharps = (2, 4, 6, 1, 3, 5, 7)
520 # bes es as des ges ces fes
521 flats = (6, 4, 2, 7, 5, 3, 1)
524 if flats[k] <= self.flats:
527 if sharps[k] <= self.sharps:
531 name = name + Note.alteration_names[a + 2]
539 return '\n\n ' + s + '\n '
547 'SEQUENCE_TRACK_NAME',
553 def __init__ (self, type, text):
559 # urg, we should be sure that we're in a lyrics staff
560 if self.type == midi.LYRIC:
561 s = '"%s"' % self.text
562 d = Duration (self.clocks)
563 if explicit_durations_p \
564 or Duration.compare (d,
565 reference_note.duration):
566 s = s + Duration (self.clocks).dump ()
569 s = '\n % [' + self.text_types[self.type] + '] ' + self.text + '\n '
573 def split_track (track):
580 if data[0] > 0x7f and data[0] < 0xf0:
582 e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
592 for v in chs.values ():
593 events = events_on_channel (v)
594 thread = unthread_notes (events)
596 threads.append (thread)
600 def quantise_clocks (clocks, quant):
601 q = int (clocks / quant) * quant
603 for tquant in allowed_tuplet_clocks:
604 if int (clocks / tquant) * tquant == clocks:
606 if 2 * (clocks - q) > quant:
610 def end_note (pitches, notes, t, e):
612 (lt, vel) = pitches[e]
622 if duration_quant_clocks:
623 d = quantise_clocks (d, duration_quant_clocks)
625 d = duration_quant_clocks
628 (lt, Note (d, e, vel)))
633 def events_on_channel (channel):
643 if start_quant_clocks:
644 t = quantise_clocks (t, start_quant_clocks)
647 if e[1][0] == midi.NOTE_OFF \
648 or (e[1][0] == midi.NOTE_ON and e[1][2] == 0):
649 end_note (pitches, notes, t, e[1][1])
651 elif e[1][0] == midi.NOTE_ON:
652 if not pitches.has_key (e[1][1]):
653 pitches[e[1][1]] = (t, e[1][2])
655 # all include ALL_NOTES_OFF
656 elif e[1][0] >= midi.ALL_SOUND_OFF \
657 and e[1][0] <= midi.POLY_MODE_ON:
658 for i in pitches.keys ():
659 end_note (pitches, notes, t, i)
661 elif e[1][0] == midi.META_EVENT:
662 if e[1][1] == midi.END_OF_TRACK:
663 for i in pitches.keys ():
664 end_note (pitches, notes, t, i)
667 elif e[1][1] == midi.SET_TEMPO:
668 (u0, u1, u2) = map (ord, e[1][2])
669 us_per_4 = u2 + 256 * (u1 + 256 * u0)
670 seconds_per_1 = us_per_4 * 4 / 1e6
671 events.append ((t, Tempo (seconds_per_1)))
672 elif e[1][1] == midi.TIME_SIGNATURE:
673 (num, dur, clocks4, count32) = map (ord, e[1][2])
675 events.append ((t, Time (num, den)))
676 elif e[1][1] == midi.KEY_SIGNATURE:
677 (alterations, minor) = map (ord, e[1][2])
680 if alterations < 127:
683 flats = 256 - alterations
685 k = Key (sharps, flats, minor)
686 events.append ((t, k))
688 # ugh, must set key while parsing
689 # because Note init uses key
690 # Better do Note.calc () at dump time?
694 elif e[1][1] == midi.LYRIC \
695 or (text_lyrics_p and e[1][1] == midi.TEXT_EVENT):
697 last_lyric.clocks = t - last_time
698 events.append ((last_time, last_lyric))
700 last_lyric = Text (midi.LYRIC, e[1][2])
702 elif e[1][1] >= midi.SEQUENCE_NUMBER \
703 and e[1][1] <= midi.CUE_POINT:
704 events.append ((t, Text (e[1][1], e[1][2])))
707 sys.stderr.write ("SKIP: %s\n" % `e`)
711 sys.stderr.write ("SKIP: %s\n" % `e`)
715 # last_lyric.clocks = t - last_time
717 last_lyric.clocks = clocks_per_4
718 events.append ((last_time, last_lyric))
723 if i < len (events) and notes[0][0] >= events[i][0]:
726 events.insert (i, notes[0])
730 def unthread_notes (channel):
739 if e[1].__class__ == Note \
740 and ((t == start_busy_t \
741 and e[1].clocks + t == end_busy_t) \
745 end_busy_t = t + e[1].clocks
746 elif e[1].__class__ == Time \
747 or e[1].__class__ == Key \
748 or e[1].__class__ == Text \
749 or e[1].__class__ == Tempo:
753 threads.append (thread)
768 def dump_skip (skip, clocks):
769 return skip + Duration (clocks).dump () + ' '
778 if i.__class__ == Note:
783 s = s + dump (notes[0])
784 elif len (notes) > 1:
785 global reference_note
787 s = s + notes[0].dump (dump_dur = 0)
790 s = s + i.dump (dump_dur = 0 )
793 s = s + notes[0].duration.dump() + ' '
797 def dump_bar_line (last_bar_t, t, bar_count):
799 bar_t = time.bar_clocks ()
800 if t - last_bar_t >= bar_t:
801 bar_count = bar_count + (t - last_bar_t) / bar_t
803 if t - last_bar_t == bar_t:
804 s = '|\n %% %d\n ' % bar_count
807 # urg, this will barf at meter changes
808 last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
810 return (s, last_bar_t, bar_count)
813 def dump_channel (thread, skip):
814 global key, reference_note, time
818 # urg LilyPond doesn't start at c4, but
819 # remembers from previous tracks!
820 # reference_note = Note (clocks_per_4, 4*12, 0)
821 reference_note = Note (0, 4*12, 0)
827 if last_e and last_e[0] == e[0]:
831 chs.append ((last_e[0], ch))
838 chs.append ((last_e[0], ch))
848 i = string.rfind (lines[-1], '\n') + 1
849 if len (lines[-1][i:]) > LINE_BELL:
853 lines[-1] = lines[-1] + dump_skip (skip, t-last_t)
855 errorport.write ('BUG: time skew')
857 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
859 lines[-1] = lines[-1] + s
861 lines[-1] = lines[-1] + dump_chord (ch[1])
865 if i.clocks > clocks:
870 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
872 lines[-1] = lines[-1] + s
874 return string.join (lines, '\n ') + '\n'
877 return 'track%c' % (i + ord ('A'))
879 def channel_name (i):
880 return 'channel%c' % (i + ord ('A'))
882 def dump_track (channels, n):
884 track = track_name (n)
885 clef = guess_clef (channels)
887 for i in range (len (channels)):
888 channel = channel_name (i)
889 item = thread_first_item (channels[i])
891 if item and item.__class__ == Note:
893 s = s + '%s = ' % (track + channel)
895 s = s + '\\relative c '
896 elif item and item.__class__ == Text:
898 s = s + '%s = \\lyricmode ' % (track + channel)
901 s = s + '%s = ' % (track + channel)
903 s = s + ' ' + dump_channel (channels[i][0], skip)
906 s = s + '%s = <<\n' % track
909 s = s + clef.dump () + '\n'
911 for i in range (len (channels)):
912 channel = channel_name (i)
913 item = thread_first_item (channels[i])
914 if item and item.__class__ == Text:
915 s = s + ' \\context Lyrics = %s \\%s\n' % (channel,
918 s = s + ' \\context Voice = %s \\%s\n' % (channel,
923 def thread_first_item (thread):
926 if event[1].__class__ == Note \
927 or (event[1].__class__ == Text \
928 and event[1].type == midi.LYRIC):
932 def track_first_item (track):
934 return thread_first_item (thread)
936 def guess_clef (track):
942 if event[1].__class__ == Note:
944 p = p + event[1].pitch
945 if i and p / i <= 3*12:
947 elif i and p / i <= 5*12:
949 elif i and p / i >= 7*12:
955 def convert_midi (f, o):
956 global clocks_per_1, clocks_per_4, key
958 str = open (f).read ()
959 midi_dump = midi.parse (str)
961 clocks_per_1 = midi_dump[0][1]
962 clocks_per_4 = clocks_per_1 / 4
964 global start_quant, start_quant_clocks
966 start_quant_clocks = clocks_per_1 / start_quant
968 global duration_quant, duration_quant_clocks
970 duration_quant_clocks = clocks_per_1 / duration_quant
972 global allowed_tuplet_clocks
973 allowed_tuplet_clocks = []
974 for (dur, num, den) in allowed_tuplets:
975 allowed_tuplet_clocks.append (clocks_per_1 * num / (dur * den))
978 for t in midi_dump[1]:
980 tracks.append (split_track (t))
982 tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, f)
986 s = tag + '\n\\version "2.3.25"\n\n'
987 for i in range (len (tracks)):
988 s = s + dump_track (tracks[i], i)
990 s = s + '\n\\score {\n <<\n'
991 for i in range (len (tracks)):
992 track = track_name (i)
993 item = track_first_item (tracks[i])
994 if item and item.__class__ == Note:
995 s = s + ' \\context Staff=%s \\%s\n' % (track, track)
996 elif item and item.__class__ == Text:
997 s = s + ' \\context Lyrics=%s \\%s\n' % (track, track)
1000 progress (_ ("%s output to `%s'...") % ('LY', o))
1011 (sh, long) = getopt_args (option_definitions)
1013 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
1014 except getopt.error, s:
1015 errorport.write ('\n')
1016 errorport.write (_ ("error: ") + _ ("getopt says: `%s\'" % s))
1017 errorport.write ('\n')
1018 errorport.write ('\n')
1028 elif o == '--help' or o == '-h':
1030 errorport.write ('\n')
1031 errorport.write (_ ("Example:"))
1032 errorport.write (r'''
1033 midi2ly --key=-2:1 --duration-quant=32 \
1034 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
1037 elif o == '--output' or o == '-o':
1039 elif o == '--verbose' or o == '-V':
1041 elif o == '--version' or o == '-v':
1044 elif o == '--warranty' or o == '-w':
1045 status = system ('lilypond -w', ignore_error = 1)
1051 elif o == '--absolute-pitches' or o == '-a':
1053 elif o == '--duration-quant' or o == '-d':
1054 duration_quant = string.atoi (a)
1055 elif o == '--explicit-durations' or o == '-e':
1056 explicit_durations_p = 1
1057 elif o == '--key' or o == '-k':
1058 (alterations, minor) = map (string.atoi, string.split (a + ':0', ':'))[0:2]
1061 if alterations >= 0:
1062 sharps = alterations
1064 flats = - alterations
1065 key = Key (sharps, flats, minor)
1066 elif o == '--start-quant' or o == '-s':
1067 start_quant = string.atoi (a)
1068 elif o == '--allow-tuplet' or o == '-t':
1069 a = string.replace (a, '/', '*')
1070 tuplet = map (string.atoi, string.split (a, '*'))
1071 allowed_tuplets.append (tuplet)
1072 # lots of midi files use plain text for lyric events
1073 elif o == '--text-lyrics' or o == '-x':
1077 if not files or files[0] == '-':
1079 # FIXME: read from stdin when files[0] = '-'
1081 errorport.write (program_name + ":" + _ ("error: ") + _ ("no files specified on command line.") + '\n')
1087 g = strip_extension (g, '.midi')
1088 g = strip_extension (g, '.mid')
1089 g = strip_extension (g, '.MID')
1090 (outdir, outbase) = ('','')
1094 outbase = os.path.basename (g)
1095 o = os.path.join (outdir, outbase + '-midi.ly')
1096 elif output_name[-1] == os.sep:
1097 outdir = output_name
1098 outbase = os.path.basename (g)
1099 os.path.join (outdir, outbase + '-gen.ly')
1102 (outdir, outbase) = os.path.split (o)
1104 if outdir != '.' and outdir != '':
1106 os.mkdir (outdir, 0777)