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 # dynamic relocation, for GUB binaries.
54 bindir = os.path.split (sys.argv[0])[0]
55 for p in ['share', 'lib']:
56 datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % p)
57 sys.path.insert (0, datadir)
59 ################################################################
64 ################################################################
65 ################ CONSTANTS
70 scale_steps = [0,2,4,5,7,9,11]
79 start_quant_clocks = 0
81 duration_quant_clocks = 0
82 allowed_tuplet_clocks = []
85 ################################################################
87 localedir = '@localedir@'
90 gettext.bindtextdomain ('lilypond', localedir)
91 gettext.textdomain ('lilypond')
97 program_name = sys.argv[0]
98 program_version = '@TOPLEVEL_VERSION@'
100 errorport = sys.stderr
103 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
107 sys.stdout.write ('''
116 _('Distributed under terms of the GNU General Public License.'),
117 _('It comes with NO WARRANTY.'))
121 errorport.write (s + '\n')
124 progress (_ ("warning: ") + s)
127 progress (_ ("error: ") + s)
128 raise _ ("Exiting ... ")
130 def system (cmd, ignore_error = 0):
131 return ly.system (cmd, ignore_error=ignore_error)
133 def strip_extension (f, ext):
134 (p, e) = os.path.splitext (f)
143 allowed_durs = (1, 2, 4, 8, 16, 32, 64, 128)
144 def __init__ (self, clocks):
147 self.clocks = duration_quant_clocks
148 (self.dur, self.num, self.den) = self.dur_num_den (clocks)
150 def dur_num_den (self, clocks):
151 for i in range (len (allowed_tuplet_clocks)):
152 if clocks == allowed_tuplet_clocks[i]:
153 return global_options.allowed_tuplets[i]
155 dur = 0; num = 1; den = 1;
156 g = gcd (clocks, clocks_per_1)
158 (dur, num) = (clocks_per_1 / g, clocks / g)
159 if not dur in self.allowed_durs:
160 dur = 4; num = clocks; den = clocks_per_4
161 return (dur, num, den)
167 elif self.num == 3 and self.dur != 1:
168 s = '%d.' % (self.dur / 2)
170 s = '%d*%d' % (self.dur, self.num)
172 s = '%d*%d/%d' % (self.dur, self.num, self.den)
174 global reference_note
175 reference_note.duration = self
179 def compare (self, other):
180 return self.clocks - other.clocks
189 names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
190 alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
191 alteration_names = ('eses', 'es', '', 'is' , 'isis')
192 def __init__ (self, clocks, pitch, velocity):
194 self.velocity = velocity
197 self.duration = Duration (clocks)
198 (self.octave, self.notename, self.alteration) = self.o_n_a ()
202 # minor scale: la-la (= + 5) '''
204 n = self.names[(self.pitch) % 12]
205 a = self.alterations[(self.pitch) % 12]
207 if a and global_options.key.flats:
208 a = - self.alterations[(self.pitch) % 12]
211 # By tradition, all scales now consist of a sequence
212 # of 7 notes each with a distinct name, from amongst
213 # a b c d e f g. But, minor scales have a wide
214 # second interval at the top - the 'leading note' is
215 # sharped. (Why? it just works that way! Anything
216 # else doesn't sound as good and isn't as flexible at
217 # saying things. In medieval times, scales only had 6
218 # notes to avoid this problem - the hexachords.)
220 # So, the d minor scale is d e f g a b-flat c-sharp d
221 # - using d-flat for the leading note would skip the
222 # name c and duplicate the name d. Why isn't c-sharp
223 # put in the key signature? Tradition. (It's also
224 # supposedly based on the Pythagorean theory of the
225 # cycle of fifths, but that really only applies to
226 # major scales...) Anyway, g minor is g a b-flat c d
227 # e-flat f-sharp g, and all the other flat minor keys
228 # end up with a natural leading note. And there you
231 # John Sankey <bf250@freenet.carleton.ca>
233 # Let's also do a-minor: a b c d e f gis a
237 o = self.pitch / 12 - 4
239 key = global_options.key
242 if key.sharps == 0 and key.flats == 0 \
243 and n == 5 and a == -1:
246 elif key.flats == 1 and n == 1 and a == -1:
249 elif key.flats == 2 and n == 4 and a == -1:
252 elif key.sharps == 5 and n == 4 and a == 0:
255 elif key.sharps == 6 and n == 1 and a == 0:
258 elif key.sharps == 7 and n == 5 and a == 0:
262 if key.flats >= 6 and n == 6 and a == 0:
263 n = 0; a = -1; o = o + 1
265 if key.flats >= 7 and n == 2 and a == 0:
269 if key.sharps >= 3 and n == 3 and a == 0:
272 if key.sharps >= 4 and n == 0 and a == 0:
273 n = 6; a = 1; o = o - 1
278 s = chr ((self.notename + 2) % 7 + ord ('a'))
279 return 'Note(%s %s)' % (s, self.duration.dump())
281 def dump (self, dump_dur = 1):
282 global reference_note
283 s = chr ((self.notename + 2) % 7 + ord ('a'))
284 s = s + self.alteration_names[self.alteration + 2]
285 if global_options.absolute_pitches:
288 delta = self.pitch - reference_note.pitch
289 commas = sign (delta) * (abs (delta) / 12)
291 * (self.notename - reference_note.notename) + 7) \
293 or ((self.notename == reference_note.notename) \
294 and (abs (delta) > 4) and (abs (delta) < 12)):
295 commas = commas + sign (delta)
300 s = s + "," * -commas
302 ## FIXME: compile fix --jcn
303 if dump_dur and (global_options.explicit_durations \
304 or Duration.compare (self.duration,
305 reference_note.duration)):
306 s = s + self.duration.dump ()
308 reference_note = self
315 def __init__ (self, num, den):
320 def bar_clocks (self):
321 return clocks_per_1 * self.num / self.den
324 return 'Time(%d/%d)' % (self.num, self.den)
329 return '\n ' + '\\time %d/%d ' % (self.num, self.den) + '\n '
332 def __init__ (self, seconds_per_1):
334 self.seconds_per_1 = seconds_per_1
337 return 'Tempo(%d)' % self.bpm ()
340 return 4 * 60 / self.seconds_per_1
343 return '\n ' + '\\tempo 4 = %d ' % (self.bpm()) + '\n '
346 clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
347 def __init__ (self, type):
351 return 'Clef(%s)' % self.clefs[self.type]
354 return '\n \\clef %s\n ' % self.clefs[self.type]
357 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
358 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
360 def __init__ (self, sharps, flats, minor):
371 if self.sharps and self.flats:
375 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
377 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
380 name = chr ((k + 2) % 7 + ord ('a'))
382 name = chr ((k + 2) % 7 + ord ('a'))
384 # fis cis gis dis ais eis bis
385 sharps = (2, 4, 6, 1, 3, 5, 7)
386 # bes es as des ges ces fes
387 flats = (6, 4, 2, 7, 5, 3, 1)
390 if flats[k] <= self.flats:
393 if sharps[k] <= self.sharps:
397 name = name + Note.alteration_names[a + 2]
405 return '\n\n ' + s + '\n '
413 'SEQUENCE_TRACK_NAME',
419 def __init__ (self, type, text):
425 # urg, we should be sure that we're in a lyrics staff
426 if self.type == midi.LYRIC:
427 s = '"%s"' % self.text
428 d = Duration (self.clocks)
429 if global_options.explicit_durations \
430 or Duration.compare (d,
431 reference_note.duration):
432 s = s + Duration (self.clocks).dump ()
435 s = '\n % [' + self.text_types[self.type] + '] ' + self.text + '\n '
439 return 'Text(%d=%s)' % (self.type, self.text)
443 def split_track (track):
450 if data[0] > 0x7f and data[0] < 0xf0:
452 e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
462 for v in chs.values ():
463 events = events_on_channel (v)
464 thread = unthread_notes (events)
466 threads.append (thread)
470 def quantise_clocks (clocks, quant):
471 q = int (clocks / quant) * quant
473 for tquant in allowed_tuplet_clocks:
474 if int (clocks / tquant) * tquant == clocks:
476 if 2 * (clocks - q) > quant:
480 def end_note (pitches, notes, t, e):
482 (lt, vel) = pitches[e]
492 if duration_quant_clocks:
493 d = quantise_clocks (d, duration_quant_clocks)
495 d = duration_quant_clocks
498 (lt, Note (d, e, vel)))
503 def events_on_channel (channel):
513 if start_quant_clocks:
514 t = quantise_clocks (t, start_quant_clocks)
517 if e[1][0] == midi.NOTE_OFF \
518 or (e[1][0] == midi.NOTE_ON and e[1][2] == 0):
519 end_note (pitches, notes, t, e[1][1])
521 elif e[1][0] == midi.NOTE_ON:
522 if not pitches.has_key (e[1][1]):
523 pitches[e[1][1]] = (t, e[1][2])
525 # all include ALL_NOTES_OFF
526 elif e[1][0] >= midi.ALL_SOUND_OFF \
527 and e[1][0] <= midi.POLY_MODE_ON:
528 for i in pitches.keys ():
529 end_note (pitches, notes, t, i)
531 elif e[1][0] == midi.META_EVENT:
532 if e[1][1] == midi.END_OF_TRACK:
533 for i in pitches.keys ():
534 end_note (pitches, notes, t, i)
537 elif e[1][1] == midi.SET_TEMPO:
538 (u0, u1, u2) = map (ord, e[1][2])
539 us_per_4 = u2 + 256 * (u1 + 256 * u0)
540 seconds_per_1 = us_per_4 * 4 / 1e6
541 events.append ((t, Tempo (seconds_per_1)))
542 elif e[1][1] == midi.TIME_SIGNATURE:
543 (num, dur, clocks4, count32) = map (ord, e[1][2])
545 events.append ((t, Time (num, den)))
546 elif e[1][1] == midi.KEY_SIGNATURE:
547 (alterations, minor) = map (ord, e[1][2])
550 if alterations < 127:
553 flats = 256 - alterations
555 k = Key (sharps, flats, minor)
556 events.append ((t, k))
558 # ugh, must set key while parsing
559 # because Note init uses key
560 # Better do Note.calc () at dump time?
564 elif e[1][1] == midi.LYRIC \
565 or (global_options.text_lyrics and e[1][1] == midi.TEXT_EVENT):
567 last_lyric.clocks = t - last_time
568 events.append ((last_time, last_lyric))
570 last_lyric = Text (midi.LYRIC, e[1][2])
572 elif e[1][1] >= midi.SEQUENCE_NUMBER \
573 and e[1][1] <= midi.CUE_POINT:
574 events.append ((t, Text (e[1][1], e[1][2])))
576 if global_options.verbose:
577 sys.stderr.write ("SKIP: %s\n" % `e`)
580 if global_options.verbose:
581 sys.stderr.write ("SKIP: %s\n" % `e`)
585 # last_lyric.clocks = t - last_time
587 last_lyric.clocks = clocks_per_4
588 events.append ((last_time, last_lyric))
593 if i < len (events) and notes[0][0] >= events[i][0]:
596 events.insert (i, notes[0])
600 def unthread_notes (channel):
609 if e[1].__class__ == Note \
610 and ((t == start_busy_t \
611 and e[1].clocks + t == end_busy_t) \
615 end_busy_t = t + e[1].clocks
616 elif e[1].__class__ == Time \
617 or e[1].__class__ == Key \
618 or e[1].__class__ == Text \
619 or e[1].__class__ == Tempo:
623 threads.append (thread)
638 def dump_skip (skip, clocks):
639 return skip + Duration (clocks).dump () + ' '
648 if i.__class__ == Note:
653 s = s + dump (notes[0])
654 elif len (notes) > 1:
655 global reference_note
657 s = s + notes[0].dump (dump_dur = 0)
660 s = s + i.dump (dump_dur = 0 )
663 s = s + notes[0].duration.dump() + ' '
667 def dump_bar_line (last_bar_t, t, bar_count):
669 bar_t = time.bar_clocks ()
670 if t - last_bar_t >= bar_t:
671 bar_count = bar_count + (t - last_bar_t) / bar_t
673 if t - last_bar_t == bar_t:
674 s = '|\n %% %d\n ' % bar_count
677 # urg, this will barf at meter changes
678 last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
680 return (s, last_bar_t, bar_count)
683 def dump_channel (thread, skip):
684 global key, reference_note, time
688 # urg LilyPond doesn't start at c4, but
689 # remembers from previous tracks!
690 # reference_note = Note (clocks_per_4, 4*12, 0)
691 reference_note = Note (0, 4*12, 0)
697 if last_e and last_e[0] == e[0]:
701 chs.append ((last_e[0], ch))
708 chs.append ((last_e[0], ch))
718 i = string.rfind (lines[-1], '\n') + 1
719 if len (lines[-1][i:]) > LINE_BELL:
723 lines[-1] = lines[-1] + dump_skip (skip, t-last_t)
725 errorport.write ('BUG: time skew')
727 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
729 lines[-1] = lines[-1] + s
731 lines[-1] = lines[-1] + dump_chord (ch[1])
735 if i.clocks > clocks:
740 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
742 lines[-1] = lines[-1] + s
744 return string.join (lines, '\n ') + '\n'
747 return 'track%c' % (i + ord ('A'))
749 def channel_name (i):
750 return 'channel%c' % (i + ord ('A'))
752 def dump_track (channels, n):
754 track = track_name (n)
755 clef = guess_clef (channels)
757 for i in range (len (channels)):
758 channel = channel_name (i)
759 item = thread_first_item (channels[i])
761 if item and item.__class__ == Note:
763 s = s + '%s = ' % (track + channel)
764 if not global_options.absolute_pitches:
765 s = s + '\\relative c '
766 elif item and item.__class__ == Text:
768 s = s + '%s = \\lyricmode ' % (track + channel)
771 s = s + '%s = ' % (track + channel)
773 s = s + ' ' + dump_channel (channels[i][0], skip)
776 s = s + '%s = <<\n' % track
779 s = s + clef.dump () + '\n'
781 for i in range (len (channels)):
782 channel = channel_name (i)
783 item = thread_first_item (channels[i])
784 if item and item.__class__ == Text:
785 s = s + ' \\context Lyrics = %s \\%s\n' % (channel,
788 s = s + ' \\context Voice = %s \\%s\n' % (channel,
793 def thread_first_item (thread):
796 if (event[1].__class__ == Note
797 or (event[1].__class__ == Text
798 and event[1].type == midi.LYRIC)):
803 def track_first_item (track):
805 first = thread_first_item (thread)
810 def guess_clef (track):
816 if event[1].__class__ == Note:
818 p = p + event[1].pitch
819 if i and p / i <= 3*12:
821 elif i and p / i <= 5*12:
823 elif i and p / i >= 7*12:
829 def convert_midi (in_file, out_file):
830 global clocks_per_1, clocks_per_4, key
831 global start_quant_clocks
832 global duration_quant_clocks
833 global allowed_tuplet_clocks
835 str = open (in_file).read ()
836 midi_dump = midi.parse (str)
838 clocks_per_1 = midi_dump[0][1]
839 clocks_per_4 = clocks_per_1 / 4
841 if global_options.start_quant:
842 start_quant_clocks = clocks_per_1 / global_options.start_quant
844 if global_options.duration_quant:
845 duration_quant_clocks = clocks_per_1 / global_options.duration_quant
847 allowed_tuplet_clocks = []
848 for (dur, num, den) in global_options.allowed_tuplets:
849 allowed_tuplet_clocks.append (clocks_per_1 * num / (dur * den))
852 for t in midi_dump[1]:
854 tracks.append (split_track (t))
856 tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, f)
860 s = tag + '\n\\version "2.7.18"\n\n'
861 for i in range (len (tracks)):
862 s = s + dump_track (tracks[i], i)
864 s = s + '\n\\score {\n <<\n'
868 track = track_name (i)
869 item = track_first_item (t)
871 if item and item.__class__ == Note:
872 s = s + ' \\context Staff=%s \\%s\n' % (track, track)
873 elif item and item.__class__ == Text:
874 s = s + ' \\context Lyrics=%s \\%s\n' % (track, track)
879 progress (_ ("%s output to `%s'...") % ('LY', o))
884 handle = open (out_file, 'w')
890 def get_option_parser ():
891 p = ly.get_option_parser (usage='midi2ly [OPTIONS] FILE',
892 version="midi2ly (LilyPond) @TOPLEVEL_VERSION@",
893 description=_('''Convert MIDI to LilyPond source.'''))
895 p.add_option ('-a', '--absolute-pitches',
897 help=_ ("print absolute pitches"))
898 p.add_option ('-d', '--duration-quant',
900 help=_("quantise note durations on DUR"))
901 p.add_option ('-e', '--explicit-durations',
903 help=_ ("print explicit durations"))
904 p.add_option('-k', '--key', help=_ ("set key: ALT=+sharps|-flats; MINOR=1"),
905 metavar=_ ("ALT[:MINOR]"),
907 p.add_option ('-o', '--output', help=_("write output to FILE"),
910 p.add_option ('-s', '--start-quant',help= _ ("quantise note starts on DUR"),
912 p.add_option ('-t', '--allow-tuplet',
913 metavar=_ ("DUR*NUM/DEN"),
915 dest="allowed_tuplets",
916 help=_ ("allow tuplet durations DUR*NUM/DEN"),
918 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
921 p.add_option ('-w', '--warranty', help=_ ("show warranty"),
924 p.add_option ('-x', '--text-lyrics', help=_("treat every text as a lyric"),
927 p.add_option_group (_ ("example"),
929 midi2ly --key=-2:1 --duration-quant=32 \
930 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
933 p.add_option_group ('bugs',
934 description='''Report bugs via http://post.gmane.org/post.php'''
935 '''?group=gmane.comp.gnu.lilypond.bugs\n''')
942 opt_parser = get_option_parser()
943 (options, args) = opt_parser.parse_args ()
945 if not args or args[0] == '-':
946 opt_parser.print_help ()
947 sys.stderr.write ('\n%s: %s %s\n' % (program_name, _ ("error: "),
948 _ ("no files specified on command line.")))
951 if options.duration_quant:
952 options.duration_quant = string.atoi (options.duration_quant)
958 (alterations, minor) = map (string.atoi, string.split (options.key + ':0', ':'))[0:2]
964 flats = - alterations
966 options.key = Key (sharps, flats, minor)
969 if options.start_quant:
970 options.start_quant = string.atoi (a)
972 options.allowed_tuplets = [map (string.atoi, a.replace ('/','*').split ('*'))
973 for a in options.allowed_tuplets]
975 global global_options
976 global_options = options
985 g = strip_extension (g, '.midi')
986 g = strip_extension (g, '.mid')
987 g = strip_extension (g, '.MID')
988 (outdir, outbase) = ('','')
992 outbase = os.path.basename (g)
993 o = os.path.join (outdir, outbase + '-midi.ly')
994 elif output_name[-1] == os.sep:
996 outbase = os.path.basename (g)
997 os.path.join (outdir, outbase + '-gen.ly')
1000 (outdir, outbase) = os.path.split (o)
1002 if outdir != '.' and outdir != '':
1004 os.mkdir (outdir, 0777)