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
36 ################################################################
42 scale_steps = [0,2,4,5,7,9,11]
51 start_quant_clocks = 0
53 duration_quant_clocks = 0
54 allowed_tuplet_clocks = []
57 ################################################################
60 program_name = sys.argv[0]
61 program_version = '@TOPLEVEL_VERSION@'
63 errorport = sys.stderr
66 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
70 ly.encoded_write (sys.stdout, '''
79 _('Distributed under terms of the GNU General Public License.'),
80 _('It comes with NO WARRANTY.')))
84 ly.encoded_write (errorport, s + '\n')
87 progress (_ ("warning: ") + s)
90 progress (_ ("error: ") + s)
91 raise _ ("Exiting... ")
93 def system (cmd, ignore_error = 0):
94 return ly.system (cmd, ignore_error=ignore_error)
96 def strip_extension (f, ext):
97 (p, e) = os.path.splitext (f)
105 allowed_durs = (1, 2, 4, 8, 16, 32, 64, 128)
106 def __init__ (self, clocks):
109 self.clocks = duration_quant_clocks
110 (self.dur, self.num, self.den) = self.dur_num_den (clocks)
112 def dur_num_den (self, clocks):
113 for i in range (len (allowed_tuplet_clocks)):
114 if clocks == allowed_tuplet_clocks[i]:
115 return global_options.allowed_tuplets[i]
117 dur = 0; num = 1; den = 1;
118 g = gcd (clocks, clocks_per_1)
120 (dur, num) = (clocks_per_1 / g, clocks / g)
121 if not dur in self.allowed_durs:
122 dur = 4; num = clocks; den = clocks_per_4
123 return (dur, num, den)
129 elif self.num == 3 and self.dur != 1:
130 s = '%d.' % (self.dur / 2)
132 s = '%d*%d' % (self.dur, self.num)
134 s = '%d*%d/%d' % (self.dur, self.num, self.den)
136 global reference_note
137 reference_note.duration = self
141 def compare (self, other):
142 return self.clocks - other.clocks
151 names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
152 alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
153 alteration_names = ('eses', 'es', '', 'is' , 'isis')
154 def __init__ (self, clocks, pitch, velocity):
156 self.velocity = velocity
159 self.duration = Duration (clocks)
160 (self.octave, self.notename, self.alteration) = self.o_n_a ()
164 # minor scale: la-la (= + 5) '''
166 n = self.names[(self.pitch) % 12]
167 a = self.alterations[(self.pitch) % 12]
169 if a and global_options.key.flats:
170 a = - self.alterations[(self.pitch) % 12]
173 # By tradition, all scales now consist of a sequence
174 # of 7 notes each with a distinct name, from amongst
175 # a b c d e f g. But, minor scales have a wide
176 # second interval at the top - the 'leading note' is
177 # sharped. (Why? it just works that way! Anything
178 # else doesn't sound as good and isn't as flexible at
179 # saying things. In medieval times, scales only had 6
180 # notes to avoid this problem - the hexachords.)
182 # So, the d minor scale is d e f g a b-flat c-sharp d
183 # - using d-flat for the leading note would skip the
184 # name c and duplicate the name d. Why isn't c-sharp
185 # put in the key signature? Tradition. (It's also
186 # supposedly based on the Pythagorean theory of the
187 # cycle of fifths, but that really only applies to
188 # major scales...) Anyway, g minor is g a b-flat c d
189 # e-flat f-sharp g, and all the other flat minor keys
190 # end up with a natural leading note. And there you
193 # John Sankey <bf250@freenet.carleton.ca>
195 # Let's also do a-minor: a b c d e f gis a
199 o = self.pitch / 12 - 4
201 key = global_options.key
204 if (key.sharps == 0 and key.flats == 0
205 and n == 5 and a == -1):
208 elif key.flats == 1 and n == 1 and a == -1:
211 elif key.flats == 2 and n == 4 and a == -1:
214 elif key.sharps == 5 and n == 4 and a == 0:
217 elif key.sharps == 6 and n == 1 and a == 0:
220 elif key.sharps == 7 and n == 5 and a == 0:
224 if key.flats >= 6 and n == 6 and a == 0:
225 n = 0; a = -1; o = o + 1
227 if key.flats >= 7 and n == 2 and a == 0:
231 if key.sharps >= 3 and n == 3 and a == 0:
234 if key.sharps >= 4 and n == 0 and a == 0:
235 n = 6; a = 1; o = o - 1
240 s = chr ((self.notename + 2) % 7 + ord ('a'))
241 return 'Note(%s %s)' % (s, self.duration.dump())
243 def dump (self, dump_dur = 1):
244 global reference_note
245 s = chr ((self.notename + 2) % 7 + ord ('a'))
246 s = s + self.alteration_names[self.alteration + 2]
247 if global_options.absolute_pitches:
250 delta = self.pitch - reference_note.pitch
251 commas = sign (delta) * (abs (delta) / 12)
253 * (self.notename - reference_note.notename) + 7) \
255 or ((self.notename == reference_note.notename) \
256 and (abs (delta) > 4) and (abs (delta) < 12)):
257 commas = commas + sign (delta)
262 s = s + "," * -commas
264 ## FIXME: compile fix --jcn
265 if dump_dur and (global_options.explicit_durations \
266 or self.duration.compare (reference_note.duration)):
267 s = s + self.duration.dump ()
269 reference_note = self
276 def __init__ (self, num, den):
281 def bar_clocks (self):
282 return clocks_per_1 * self.num / self.den
285 return 'Time(%d/%d)' % (self.num, self.den)
290 return '\n ' + '\\time %d/%d ' % (self.num, self.den) + '\n '
293 def __init__ (self, seconds_per_1):
295 self.seconds_per_1 = seconds_per_1
298 return 'Tempo(%d)' % self.bpm ()
301 return 4 * 60 / self.seconds_per_1
304 return '\n ' + '\\tempo 4 = %d ' % (self.bpm()) + '\n '
307 clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
308 def __init__ (self, type):
312 return 'Clef(%s)' % self.clefs[self.type]
315 return '\n \\clef %s\n ' % self.clefs[self.type]
318 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
319 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
321 def __init__ (self, sharps, flats, minor):
328 global_options.key = self
331 if self.sharps and self.flats:
335 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
337 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
340 name = chr ((k + 2) % 7 + ord ('a'))
342 name = chr ((k + 2) % 7 + ord ('a'))
344 # fis cis gis dis ais eis bis
345 sharps = (2, 4, 6, 1, 3, 5, 7)
346 # bes es as des ges ces fes
347 flats = (6, 4, 2, 7, 5, 3, 1)
350 if flats[k] <= self.flats:
353 if sharps[k] <= self.sharps:
357 name = name + Note.alteration_names[a + 2]
365 return '\n\n ' + s + '\n '
373 'SEQUENCE_TRACK_NAME',
379 def __init__ (self, type, text):
385 # urg, we should be sure that we're in a lyrics staff
386 if self.type == midi.LYRIC:
387 s = '"%s"' % self.text
388 d = Duration (self.clocks)
389 if global_options.explicit_durations \
390 or d.compare (reference_note.duration):
391 s = s + Duration (self.clocks).dump ()
394 s = '\n % [' + self.text_types[self.type] + '] ' + self.text + '\n '
398 return 'Text(%d=%s)' % (self.type, self.text)
402 def split_track (track):
409 if data[0] > 0x7f and data[0] < 0xf0:
411 e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
421 for v in chs.values ():
422 events = events_on_channel (v)
423 thread = unthread_notes (events)
425 threads.append (thread)
429 def quantise_clocks (clocks, quant):
430 q = int (clocks / quant) * quant
432 for tquant in allowed_tuplet_clocks:
433 if int (clocks / tquant) * tquant == clocks:
435 if 2 * (clocks - q) > quant:
439 def end_note (pitches, notes, t, e):
441 (lt, vel) = pitches[e]
451 if duration_quant_clocks:
452 d = quantise_clocks (d, duration_quant_clocks)
454 d = duration_quant_clocks
457 (lt, Note (d, e, vel)))
462 def events_on_channel (channel):
472 if start_quant_clocks:
473 t = quantise_clocks (t, start_quant_clocks)
476 if e[1][0] == midi.NOTE_OFF \
477 or (e[1][0] == midi.NOTE_ON and e[1][2] == 0):
478 end_note (pitches, notes, t, e[1][1])
480 elif e[1][0] == midi.NOTE_ON:
481 if not pitches.has_key (e[1][1]):
482 pitches[e[1][1]] = (t, e[1][2])
484 # all include ALL_NOTES_OFF
485 elif e[1][0] >= midi.ALL_SOUND_OFF \
486 and e[1][0] <= midi.POLY_MODE_ON:
487 for i in pitches.keys ():
488 end_note (pitches, notes, t, i)
490 elif e[1][0] == midi.META_EVENT:
491 if e[1][1] == midi.END_OF_TRACK:
492 for i in pitches.keys ():
493 end_note (pitches, notes, t, i)
496 elif e[1][1] == midi.SET_TEMPO:
497 (u0, u1, u2) = map (ord, e[1][2])
498 us_per_4 = u2 + 256 * (u1 + 256 * u0)
499 seconds_per_1 = us_per_4 * 4 / 1e6
500 events.append ((t, Tempo (seconds_per_1)))
501 elif e[1][1] == midi.TIME_SIGNATURE:
502 (num, dur, clocks4, count32) = map (ord, e[1][2])
504 events.append ((t, Time (num, den)))
505 elif e[1][1] == midi.KEY_SIGNATURE:
506 (alterations, minor) = map (ord, e[1][2])
509 if alterations < 127:
512 flats = 256 - alterations
514 k = Key (sharps, flats, minor)
515 events.append ((t, k))
517 # ugh, must set key while parsing
518 # because Note init uses key
519 # Better do Note.calc () at dump time?
520 global_options.key = k
522 elif e[1][1] == midi.LYRIC \
523 or (global_options.text_lyrics and e[1][1] == midi.TEXT_EVENT):
525 last_lyric.clocks = t - last_time
526 events.append ((last_time, last_lyric))
528 last_lyric = Text (midi.LYRIC, e[1][2])
530 elif e[1][1] >= midi.SEQUENCE_NUMBER \
531 and e[1][1] <= midi.CUE_POINT:
532 events.append ((t, Text (e[1][1], e[1][2])))
534 if global_options.verbose:
535 sys.stderr.write ("SKIP: %s\n" % `e`)
538 if global_options.verbose:
539 sys.stderr.write ("SKIP: %s\n" % `e`)
543 # last_lyric.clocks = t - last_time
545 last_lyric.clocks = clocks_per_4
546 events.append ((last_time, last_lyric))
551 if i < len (events) and notes[0][0] >= events[i][0]:
554 events.insert (i, notes[0])
558 def unthread_notes (channel):
567 if e[1].__class__ == Note \
568 and ((t == start_busy_t \
569 and e[1].clocks + t == end_busy_t) \
573 end_busy_t = t + e[1].clocks
574 elif e[1].__class__ == Time \
575 or e[1].__class__ == Key \
576 or e[1].__class__ == Text \
577 or e[1].__class__ == Tempo:
581 threads.append (thread)
596 def dump_skip (skip, clocks):
597 return skip + Duration (clocks).dump () + ' '
606 if i.__class__ == Note:
611 s = s + dump (notes[0])
612 elif len (notes) > 1:
613 global reference_note
615 s = s + notes[0].dump (dump_dur = 0)
618 s = s + i.dump (dump_dur = 0 )
621 s = s + notes[0].duration.dump() + ' '
625 def dump_bar_line (last_bar_t, t, bar_count):
627 bar_t = time.bar_clocks ()
628 if t - last_bar_t >= bar_t:
629 bar_count = bar_count + (t - last_bar_t) / bar_t
631 if t - last_bar_t == bar_t:
632 s = '|\n %% %d\n ' % bar_count
635 # urg, this will barf at meter changes
636 last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
638 return (s, last_bar_t, bar_count)
641 def dump_channel (thread, skip):
642 global reference_note, time
644 global_options.key = Key (0, 0, 0)
646 # urg LilyPond doesn't start at c4, but
647 # remembers from previous tracks!
648 # reference_note = Note (clocks_per_4, 4*12, 0)
649 reference_note = Note (0, 4*12, 0)
655 if last_e and last_e[0] == e[0]:
659 chs.append ((last_e[0], ch))
666 chs.append ((last_e[0], ch))
676 i = string.rfind (lines[-1], '\n') + 1
677 if len (lines[-1][i:]) > LINE_BELL:
681 lines[-1] = lines[-1] + dump_skip (skip, t-last_t)
683 errorport.write ('BUG: time skew')
685 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
687 lines[-1] = lines[-1] + s
689 lines[-1] = lines[-1] + dump_chord (ch[1])
693 if i.clocks > clocks:
698 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
700 lines[-1] = lines[-1] + s
702 return string.join (lines, '\n ') + '\n'
705 return 'track%c' % (i + ord ('A'))
707 def channel_name (i):
708 return 'channel%c' % (i + ord ('A'))
710 def dump_track (channels, n):
712 track = track_name (n)
713 clef = guess_clef (channels)
715 for i in range (len (channels)):
716 channel = channel_name (i)
717 item = thread_first_item (channels[i])
719 if item and item.__class__ == Note:
721 s = s + '%s = ' % (track + channel)
722 if not global_options.absolute_pitches:
723 s = s + '\\relative c '
724 elif item and item.__class__ == Text:
726 s = s + '%s = \\lyricmode ' % (track + channel)
729 s = s + '%s = ' % (track + channel)
731 s = s + ' ' + dump_channel (channels[i][0], skip)
734 s = s + '%s = <<\n' % track
737 s = s + clef.dump () + '\n'
739 for i in range (len (channels)):
740 channel = channel_name (i)
741 item = thread_first_item (channels[i])
742 if item and item.__class__ == Text:
743 s = s + ' \\context Lyrics = %s \\%s\n' % (channel,
746 s = s + ' \\context Voice = %s \\%s\n' % (channel,
751 def thread_first_item (thread):
754 if (event[1].__class__ == Note
755 or (event[1].__class__ == Text
756 and event[1].type == midi.LYRIC)):
761 def track_first_item (track):
763 first = thread_first_item (thread)
768 def guess_clef (track):
774 if event[1].__class__ == Note:
776 p = p + event[1].pitch
777 if i and p / i <= 3*12:
779 elif i and p / i <= 5*12:
781 elif i and p / i >= 7*12:
787 def convert_midi (in_file, out_file):
788 global clocks_per_1, clocks_per_4, key
789 global start_quant_clocks
790 global duration_quant_clocks
791 global allowed_tuplet_clocks
793 str = open (in_file).read ()
794 midi_dump = midi.parse (str)
796 clocks_per_1 = midi_dump[0][1]
797 clocks_per_4 = clocks_per_1 / 4
799 if global_options.start_quant:
800 start_quant_clocks = clocks_per_1 / global_options.start_quant
802 if global_options.duration_quant:
803 duration_quant_clocks = clocks_per_1 / global_options.duration_quant
805 allowed_tuplet_clocks = []
806 for (dur, num, den) in global_options.allowed_tuplets:
807 allowed_tuplet_clocks.append (clocks_per_1 / den)
810 for t in midi_dump[1]:
811 global_options.key = Key (0, 0, 0)
812 tracks.append (split_track (t))
814 tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, in_file)
818 s = tag + '\n\\version "2.7.18"\n\n'
819 for i in range (len (tracks)):
820 s = s + dump_track (tracks[i], i)
822 s = s + '\n\\score {\n <<\n'
826 track = track_name (i)
827 item = track_first_item (t)
829 if item and item.__class__ == Note:
830 s = s + ' \\context Staff=%s \\%s\n' % (track, track)
831 elif item and item.__class__ == Text:
832 s = s + ' \\context Lyrics=%s \\%s\n' % (track, track)
837 progress (_ ("%s output to `%s'...") % ('LY', out_file))
842 handle = open (out_file, 'w')
848 def get_option_parser ():
849 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'midi2ly',
850 version="midi2ly (LilyPond) @TOPLEVEL_VERSION@",
851 description=_ ("Convert %s to LilyPond input.") % 'MIDI')
853 p.add_option ('-a', '--absolute-pitches',
855 help=_ ("print absolute pitches"))
856 p.add_option ('-d', '--duration-quant',
858 help=_ ("quantise note durations on DUR"))
859 p.add_option ('-e', '--explicit-durations',
861 help=_ ("print explicit durations"))
862 p.add_option('-k', '--key', help=_ ("set key: ALT=+sharps|-flats; MINOR=1"),
863 metavar=_ ("ALT[:MINOR]"),
865 p.add_option ('-o', '--output', help=_ ("write output to FILE"),
868 p.add_option ('-s', '--start-quant',help= _ ("quantise note starts on DUR"),
870 p.add_option ('-t', '--allow-tuplet',
871 metavar=_ ("DUR*NUM/DEN"),
873 dest="allowed_tuplets",
874 help=_ ("allow tuplet durations DUR*NUM/DEN"),
876 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
879 p.add_option ('-w', '--warranty', help=_ ("show warranty and copyright"),
882 p.add_option ('-x', '--text-lyrics', help=_ ("treat every text as a lyric"),
885 # urg, Python 2.5 optparse is broken, it doesn't accept Unicode strings
886 p.add_option_group (_ ("Examples").encode (sys.stdout.encoding),
888 midi2ly --key=-2:1 --duration-quant=32 \
889 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
891 p.add_option_group (_ ('Bugs').encode (sys.stdout.encoding),
892 description=(_ ('Report bugs via')
893 + ''' http://post.gmane.org/post.php'''
894 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
900 opt_parser = get_option_parser()
901 (options, args) = opt_parser.parse_args ()
903 if not args or args[0] == '-':
904 opt_parser.print_help ()
905 ly.stderr_write ('\n%s: %s %s\n' % (program_name, _ ("error: "),
906 _ ("no files specified on command line.")))
909 if options.duration_quant:
910 options.duration_quant = int (options.duration_quant)
916 (alterations, minor) = map (int, string.split (options.key + ':0', ':'))[0:2]
922 flats = - alterations
924 options.key = Key (sharps, flats, minor)
927 if options.start_quant:
928 options.start_quant = int (options.start_quant)
930 options.allowed_tuplets = [map (int, a.replace ('/','*').split ('*'))
931 for a in options.allowed_tuplets]
933 global global_options
934 global_options = options
943 g = strip_extension (g, '.midi')
944 g = strip_extension (g, '.mid')
945 g = strip_extension (g, '.MID')
946 (outdir, outbase) = ('','')
950 outbase = os.path.basename (g)
951 o = os.path.join (outdir, outbase + '-midi.ly')
952 elif output_name[-1] == os.sep:
954 outbase = os.path.basename (g)
955 os.path.join (outdir, outbase + '-gen.ly')
958 (outdir, outbase) = os.path.split (o)
960 if outdir != '.' and outdir != '':
962 os.mkdir (outdir, 0777)
967 if __name__ == '__main__':