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
28 ################################################################
29 # Users of python modules should include this snippet.
32 for d in ['@lilypond_datadir@',
34 sys.path.insert (0, os.path.join (d, 'python'))
36 # dynamic relocation, for GUB binaries.
37 bindir = os.path.abspath (os.path.split (sys.argv[0])[0])
38 for p in ['share', 'lib']:
39 datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % p)
40 sys.path.insert (0, datadir)
46 ################################################################
47 ################ CONSTANTS
52 scale_steps = [0,2,4,5,7,9,11]
61 start_quant_clocks = 0
63 duration_quant_clocks = 0
64 allowed_tuplet_clocks = []
67 ################################################################
69 localedir = '@localedir@'
72 gettext.bindtextdomain ('lilypond', localedir)
73 gettext.textdomain ('lilypond')
79 program_name = sys.argv[0]
80 program_version = '@TOPLEVEL_VERSION@'
82 errorport = sys.stderr
85 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
98 _('Distributed under terms of the GNU General Public License.'),
99 _('It comes with NO WARRANTY.')))
103 errorport.write (s + '\n')
106 progress (_ ("warning: ") + s)
109 progress (_ ("error: ") + s)
110 raise _ ("Exiting ... ")
112 def system (cmd, ignore_error = 0):
113 return ly.system (cmd, ignore_error=ignore_error)
115 def strip_extension (f, ext):
116 (p, e) = os.path.splitext (f)
125 allowed_durs = (1, 2, 4, 8, 16, 32, 64, 128)
126 def __init__ (self, clocks):
129 self.clocks = duration_quant_clocks
130 (self.dur, self.num, self.den) = self.dur_num_den (clocks)
132 def dur_num_den (self, clocks):
133 for i in range (len (allowed_tuplet_clocks)):
134 if clocks == allowed_tuplet_clocks[i]:
135 return global_options.allowed_tuplets[i]
137 dur = 0; num = 1; den = 1;
138 g = gcd (clocks, clocks_per_1)
140 (dur, num) = (clocks_per_1 / g, clocks / g)
141 if not dur in self.allowed_durs:
142 dur = 4; num = clocks; den = clocks_per_4
143 return (dur, num, den)
149 elif self.num == 3 and self.dur != 1:
150 s = '%d.' % (self.dur / 2)
152 s = '%d*%d' % (self.dur, self.num)
154 s = '%d*%d/%d' % (self.dur, self.num, self.den)
156 global reference_note
157 reference_note.duration = self
161 def compare (self, other):
162 return self.clocks - other.clocks
171 names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
172 alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
173 alteration_names = ('eses', 'es', '', 'is' , 'isis')
174 def __init__ (self, clocks, pitch, velocity):
176 self.velocity = velocity
179 self.duration = Duration (clocks)
180 (self.octave, self.notename, self.alteration) = self.o_n_a ()
184 # minor scale: la-la (= + 5) '''
186 n = self.names[(self.pitch) % 12]
187 a = self.alterations[(self.pitch) % 12]
189 if a and global_options.key.flats:
190 a = - self.alterations[(self.pitch) % 12]
193 # By tradition, all scales now consist of a sequence
194 # of 7 notes each with a distinct name, from amongst
195 # a b c d e f g. But, minor scales have a wide
196 # second interval at the top - the 'leading note' is
197 # sharped. (Why? it just works that way! Anything
198 # else doesn't sound as good and isn't as flexible at
199 # saying things. In medieval times, scales only had 6
200 # notes to avoid this problem - the hexachords.)
202 # So, the d minor scale is d e f g a b-flat c-sharp d
203 # - using d-flat for the leading note would skip the
204 # name c and duplicate the name d. Why isn't c-sharp
205 # put in the key signature? Tradition. (It's also
206 # supposedly based on the Pythagorean theory of the
207 # cycle of fifths, but that really only applies to
208 # major scales...) Anyway, g minor is g a b-flat c d
209 # e-flat f-sharp g, and all the other flat minor keys
210 # end up with a natural leading note. And there you
213 # John Sankey <bf250@freenet.carleton.ca>
215 # Let's also do a-minor: a b c d e f gis a
219 o = self.pitch / 12 - 4
221 key = global_options.key
224 if (key.sharps == 0 and key.flats == 0
225 and n == 5 and a == -1):
228 elif key.flats == 1 and n == 1 and a == -1:
231 elif key.flats == 2 and n == 4 and a == -1:
234 elif key.sharps == 5 and n == 4 and a == 0:
237 elif key.sharps == 6 and n == 1 and a == 0:
240 elif key.sharps == 7 and n == 5 and a == 0:
244 if key.flats >= 6 and n == 6 and a == 0:
245 n = 0; a = -1; o = o + 1
247 if key.flats >= 7 and n == 2 and a == 0:
251 if key.sharps >= 3 and n == 3 and a == 0:
254 if key.sharps >= 4 and n == 0 and a == 0:
255 n = 6; a = 1; o = o - 1
260 s = chr ((self.notename + 2) % 7 + ord ('a'))
261 return 'Note(%s %s)' % (s, self.duration.dump())
263 def dump (self, dump_dur = 1):
264 global reference_note
265 s = chr ((self.notename + 2) % 7 + ord ('a'))
266 s = s + self.alteration_names[self.alteration + 2]
267 if global_options.absolute_pitches:
270 delta = self.pitch - reference_note.pitch
271 commas = sign (delta) * (abs (delta) / 12)
273 * (self.notename - reference_note.notename) + 7) \
275 or ((self.notename == reference_note.notename) \
276 and (abs (delta) > 4) and (abs (delta) < 12)):
277 commas = commas + sign (delta)
282 s = s + "," * -commas
284 ## FIXME: compile fix --jcn
285 if dump_dur and (global_options.explicit_durations \
286 or self.duration.compare (reference_note.duration)):
287 s = s + self.duration.dump ()
289 reference_note = self
296 def __init__ (self, num, den):
301 def bar_clocks (self):
302 return clocks_per_1 * self.num / self.den
305 return 'Time(%d/%d)' % (self.num, self.den)
310 return '\n ' + '\\time %d/%d ' % (self.num, self.den) + '\n '
313 def __init__ (self, seconds_per_1):
315 self.seconds_per_1 = seconds_per_1
318 return 'Tempo(%d)' % self.bpm ()
321 return 4 * 60 / self.seconds_per_1
324 return '\n ' + '\\tempo 4 = %d ' % (self.bpm()) + '\n '
327 clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
328 def __init__ (self, type):
332 return 'Clef(%s)' % self.clefs[self.type]
335 return '\n \\clef %s\n ' % self.clefs[self.type]
338 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
339 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
341 def __init__ (self, sharps, flats, minor):
348 global_options.key = self
351 if self.sharps and self.flats:
355 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
357 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
360 name = chr ((k + 2) % 7 + ord ('a'))
362 name = chr ((k + 2) % 7 + ord ('a'))
364 # fis cis gis dis ais eis bis
365 sharps = (2, 4, 6, 1, 3, 5, 7)
366 # bes es as des ges ces fes
367 flats = (6, 4, 2, 7, 5, 3, 1)
370 if flats[k] <= self.flats:
373 if sharps[k] <= self.sharps:
377 name = name + Note.alteration_names[a + 2]
385 return '\n\n ' + s + '\n '
393 'SEQUENCE_TRACK_NAME',
399 def __init__ (self, type, text):
405 # urg, we should be sure that we're in a lyrics staff
406 if self.type == midi.LYRIC:
407 s = '"%s"' % self.text
408 d = Duration (self.clocks)
409 if global_options.explicit_durations \
410 or d.compare (reference_note.duration):
411 s = s + Duration (self.clocks).dump ()
414 s = '\n % [' + self.text_types[self.type] + '] ' + self.text + '\n '
418 return 'Text(%d=%s)' % (self.type, self.text)
422 def split_track (track):
429 if data[0] > 0x7f and data[0] < 0xf0:
431 e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
441 for v in chs.values ():
442 events = events_on_channel (v)
443 thread = unthread_notes (events)
445 threads.append (thread)
449 def quantise_clocks (clocks, quant):
450 q = int (clocks / quant) * quant
452 for tquant in allowed_tuplet_clocks:
453 if int (clocks / tquant) * tquant == clocks:
455 if 2 * (clocks - q) > quant:
459 def end_note (pitches, notes, t, e):
461 (lt, vel) = pitches[e]
471 if duration_quant_clocks:
472 d = quantise_clocks (d, duration_quant_clocks)
474 d = duration_quant_clocks
477 (lt, Note (d, e, vel)))
482 def events_on_channel (channel):
492 if start_quant_clocks:
493 t = quantise_clocks (t, start_quant_clocks)
496 if e[1][0] == midi.NOTE_OFF \
497 or (e[1][0] == midi.NOTE_ON and e[1][2] == 0):
498 end_note (pitches, notes, t, e[1][1])
500 elif e[1][0] == midi.NOTE_ON:
501 if not pitches.has_key (e[1][1]):
502 pitches[e[1][1]] = (t, e[1][2])
504 # all include ALL_NOTES_OFF
505 elif e[1][0] >= midi.ALL_SOUND_OFF \
506 and e[1][0] <= midi.POLY_MODE_ON:
507 for i in pitches.keys ():
508 end_note (pitches, notes, t, i)
510 elif e[1][0] == midi.META_EVENT:
511 if e[1][1] == midi.END_OF_TRACK:
512 for i in pitches.keys ():
513 end_note (pitches, notes, t, i)
516 elif e[1][1] == midi.SET_TEMPO:
517 (u0, u1, u2) = map (ord, e[1][2])
518 us_per_4 = u2 + 256 * (u1 + 256 * u0)
519 seconds_per_1 = us_per_4 * 4 / 1e6
520 events.append ((t, Tempo (seconds_per_1)))
521 elif e[1][1] == midi.TIME_SIGNATURE:
522 (num, dur, clocks4, count32) = map (ord, e[1][2])
524 events.append ((t, Time (num, den)))
525 elif e[1][1] == midi.KEY_SIGNATURE:
526 (alterations, minor) = map (ord, e[1][2])
529 if alterations < 127:
532 flats = 256 - alterations
534 k = Key (sharps, flats, minor)
535 events.append ((t, k))
537 # ugh, must set key while parsing
538 # because Note init uses key
539 # Better do Note.calc () at dump time?
540 global_options.key = k
542 elif e[1][1] == midi.LYRIC \
543 or (global_options.text_lyrics and e[1][1] == midi.TEXT_EVENT):
545 last_lyric.clocks = t - last_time
546 events.append ((last_time, last_lyric))
548 last_lyric = Text (midi.LYRIC, e[1][2])
550 elif e[1][1] >= midi.SEQUENCE_NUMBER \
551 and e[1][1] <= midi.CUE_POINT:
552 events.append ((t, Text (e[1][1], e[1][2])))
554 if global_options.verbose:
555 sys.stderr.write ("SKIP: %s\n" % `e`)
558 if global_options.verbose:
559 sys.stderr.write ("SKIP: %s\n" % `e`)
563 # last_lyric.clocks = t - last_time
565 last_lyric.clocks = clocks_per_4
566 events.append ((last_time, last_lyric))
571 if i < len (events) and notes[0][0] >= events[i][0]:
574 events.insert (i, notes[0])
578 def unthread_notes (channel):
587 if e[1].__class__ == Note \
588 and ((t == start_busy_t \
589 and e[1].clocks + t == end_busy_t) \
593 end_busy_t = t + e[1].clocks
594 elif e[1].__class__ == Time \
595 or e[1].__class__ == Key \
596 or e[1].__class__ == Text \
597 or e[1].__class__ == Tempo:
601 threads.append (thread)
616 def dump_skip (skip, clocks):
617 return skip + Duration (clocks).dump () + ' '
626 if i.__class__ == Note:
631 s = s + dump (notes[0])
632 elif len (notes) > 1:
633 global reference_note
635 s = s + notes[0].dump (dump_dur = 0)
638 s = s + i.dump (dump_dur = 0 )
641 s = s + notes[0].duration.dump() + ' '
645 def dump_bar_line (last_bar_t, t, bar_count):
647 bar_t = time.bar_clocks ()
648 if t - last_bar_t >= bar_t:
649 bar_count = bar_count + (t - last_bar_t) / bar_t
651 if t - last_bar_t == bar_t:
652 s = '|\n %% %d\n ' % bar_count
655 # urg, this will barf at meter changes
656 last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
658 return (s, last_bar_t, bar_count)
661 def dump_channel (thread, skip):
662 global reference_note, time
664 global_options.key = Key (0, 0, 0)
666 # urg LilyPond doesn't start at c4, but
667 # remembers from previous tracks!
668 # reference_note = Note (clocks_per_4, 4*12, 0)
669 reference_note = Note (0, 4*12, 0)
675 if last_e and last_e[0] == e[0]:
679 chs.append ((last_e[0], ch))
686 chs.append ((last_e[0], ch))
696 i = string.rfind (lines[-1], '\n') + 1
697 if len (lines[-1][i:]) > LINE_BELL:
701 lines[-1] = lines[-1] + dump_skip (skip, t-last_t)
703 errorport.write ('BUG: time skew')
705 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
707 lines[-1] = lines[-1] + s
709 lines[-1] = lines[-1] + dump_chord (ch[1])
713 if i.clocks > clocks:
718 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
720 lines[-1] = lines[-1] + s
722 return string.join (lines, '\n ') + '\n'
725 return 'track%c' % (i + ord ('A'))
727 def channel_name (i):
728 return 'channel%c' % (i + ord ('A'))
730 def dump_track (channels, n):
732 track = track_name (n)
733 clef = guess_clef (channels)
735 for i in range (len (channels)):
736 channel = channel_name (i)
737 item = thread_first_item (channels[i])
739 if item and item.__class__ == Note:
741 s = s + '%s = ' % (track + channel)
742 if not global_options.absolute_pitches:
743 s = s + '\\relative c '
744 elif item and item.__class__ == Text:
746 s = s + '%s = \\lyricmode ' % (track + channel)
749 s = s + '%s = ' % (track + channel)
751 s = s + ' ' + dump_channel (channels[i][0], skip)
754 s = s + '%s = <<\n' % track
757 s = s + clef.dump () + '\n'
759 for i in range (len (channels)):
760 channel = channel_name (i)
761 item = thread_first_item (channels[i])
762 if item and item.__class__ == Text:
763 s = s + ' \\context Lyrics = %s \\%s\n' % (channel,
766 s = s + ' \\context Voice = %s \\%s\n' % (channel,
771 def thread_first_item (thread):
774 if (event[1].__class__ == Note
775 or (event[1].__class__ == Text
776 and event[1].type == midi.LYRIC)):
781 def track_first_item (track):
783 first = thread_first_item (thread)
788 def guess_clef (track):
794 if event[1].__class__ == Note:
796 p = p + event[1].pitch
797 if i and p / i <= 3*12:
799 elif i and p / i <= 5*12:
801 elif i and p / i >= 7*12:
807 def convert_midi (in_file, out_file):
808 global clocks_per_1, clocks_per_4, key
809 global start_quant_clocks
810 global duration_quant_clocks
811 global allowed_tuplet_clocks
813 str = open (in_file).read ()
814 midi_dump = midi.parse (str)
816 clocks_per_1 = midi_dump[0][1]
817 clocks_per_4 = clocks_per_1 / 4
819 if global_options.start_quant:
820 start_quant_clocks = clocks_per_1 / global_options.start_quant
822 if global_options.duration_quant:
823 duration_quant_clocks = clocks_per_1 / global_options.duration_quant
825 allowed_tuplet_clocks = []
826 for (dur, num, den) in global_options.allowed_tuplets:
827 allowed_tuplet_clocks.append (clocks_per_1 / den)
830 for t in midi_dump[1]:
831 global_options.key = Key (0, 0, 0)
832 tracks.append (split_track (t))
834 tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, in_file)
838 s = tag + '\n\\version "2.7.18"\n\n'
839 for i in range (len (tracks)):
840 s = s + dump_track (tracks[i], i)
842 s = s + '\n\\score {\n <<\n'
846 track = track_name (i)
847 item = track_first_item (t)
849 if item and item.__class__ == Note:
850 s = s + ' \\context Staff=%s \\%s\n' % (track, track)
851 elif item and item.__class__ == Text:
852 s = s + ' \\context Lyrics=%s \\%s\n' % (track, track)
857 progress (_ ("%s output to `%s'...") % ('LY', out_file))
862 handle = open (out_file, 'w')
868 def get_option_parser ():
869 p = ly.get_option_parser (usage='midi2ly [OPTIONS] FILE',
870 version="midi2ly (LilyPond) @TOPLEVEL_VERSION@",
871 description=_('''Convert MIDI to LilyPond source.'''))
873 p.add_option ('-a', '--absolute-pitches',
875 help=_ ("print absolute pitches"))
876 p.add_option ('-d', '--duration-quant',
878 help=_("quantise note durations on DUR"))
879 p.add_option ('-e', '--explicit-durations',
881 help=_ ("print explicit durations"))
882 p.add_option('-k', '--key', help=_ ("set key: ALT=+sharps|-flats; MINOR=1"),
883 metavar=_ ("ALT[:MINOR]"),
885 p.add_option ('-o', '--output', help=_("write output to FILE"),
888 p.add_option ('-s', '--start-quant',help= _ ("quantise note starts on DUR"),
890 p.add_option ('-t', '--allow-tuplet',
891 metavar=_ ("DUR*NUM/DEN"),
893 dest="allowed_tuplets",
894 help=_ ("allow tuplet durations DUR*NUM/DEN"),
896 p.add_option ('-V', '--verbose', help=_("be verbose"),
899 p.add_option ('-w', '--warranty', help=_("show warranty"),
902 p.add_option ('-x', '--text-lyrics', help=_("treat every text as a lyric"),
905 p.add_option_group (_ ("example"),
907 midi2ly --key=-2:1 --duration-quant=32 \
908 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
911 p.add_option_group ('bugs',
912 description='''Report bugs via http://post.gmane.org/post.php'''
913 '''?group=gmane.comp.gnu.lilypond.bugs\n''')
920 opt_parser = get_option_parser()
921 (options, args) = opt_parser.parse_args ()
923 if not args or args[0] == '-':
924 opt_parser.print_help ()
925 sys.stderr.write ('\n%s: %s %s\n' % (program_name, _ ("error: "),
926 _ ("no files specified on command line.")))
929 if options.duration_quant:
930 options.duration_quant = int (options.duration_quant)
936 (alterations, minor) = map (int, string.split (options.key + ':0', ':'))[0:2]
942 flats = - alterations
944 options.key = Key (sharps, flats, minor)
947 if options.start_quant:
948 options.start_quant = int (options.start_quant)
950 options.allowed_tuplets = [map (int, a.replace ('/','*').split ('*'))
951 for a in options.allowed_tuplets]
953 global global_options
954 global_options = options
963 g = strip_extension (g, '.midi')
964 g = strip_extension (g, '.mid')
965 g = strip_extension (g, '.MID')
966 (outdir, outbase) = ('','')
970 outbase = os.path.basename (g)
971 o = os.path.join (outdir, outbase + '-midi.ly')
972 elif output_name[-1] == os.sep:
974 outbase = os.path.basename (g)
975 os.path.join (outdir, outbase + '-gen.ly')
978 (outdir, outbase) = os.path.split (o)
980 if outdir != '.' and outdir != '':
982 os.mkdir (outdir, 0777)
987 if __name__ == '__main__':