3 # midi2ly.py -- LilyPond midi import script
5 # source file of the GNU LilyPond music typesetter
7 # (c) 1998--2002 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 # If set, LILYPONDPREFIX must take prevalence
35 # if datadir is not set, we're doing a build and LILYPONDPREFIX
36 datadir = '@local_lilypond_datadir@'
37 if not os.path.isdir (datadir):
38 datadir = '@lilypond_datadir@'
39 if os.environ.has_key ('LILYPONDPREFIX') :
40 datadir = os.environ['LILYPONDPREFIX']
41 while datadir[-1] == os.sep:
44 sys.path.insert (0, os.path.join (datadir, 'python'))
45 ################################################################
50 ################################################################
51 ################ CONSTANTS
56 scale_steps = [0,2,4,5,7,9,11]
64 start_quant_clocks = 0
66 duration_quant_clocks = 0
68 allowed_tuplet_clocks = []
70 explicit_durations_p = 0
75 ################################################################
77 localedir = '@localedir@'
80 gettext.bindtextdomain ('lilypond', localedir)
81 gettext.textdomain ('lilypond')
87 program_name = 'midi2ly'
88 program_version = '@TOPLEVEL_VERSION@'
90 errorport = sys.stderr
93 # temp_dir = os.path.join (original_dir, '%s.dir' % program_name)
94 # original_dir = os.getcwd ()
98 help_summary = _ ("Convert MIDI to LilyPond source")
100 option_definitions = [
101 ('', 'a', 'absolute-pitches', _ ("print absolute pitches")),
102 (_ ("DUR"), 'd', 'duration-quant', _ ("quantise note durations on DUR")),
103 ('', 'e', 'explicit-durations', _ ("print explicit durations")),
104 ('', 'h', 'help', _ ("this help")),
105 (_ ("ALT[:MINOR]"), 'k', 'key', _ ("set key: ALT=+sharps|-flats; MINOR=1")),
106 (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
107 (_ ("DUR"), 's', 'start-quant', _ ("quantise note starts on DUR")),
108 (_ ("DUR*NUM/DEN"), 't', 'allow-tuplet', _ ("allow tuplet durations DUR*NUM/DEN")),
109 ('', 'V', 'verbose', _ ("verbose")),
110 ('', 'v', 'version', _ ("print version number")),
111 ('', 'w', 'warranty', _ ("show warranty and copyright")),
112 ('', 'x', 'text-lyrics', _ ("treat every text as a lyric")),
115 ################################################################
116 # lilylib.py -- options and stuff
118 # source file of the GNU LilyPond music typesetter
124 gettext.bindtextdomain ('lilypond', localedir)
125 gettext.textdomain ('lilypond')
131 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
132 program_version = '1.5.17'
135 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
139 sys.stdout.write ('\n')
140 sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001--2002'))
141 sys.stdout.write ('\n')
142 sys.stdout.write (' Han-Wen Nienhuys')
143 sys.stdout.write (' Jan Nieuwenhuizen')
144 sys.stdout.write ('\n')
145 sys.stdout.write (_ (r'''
146 Distributed under terms of the GNU General Public License. It comes with
148 sys.stdout.write ('\n')
151 errorport.write (s + '\n')
154 progress (_ ("warning: ") + s)
159 '''Report the error S. Exit by raising an exception. Please
160 do not abuse by trying to catch this error. If you do not want
161 a stack trace, write to the output directly.
169 progress (_ ("error: ") + s)
170 raise _ ("Exiting ... ")
172 def getopt_args (opts):
173 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
188 def option_help_str (o):
189 '''Transform one option description (4-tuple ) into neatly formatted string'''
207 return ' ' + sh + sep + long + arg
210 def options_help_str (opts):
211 '''Convert a list of options into a neatly formatted string'''
217 s = option_help_str (o)
218 strs.append ((s, o[3]))
224 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
228 ls = [(_ ("Usage: %s [OPTION]... FILE") % program_name),
234 (options_help_str (option_definitions)),
236 (_ ("Report bugs to %s") % 'bug-lilypond@gnu.org'),
238 map (sys.stdout.write, ls)
242 Create a temporary directory, and return its name.
245 if not keep_temp_dir_p:
246 temp_dir = tempfile.mktemp (program_name)
248 os.mkdir (temp_dir, 0777)
255 def system (cmd, ignore_error = 0):
256 """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
264 progress (_ ("Invoking `%s\'") % cmd)
267 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
268 msg = name + ': ' + _ ("command exited with value %d") % st
270 warning (msg + ' ' + _ ("(ignored)") + ' ')
278 if not keep_temp_dir_p:
280 progress (_ ("Cleaning %s...") % temp_dir)
281 shutil.rmtree (temp_dir)
284 def strip_extension (f, ext):
285 (p, e) = os.path.splitext (f)
290 ################################################################
292 ################################################################
298 allowed_durs = (1, 2, 4, 8, 16, 32, 64, 128)
299 def __init__ (self, clocks):
302 self.clocks = duration_quant_clocks
303 (self.dur, self.num, self.den) = self.dur_num_den (clocks)
305 def dur_num_den (self, clocks):
306 for i in range (len (allowed_tuplet_clocks)):
307 if clocks == allowed_tuplet_clocks[i]:
308 return allowed_tuplets[i]
310 dur = 0; num = 1; den = 1;
311 g = gcd (clocks, clocks_per_1)
313 (dur, num) = (clocks_per_1 / g, clocks / g)
314 if not dur in self.allowed_durs:
315 dur = 4; num = clocks; den = clocks_per_4
316 return (dur, num, den)
322 elif self.num == 3 and self.dur != 1:
323 s = '%d.' % (self.dur / 2)
325 s = '%d*%d' % (self.dur, self.num)
327 s = '%d*%d/%d' % (self.dur, self.num, self.den)
329 global reference_note
330 reference_note.duration = self
334 def compare (self, other):
335 return self.clocks - other.clocks
344 names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
345 alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
346 alteration_names = ('eses', 'es', '', 'is' , 'isis')
348 def __init__ (self, clocks, pitch, velocity):
350 self.velocity = velocity
353 self.duration = Duration (clocks)
354 (self.octave, self.notename, self.alteration) = self.o_n_a ()
358 # minor scale: la-la (= + 5) '''
360 n = self.names[(self.pitch) % 12]
361 a = self.alterations[(self.pitch) % 12]
364 a = - self.alterations[(self.pitch) % 12]
367 # By tradition, all scales now consist of a sequence
368 # of 7 notes each with a distinct name, from amongst
369 # a b c d e f g. But, minor scales have a wide
370 # second interval at the top - the 'leading note' is
371 # sharped. (Why? it just works that way! Anything
372 # else doesn't sound as good and isn't as flexible at
373 # saying things. In medieval times, scales only had 6
374 # notes to avoid this problem - the hexachords.)
376 # So, the d minor scale is d e f g a b-flat c-sharp d
377 # - using d-flat for the leading note would skip the
378 # name c and duplicate the name d. Why isn't c-sharp
379 # put in the key signature? Tradition. (It's also
380 # supposedly based on the Pythagorean theory of the
381 # cycle of fifths, but that really only applies to
382 # major scales...) Anyway, g minor is g a b-flat c d
383 # e-flat f-sharp g, and all the other flat minor keys
384 # end up with a natural leading note. And there you
387 # John Sankey <bf250@freenet.carleton.ca>
389 # Let's also do a-minor: a b c d e f gis a
393 o = self.pitch / 12 - 4
397 if key.sharps == 0 and key.flats == 0 \
398 and n == 5 and a == -1:
401 elif key.flats == 1 and n == 1 and a == -1:
404 elif key.flats == 2 and n == 4 and a == -1:
407 elif key.sharps == 5 and n == 4 and a == 0:
410 elif key.sharps == 6 and n == 1 and a == 0:
413 elif key.sharps == 7 and n == 5 and a == 0:
417 if key.flats >= 6 and n == 6 and a == 0:
418 n = 0; a = -1; o = o + 1
420 if key.flats >= 7 and n == 2 and a == 0:
424 if key.sharps >= 3 and n == 3 and a == 0:
427 if key.sharps >= 4 and n == 0 and a == 0:
428 n = 6; a = 1; o = o - 1
432 def dump (self, dump_dur = 1):
433 global reference_note
434 s = chr ((self.notename + 2) % 7 + ord ('a'))
435 s = s + self.alteration_names[self.alteration + 2]
439 delta = self.pitch - reference_note.pitch
440 commas = sign (delta) * (abs (delta) / 12)
442 * (self.notename - reference_note.notename) + 7) \
444 or ((self.notename == reference_note.notename) \
445 and (abs (delta) > 4) and (abs (delta) < 12)):
446 commas = commas + sign (delta)
451 s = s + "," * -commas
453 if and dump_dur (explicit_durations_p \
454 or Duration.compare (self.duration,
455 reference_note.duration)):
456 s = s + self.duration.dump ()
458 reference_note = self
465 def __init__ (self, num, den):
470 def bar_clocks (self):
471 return clocks_per_1 * self.num / self.den
476 return '\n ' + '\\time %d/%d ' % (self.num, self.den) + '\n '
479 def __init__ (self, seconds_per_1):
481 self.seconds_per_1 = seconds_per_1
484 return '\n ' + '\\tempo 4 = %d ' % (4 * 60 / self.seconds_per_1) + '\n '
487 clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
488 def __init__ (self, type):
492 return '\n \\clef %s\n ' % self.clefs[self.type]
495 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
496 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
498 def __init__ (self, sharps, flats, minor):
509 if self.sharps and self.flats:
510 s = '\\keysignature %s ' % 'TODO'
514 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
516 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
519 name = chr ((k + 2) % 7 + ord ('a'))
521 name = chr ((k + 2) % 7 + ord ('a'))
523 # fis cis gis dis ais eis bis
524 sharps = (2, 4, 6, 1, 3, 5, 7)
525 # bes es as des ges ces fes
526 flats = (6, 4, 2, 7, 5, 3, 1)
529 if flats[k] <= self.flats:
532 if sharps[k] <= self.sharps:
536 name = name + Note.alteration_names[a + 2]
544 return '\n\n ' + s + '\n '
552 'SEQUENCE_TRACK_NAME',
558 def __init__ (self, type, text):
564 # urg, we should be sure that we're in a lyrics staff
565 if self.type == midi.LYRIC:
566 s = '"%s"' % self.text
567 d = Duration (self.clocks)
568 if explicit_durations_p \
569 or Duration.compare (d,
570 reference_note.duration):
571 s = s + Duration (self.clocks).dump ()
574 s = '\n % [' + self.text_types[self.type] + '] ' + self.text + '\n '
578 def split_track (track):
585 if data[0] > 0x7f and data[0] < 0xf0:
587 e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
597 for v in chs.values ():
598 events = events_on_channel (v)
599 thread = unthread_notes (events)
601 threads.append (thread)
605 def quantise_clocks (clocks, quant):
606 q = int (clocks / quant) * quant
608 for tquant in allowed_tuplet_clocks:
609 if int (clocks / tquant) * tquant == clocks:
611 if 2 * (clocks - q) > quant:
615 def end_note (pitches, notes, t, e):
617 (lt, vel) = pitches[e]
627 if duration_quant_clocks:
628 d = quantise_clocks (d, duration_quant_clocks)
630 d = duration_quant_clocks
633 (lt, Note (d, e, vel)))
638 def events_on_channel (channel):
648 if start_quant_clocks:
649 t = quantise_clocks (t, start_quant_clocks)
652 if e[1][0] == midi.NOTE_OFF \
653 or (e[1][0] == midi.NOTE_ON and e[1][2] == 0):
654 end_note (pitches, notes, t, e[1][1])
656 elif e[1][0] == midi.NOTE_ON:
657 if not pitches.has_key (e[1][1]):
658 pitches[e[1][1]] = (t, e[1][2])
660 # all include ALL_NOTES_OFF
661 elif e[1][0] >= midi.ALL_SOUND_OFF \
662 and e[1][0] <= midi.POLY_MODE_ON:
663 for i in pitches.keys ():
664 end_note (pitches, notes, t, i)
666 elif e[1][0] == midi.META_EVENT:
667 if e[1][1] == midi.END_OF_TRACK:
668 for i in pitches.keys ():
669 end_note (pitches, notes, t, i)
672 elif e[1][1] == midi.SET_TEMPO:
673 (u0, u1, u2) = map (ord, e[1][2])
674 us_per_4 = u2 + 256 * (u1 + 256 * u0)
675 seconds_per_1 = us_per_4 * 4 / 1e6
676 events.append ((t, Tempo (seconds_per_1)))
677 elif e[1][1] == midi.TIME_SIGNATURE:
678 (num, dur, clocks4, count32) = map (ord, e[1][2])
680 events.append ((t, Time (num, den)))
681 elif e[1][1] == midi.KEY_SIGNATURE:
682 (alterations, minor) = map (ord, e[1][2])
685 if alterations < 127:
688 flats = 256 - alterations
690 k = Key (sharps, flats, minor)
691 events.append ((t, k))
693 # ugh, must set key while parsing
694 # because Note init uses key
695 # Better do Note.calc () at dump time?
699 elif e[1][1] == midi.LYRIC \
700 or (text_lyrics_p and e[1][1] == midi.TEXT_EVENT):
702 last_lyric.clocks = t - last_time
703 events.append ((last_time, last_lyric))
705 last_lyric = Text (midi.LYRIC, e[1][2])
707 elif e[1][1] >= midi.SEQUENCE_NUMBER \
708 and e[1][1] <= midi.CUE_POINT:
709 events.append ((t, Text (e[1][1], e[1][2])))
712 sys.stderr.write ("SKIP: %s\n" % `e`)
716 sys.stderr.write ("SKIP: %s\n" % `e`)
720 # last_lyric.clocks = t - last_time
722 last_lyric.clocks = clocks_per_4
723 events.append ((last_time, last_lyric))
728 if i < len (events) and notes[0][0] >= events[i][0]:
731 events.insert (i, notes[0])
735 def unthread_notes (channel):
744 if e[1].__class__ == Note \
745 and ((t == start_busy_t \
746 and e[1].clocks + t == end_busy_t) \
750 end_busy_t = t + e[1].clocks
751 elif e[1].__class__ == Time \
752 or e[1].__class__ == Key \
753 or e[1].__class__ == Text \
754 or e[1].__class__ == Tempo:
758 threads.append (thread)
773 def dump_skip (skip, clocks):
774 return skip + Duration (clocks).dump () + ' '
783 if i.__class__ == Note:
788 s = s + dump (notes[0])
789 elif len (notes) > 1:
790 global reference_note
792 s = s + notes[0].dump (dump_dur = 0)
795 s = s + i.dump (dump_dur = 0 )
798 s = s + notes[0].duration.dump()
802 def dump_bar_line (last_bar_t, t, bar_count):
804 bar_t = time.bar_clocks ()
805 if t - last_bar_t >= bar_t:
806 bar_count = bar_count + (t - last_bar_t) / bar_t
808 if t - last_bar_t == bar_t:
809 s = '|\n %% %d\n ' % bar_count
812 # urg, this will barf at meter changes
813 last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
815 return (s, last_bar_t, bar_count)
818 def dump_channel (thread, skip):
819 global key, reference_note, time
823 # urg LilyPond doesn't start at c4, but
824 # remembers from previous tracks!
825 # reference_note = Note (clocks_per_4, 4*12, 0)
826 reference_note = Note (0, 4*12, 0)
832 if last_e and last_e[0] == e[0]:
836 chs.append ((last_e[0], ch))
843 chs.append ((last_e[0], ch))
853 i = string.rfind (lines[-1], '\n') + 1
854 if len (lines[-1][i:]) > LINE_BELL:
858 lines[-1] = lines[-1] + dump_skip (skip, t-last_t)
860 errorport.write ('BUG: time skew')
862 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
864 lines[-1] = lines[-1] + s
866 lines[-1] = lines[-1] + dump_chord (ch[1])
870 if i.clocks > clocks:
875 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
877 lines[-1] = lines[-1] + s
879 return string.join (lines, '\n ') + '\n'
882 return 'track%c' % (i + ord ('A'))
884 def channel_name (i):
885 return 'channel%c' % (i + ord ('A'))
887 def dump_track (channels, n):
889 track = track_name (n)
890 clef = guess_clef (channels)
892 for i in range (len (channels)):
893 channel = channel_name (i)
894 item = thread_first_item (channels[i])
896 if item and item.__class__ == Note:
898 s = s + '%s = \\notes' % (track + channel)
900 s = s + '\\relative c '
901 elif item and item.__class__ == Text:
903 s = s + '%s = \\lyrics ' % (track + channel)
906 # must be in \notes mode for parsing \skip
907 s = s + '%s = \\notes ' % (track + channel)
909 s = s + ' ' + dump_channel (channels[i][0], skip)
912 s = s + '%s = <\n' % track
915 s = s + clef.dump () + '\n'
917 for i in range (len (channels)):
918 channel = channel_name (i)
919 item = thread_first_item (channels[i])
920 if item and item.__class__ == Text:
921 s = s + ' \\context Lyrics = %s \\%s\n' % (channel,
924 s = s + ' \\context Voice = %s \\%s\n' % (channel,
929 def thread_first_item (thread):
932 if event[1].__class__ == Note \
933 or (event[1].__class__ == Text \
934 and event[1].type == midi.LYRIC):
938 def track_first_item (track):
940 return thread_first_item (thread)
942 def guess_clef (track):
948 if event[1].__class__ == Note:
950 p = p + event[1].pitch
951 if i and p / i <= 3*12:
953 elif i and p / i <= 5*12:
955 elif i and p / i >= 7*12:
961 def convert_midi (f, o):
962 global clocks_per_1, clocks_per_4, key
964 str = open (f).read ()
965 midi_dump = midi.parse (str)
967 clocks_per_1 = midi_dump[0][1]
968 clocks_per_4 = clocks_per_1 / 4
970 global start_quant, start_quant_clocks
972 start_quant_clocks = clocks_per_1 / start_quant
974 global duration_quant, duration_quant_clocks
976 duration_quant_clocks = clocks_per_1 / duration_quant
978 global allowed_tuplet_clocks
979 allowed_tuplet_clocks = []
980 for (dur, num, den) in allowed_tuplets:
981 allowed_tuplet_clocks.append (clocks_per_1 * num / (dur * den))
984 for t in midi_dump[1]:
986 tracks.append (split_track (t))
988 tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, f)
992 for i in range (len (tracks)):
993 s = s + dump_track (tracks[i], i)
995 s = s + '\n\\score {\n <\n'
996 for i in range (len (tracks)):
997 track = track_name (i)
998 item = track_first_item (tracks[i])
999 if item and item.__class__ == Note:
1000 s = s + ' \\context Staff=%s \\%s\n' % (track, track)
1001 elif item and item.__class__ == Text:
1002 s = s + ' \\context Lyrics=%s \\%s\n' % (track, track)
1005 progress (_ ("%s output to `%s'...") % ('LY', o))
1016 (sh, long) = getopt_args (option_definitions)
1018 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
1019 except getopt.error, s:
1020 errorport.write ('\n')
1021 errorport.write (_ ("error: ") + _ ("getopt says: `%s\'" % s))
1022 errorport.write ('\n')
1023 errorport.write ('\n')
1033 elif o == '--help' or o == '-h':
1035 errorport.write ('\n')
1036 errorport.write (_ ("Example:"))
1037 errorport.write (r'''
1038 midi2ly --key=-2:1 --duration-quant=32 \
1039 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
1042 elif o == '--output' or o == '-o':
1044 elif o == '--verbose' or o == '-V':
1046 elif o == '--version' or o == '-v':
1049 elif o == '--warranty' or o == '-w':
1050 status = system ('lilypond -w', ignore_error = 1)
1056 elif o == '--absolute-pitches' or o == '-a':
1058 elif o == '--duration-quant' or o == '-d':
1059 duration_quant = string.atoi (a)
1060 elif o == '--explicit-durations' or o == '-e':
1061 explicit_durations_p = 1
1062 elif o == '--key' or o == '-k':
1063 (alterations, minor) = map (string.atoi, string.split (a + ':0', ':'))[0:2]
1066 if alterations >= 0:
1067 sharps = alterations
1069 flats = - alterations
1070 key = Key (sharps, flats, minor)
1071 elif o == '--start-quant' or o == '-s':
1072 start_quant = string.atoi (a)
1073 elif o == '--allow-tuplet' or o == '-t':
1074 a = string.replace (a, '/', '*')
1075 tuplet = map (string.atoi, string.split (a, '*'))
1076 allowed_tuplets.append (tuplet)
1077 # lots of midi files use plain text for lyric events
1078 elif o == '--text-lyrics' or o == '-x':
1082 if not files or files[0] == '-':
1084 # FIXME: read from stdin when files[0] = '-'
1086 errorport.write (program_name + ":" + _ ("error: ") + _ ("no files specified on command line.") + '\n')
1093 g = strip_extension (g, '.midi')
1094 g = strip_extension (g, '.mid')
1095 g = strip_extension (g, '.MID')
1096 (outdir, outbase) = ('','')
1100 outbase = os.path.basename (g)
1101 o = os.path.join (outdir, outbase + '-midi.ly')
1102 elif output_name[-1] == os.sep:
1103 outdir = output_name
1104 outbase = os.path.basename (g)
1105 os.path.join (outdir, outbase + '-gen.ly')
1108 (outdir, outbase) = os.path.split (o)
1110 if outdir != '.' and outdir != '':
1112 os.mkdir (outdir, 0777)