3 # msdi2ly.py -- LilyPond midi import script
5 # source file of the GNU LilyPond music typesetter
7 # (c) 1998--2007 Han-Wen Nienhuys <hanwen@xs4all.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
35 ################################################################
41 scale_steps = [0,2,4,5,7,9,11]
50 start_quant_clocks = 0
52 duration_quant_clocks = 0
53 allowed_tuplet_clocks = []
56 ################################################################
58 localedir = '@localedir@'
61 gettext.bindtextdomain ('lilypond', localedir)
62 gettext.textdomain ('lilypond')
68 program_name = sys.argv[0]
69 program_version = '@TOPLEVEL_VERSION@'
71 errorport = sys.stderr
74 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
87 _('Distributed under terms of the GNU General Public License.'),
88 _('It comes with NO WARRANTY.')))
92 errorport.write (s + '\n')
95 progress (_ ("warning: ") + s)
98 progress (_ ("error: ") + s)
99 raise _ ("Exiting ... ")
101 def system (cmd, ignore_error = 0):
102 return ly.system (cmd, ignore_error=ignore_error)
104 def strip_extension (f, ext):
105 (p, e) = os.path.splitext (f)
114 allowed_durs = (1, 2, 4, 8, 16, 32, 64, 128)
115 def __init__ (self, clocks):
118 self.clocks = duration_quant_clocks
119 (self.dur, self.num, self.den) = self.dur_num_den (clocks)
121 def dur_num_den (self, clocks):
122 for i in range (len (allowed_tuplet_clocks)):
123 if clocks == allowed_tuplet_clocks[i]:
124 return global_options.allowed_tuplets[i]
126 dur = 0; num = 1; den = 1;
127 g = gcd (clocks, clocks_per_1)
129 (dur, num) = (clocks_per_1 / g, clocks / g)
130 if not dur in self.allowed_durs:
131 dur = 4; num = clocks; den = clocks_per_4
132 return (dur, num, den)
138 elif self.num == 3 and self.dur != 1:
139 s = '%d.' % (self.dur / 2)
141 s = '%d*%d' % (self.dur, self.num)
143 s = '%d*%d/%d' % (self.dur, self.num, self.den)
145 global reference_note
146 reference_note.duration = self
150 def compare (self, other):
151 return self.clocks - other.clocks
160 names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
161 alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
162 alteration_names = ('eses', 'es', '', 'is' , 'isis')
163 def __init__ (self, clocks, pitch, velocity):
165 self.velocity = velocity
168 self.duration = Duration (clocks)
169 (self.octave, self.notename, self.alteration) = self.o_n_a ()
173 # minor scale: la-la (= + 5) '''
175 n = self.names[(self.pitch) % 12]
176 a = self.alterations[(self.pitch) % 12]
178 if a and global_options.key.flats:
179 a = - self.alterations[(self.pitch) % 12]
182 # By tradition, all scales now consist of a sequence
183 # of 7 notes each with a distinct name, from amongst
184 # a b c d e f g. But, minor scales have a wide
185 # second interval at the top - the 'leading note' is
186 # sharped. (Why? it just works that way! Anything
187 # else doesn't sound as good and isn't as flexible at
188 # saying things. In medieval times, scales only had 6
189 # notes to avoid this problem - the hexachords.)
191 # So, the d minor scale is d e f g a b-flat c-sharp d
192 # - using d-flat for the leading note would skip the
193 # name c and duplicate the name d. Why isn't c-sharp
194 # put in the key signature? Tradition. (It's also
195 # supposedly based on the Pythagorean theory of the
196 # cycle of fifths, but that really only applies to
197 # major scales...) Anyway, g minor is g a b-flat c d
198 # e-flat f-sharp g, and all the other flat minor keys
199 # end up with a natural leading note. And there you
202 # John Sankey <bf250@freenet.carleton.ca>
204 # Let's also do a-minor: a b c d e f gis a
208 o = self.pitch / 12 - 4
210 key = global_options.key
213 if (key.sharps == 0 and key.flats == 0
214 and n == 5 and a == -1):
217 elif key.flats == 1 and n == 1 and a == -1:
220 elif key.flats == 2 and n == 4 and a == -1:
223 elif key.sharps == 5 and n == 4 and a == 0:
226 elif key.sharps == 6 and n == 1 and a == 0:
229 elif key.sharps == 7 and n == 5 and a == 0:
233 if key.flats >= 6 and n == 6 and a == 0:
234 n = 0; a = -1; o = o + 1
236 if key.flats >= 7 and n == 2 and a == 0:
240 if key.sharps >= 3 and n == 3 and a == 0:
243 if key.sharps >= 4 and n == 0 and a == 0:
244 n = 6; a = 1; o = o - 1
249 s = chr ((self.notename + 2) % 7 + ord ('a'))
250 return 'Note(%s %s)' % (s, self.duration.dump())
252 def dump (self, dump_dur = 1):
253 global reference_note
254 s = chr ((self.notename + 2) % 7 + ord ('a'))
255 s = s + self.alteration_names[self.alteration + 2]
256 if global_options.absolute_pitches:
259 delta = self.pitch - reference_note.pitch
260 commas = sign (delta) * (abs (delta) / 12)
262 * (self.notename - reference_note.notename) + 7) \
264 or ((self.notename == reference_note.notename) \
265 and (abs (delta) > 4) and (abs (delta) < 12)):
266 commas = commas + sign (delta)
271 s = s + "," * -commas
273 ## FIXME: compile fix --jcn
274 if dump_dur and (global_options.explicit_durations \
275 or self.duration.compare (reference_note.duration)):
276 s = s + self.duration.dump ()
278 reference_note = self
285 def __init__ (self, num, den):
290 def bar_clocks (self):
291 return clocks_per_1 * self.num / self.den
294 return 'Time(%d/%d)' % (self.num, self.den)
299 return '\n ' + '\\time %d/%d ' % (self.num, self.den) + '\n '
302 def __init__ (self, seconds_per_1):
304 self.seconds_per_1 = seconds_per_1
307 return 'Tempo(%d)' % self.bpm ()
310 return 4 * 60 / self.seconds_per_1
313 return '\n ' + '\\tempo 4 = %d ' % (self.bpm()) + '\n '
316 clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
317 def __init__ (self, type):
321 return 'Clef(%s)' % self.clefs[self.type]
324 return '\n \\clef %s\n ' % self.clefs[self.type]
327 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
328 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
330 def __init__ (self, sharps, flats, minor):
337 global_options.key = self
340 if self.sharps and self.flats:
344 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
346 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
349 name = chr ((k + 2) % 7 + ord ('a'))
351 name = chr ((k + 2) % 7 + ord ('a'))
353 # fis cis gis dis ais eis bis
354 sharps = (2, 4, 6, 1, 3, 5, 7)
355 # bes es as des ges ces fes
356 flats = (6, 4, 2, 7, 5, 3, 1)
359 if flats[k] <= self.flats:
362 if sharps[k] <= self.sharps:
366 name = name + Note.alteration_names[a + 2]
374 return '\n\n ' + s + '\n '
382 'SEQUENCE_TRACK_NAME',
388 def __init__ (self, type, text):
394 # urg, we should be sure that we're in a lyrics staff
395 if self.type == midi.LYRIC:
396 s = '"%s"' % self.text
397 d = Duration (self.clocks)
398 if global_options.explicit_durations \
399 or d.compare (reference_note.duration):
400 s = s + Duration (self.clocks).dump ()
403 s = '\n % [' + self.text_types[self.type] + '] ' + self.text + '\n '
407 return 'Text(%d=%s)' % (self.type, self.text)
411 def split_track (track):
418 if data[0] > 0x7f and data[0] < 0xf0:
420 e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
430 for v in chs.values ():
431 events = events_on_channel (v)
432 thread = unthread_notes (events)
434 threads.append (thread)
438 def quantise_clocks (clocks, quant):
439 q = int (clocks / quant) * quant
441 for tquant in allowed_tuplet_clocks:
442 if int (clocks / tquant) * tquant == clocks:
444 if 2 * (clocks - q) > quant:
448 def end_note (pitches, notes, t, e):
450 (lt, vel) = pitches[e]
460 if duration_quant_clocks:
461 d = quantise_clocks (d, duration_quant_clocks)
463 d = duration_quant_clocks
466 (lt, Note (d, e, vel)))
471 def events_on_channel (channel):
481 if start_quant_clocks:
482 t = quantise_clocks (t, start_quant_clocks)
485 if e[1][0] == midi.NOTE_OFF \
486 or (e[1][0] == midi.NOTE_ON and e[1][2] == 0):
487 end_note (pitches, notes, t, e[1][1])
489 elif e[1][0] == midi.NOTE_ON:
490 if not pitches.has_key (e[1][1]):
491 pitches[e[1][1]] = (t, e[1][2])
493 # all include ALL_NOTES_OFF
494 elif e[1][0] >= midi.ALL_SOUND_OFF \
495 and e[1][0] <= midi.POLY_MODE_ON:
496 for i in pitches.keys ():
497 end_note (pitches, notes, t, i)
499 elif e[1][0] == midi.META_EVENT:
500 if e[1][1] == midi.END_OF_TRACK:
501 for i in pitches.keys ():
502 end_note (pitches, notes, t, i)
505 elif e[1][1] == midi.SET_TEMPO:
506 (u0, u1, u2) = map (ord, e[1][2])
507 us_per_4 = u2 + 256 * (u1 + 256 * u0)
508 seconds_per_1 = us_per_4 * 4 / 1e6
509 events.append ((t, Tempo (seconds_per_1)))
510 elif e[1][1] == midi.TIME_SIGNATURE:
511 (num, dur, clocks4, count32) = map (ord, e[1][2])
513 events.append ((t, Time (num, den)))
514 elif e[1][1] == midi.KEY_SIGNATURE:
515 (alterations, minor) = map (ord, e[1][2])
518 if alterations < 127:
521 flats = 256 - alterations
523 k = Key (sharps, flats, minor)
524 events.append ((t, k))
526 # ugh, must set key while parsing
527 # because Note init uses key
528 # Better do Note.calc () at dump time?
529 global_options.key = k
531 elif e[1][1] == midi.LYRIC \
532 or (global_options.text_lyrics and e[1][1] == midi.TEXT_EVENT):
534 last_lyric.clocks = t - last_time
535 events.append ((last_time, last_lyric))
537 last_lyric = Text (midi.LYRIC, e[1][2])
539 elif e[1][1] >= midi.SEQUENCE_NUMBER \
540 and e[1][1] <= midi.CUE_POINT:
541 events.append ((t, Text (e[1][1], e[1][2])))
543 if global_options.verbose:
544 sys.stderr.write ("SKIP: %s\n" % `e`)
547 if global_options.verbose:
548 sys.stderr.write ("SKIP: %s\n" % `e`)
552 # last_lyric.clocks = t - last_time
554 last_lyric.clocks = clocks_per_4
555 events.append ((last_time, last_lyric))
560 if i < len (events) and notes[0][0] >= events[i][0]:
563 events.insert (i, notes[0])
567 def unthread_notes (channel):
576 if e[1].__class__ == Note \
577 and ((t == start_busy_t \
578 and e[1].clocks + t == end_busy_t) \
582 end_busy_t = t + e[1].clocks
583 elif e[1].__class__ == Time \
584 or e[1].__class__ == Key \
585 or e[1].__class__ == Text \
586 or e[1].__class__ == Tempo:
590 threads.append (thread)
605 def dump_skip (skip, clocks):
606 return skip + Duration (clocks).dump () + ' '
615 if i.__class__ == Note:
620 s = s + dump (notes[0])
621 elif len (notes) > 1:
622 global reference_note
624 s = s + notes[0].dump (dump_dur = 0)
627 s = s + i.dump (dump_dur = 0 )
630 s = s + notes[0].duration.dump() + ' '
634 def dump_bar_line (last_bar_t, t, bar_count):
636 bar_t = time.bar_clocks ()
637 if t - last_bar_t >= bar_t:
638 bar_count = bar_count + (t - last_bar_t) / bar_t
640 if t - last_bar_t == bar_t:
641 s = '|\n %% %d\n ' % bar_count
644 # urg, this will barf at meter changes
645 last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
647 return (s, last_bar_t, bar_count)
650 def dump_channel (thread, skip):
651 global reference_note, time
653 global_options.key = Key (0, 0, 0)
655 # urg LilyPond doesn't start at c4, but
656 # remembers from previous tracks!
657 # reference_note = Note (clocks_per_4, 4*12, 0)
658 reference_note = Note (0, 4*12, 0)
664 if last_e and last_e[0] == e[0]:
668 chs.append ((last_e[0], ch))
675 chs.append ((last_e[0], ch))
685 i = string.rfind (lines[-1], '\n') + 1
686 if len (lines[-1][i:]) > LINE_BELL:
690 lines[-1] = lines[-1] + dump_skip (skip, t-last_t)
692 errorport.write ('BUG: time skew')
694 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
696 lines[-1] = lines[-1] + s
698 lines[-1] = lines[-1] + dump_chord (ch[1])
702 if i.clocks > clocks:
707 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
709 lines[-1] = lines[-1] + s
711 return string.join (lines, '\n ') + '\n'
714 return 'track%c' % (i + ord ('A'))
716 def channel_name (i):
717 return 'channel%c' % (i + ord ('A'))
719 def dump_track (channels, n):
721 track = track_name (n)
722 clef = guess_clef (channels)
724 for i in range (len (channels)):
725 channel = channel_name (i)
726 item = thread_first_item (channels[i])
728 if item and item.__class__ == Note:
730 s = s + '%s = ' % (track + channel)
731 if not global_options.absolute_pitches:
732 s = s + '\\relative c '
733 elif item and item.__class__ == Text:
735 s = s + '%s = \\lyricmode ' % (track + channel)
738 s = s + '%s = ' % (track + channel)
740 s = s + ' ' + dump_channel (channels[i][0], skip)
743 s = s + '%s = <<\n' % track
746 s = s + clef.dump () + '\n'
748 for i in range (len (channels)):
749 channel = channel_name (i)
750 item = thread_first_item (channels[i])
751 if item and item.__class__ == Text:
752 s = s + ' \\context Lyrics = %s \\%s\n' % (channel,
755 s = s + ' \\context Voice = %s \\%s\n' % (channel,
760 def thread_first_item (thread):
763 if (event[1].__class__ == Note
764 or (event[1].__class__ == Text
765 and event[1].type == midi.LYRIC)):
770 def track_first_item (track):
772 first = thread_first_item (thread)
777 def guess_clef (track):
783 if event[1].__class__ == Note:
785 p = p + event[1].pitch
786 if i and p / i <= 3*12:
788 elif i and p / i <= 5*12:
790 elif i and p / i >= 7*12:
796 def convert_midi (in_file, out_file):
797 global clocks_per_1, clocks_per_4, key
798 global start_quant_clocks
799 global duration_quant_clocks
800 global allowed_tuplet_clocks
802 str = open (in_file).read ()
803 midi_dump = midi.parse (str)
805 clocks_per_1 = midi_dump[0][1]
806 clocks_per_4 = clocks_per_1 / 4
808 if global_options.start_quant:
809 start_quant_clocks = clocks_per_1 / global_options.start_quant
811 if global_options.duration_quant:
812 duration_quant_clocks = clocks_per_1 / global_options.duration_quant
814 allowed_tuplet_clocks = []
815 for (dur, num, den) in global_options.allowed_tuplets:
816 allowed_tuplet_clocks.append (clocks_per_1 / den)
819 for t in midi_dump[1]:
820 global_options.key = Key (0, 0, 0)
821 tracks.append (split_track (t))
823 tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, in_file)
827 s = tag + '\n\\version "2.7.18"\n\n'
828 for i in range (len (tracks)):
829 s = s + dump_track (tracks[i], i)
831 s = s + '\n\\score {\n <<\n'
835 track = track_name (i)
836 item = track_first_item (t)
838 if item and item.__class__ == Note:
839 s = s + ' \\context Staff=%s \\%s\n' % (track, track)
840 elif item and item.__class__ == Text:
841 s = s + ' \\context Lyrics=%s \\%s\n' % (track, track)
846 progress (_ ("%s output to `%s'...") % ('LY', out_file))
851 handle = open (out_file, 'w')
857 def get_option_parser ():
858 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'midi2ly',
859 version="midi2ly (LilyPond) @TOPLEVEL_VERSION@",
860 description=_ ("Convert %s to LilyPond input.") % 'MIDI')
862 p.add_option ('-a', '--absolute-pitches',
864 help=_ ("print absolute pitches"))
865 p.add_option ('-d', '--duration-quant',
867 help=_ ("quantise note durations on DUR"))
868 p.add_option ('-e', '--explicit-durations',
870 help=_ ("print explicit durations"))
871 p.add_option('-k', '--key', help=_ ("set key: ALT=+sharps|-flats; MINOR=1"),
872 metavar=_ ("ALT[:MINOR]"),
874 p.add_option ('-o', '--output', help=_ ("write output to FILE"),
877 p.add_option ('-s', '--start-quant',help= _ ("quantise note starts on DUR"),
879 p.add_option ('-t', '--allow-tuplet',
880 metavar=_ ("DUR*NUM/DEN"),
882 dest="allowed_tuplets",
883 help=_ ("allow tuplet durations DUR*NUM/DEN"),
885 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
888 p.add_option ('-w', '--warranty', help=_ ("show warranty and copyright"),
891 p.add_option ('-x', '--text-lyrics', help=_ ("treat every text as a lyric"),
894 p.add_option_group (_ ("Examples"),
896 midi2ly --key=-2:1 --duration-quant=32 \
897 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
899 p.add_option_group ('bugs',
900 description=(_ ('Report bugs via')
901 + ''' http://post.gmane.org/post.php'''
902 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
908 opt_parser = get_option_parser()
909 (options, args) = opt_parser.parse_args ()
911 if not args or args[0] == '-':
912 opt_parser.print_help ()
913 sys.stderr.write ('\n%s: %s %s\n' % (program_name, _ ("error: "),
914 _ ("no files specified on command line.")))
917 if options.duration_quant:
918 options.duration_quant = int (options.duration_quant)
924 (alterations, minor) = map (int, string.split (options.key + ':0', ':'))[0:2]
930 flats = - alterations
932 options.key = Key (sharps, flats, minor)
935 if options.start_quant:
936 options.start_quant = int (options.start_quant)
938 options.allowed_tuplets = [map (int, a.replace ('/','*').split ('*'))
939 for a in options.allowed_tuplets]
941 global global_options
942 global_options = options
951 g = strip_extension (g, '.midi')
952 g = strip_extension (g, '.mid')
953 g = strip_extension (g, '.MID')
954 (outdir, outbase) = ('','')
958 outbase = os.path.basename (g)
959 o = os.path.join (outdir, outbase + '-midi.ly')
960 elif output_name[-1] == os.sep:
962 outbase = os.path.basename (g)
963 os.path.join (outdir, outbase + '-gen.ly')
966 (outdir, outbase) = os.path.split (o)
968 if outdir != '.' and outdir != '':
970 os.mkdir (outdir, 0777)
975 if __name__ == '__main__':