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 sys.path.insert (0, os.path.join (datadir, 'python'))
38 # dynamic relocation, for GUB binaries.
39 bindir = os.path.abspath (os.path.split (sys.argv[0])[0])
40 for p in ['share', 'lib']:
41 datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % p)
42 sys.path.insert (0, datadir)
48 ################################################################
49 ################ CONSTANTS
54 scale_steps = [0,2,4,5,7,9,11]
63 start_quant_clocks = 0
65 duration_quant_clocks = 0
66 allowed_tuplet_clocks = []
69 ################################################################
71 localedir = '@localedir@'
74 gettext.bindtextdomain ('lilypond', localedir)
75 gettext.textdomain ('lilypond')
81 program_name = sys.argv[0]
82 program_version = '@TOPLEVEL_VERSION@'
84 errorport = sys.stderr
87 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
100 _('Distributed under terms of the GNU General Public License.'),
101 _('It comes with NO WARRANTY.')))
105 errorport.write (s + '\n')
108 progress (_ ("warning: ") + s)
111 progress (_ ("error: ") + s)
112 raise _ ("Exiting ... ")
114 def system (cmd, ignore_error = 0):
115 return ly.system (cmd, ignore_error=ignore_error)
117 def strip_extension (f, ext):
118 (p, e) = os.path.splitext (f)
127 allowed_durs = (1, 2, 4, 8, 16, 32, 64, 128)
128 def __init__ (self, clocks):
131 self.clocks = duration_quant_clocks
132 (self.dur, self.num, self.den) = self.dur_num_den (clocks)
134 def dur_num_den (self, clocks):
135 for i in range (len (allowed_tuplet_clocks)):
136 if clocks == allowed_tuplet_clocks[i]:
137 return global_options.allowed_tuplets[i]
139 dur = 0; num = 1; den = 1;
140 g = gcd (clocks, clocks_per_1)
142 (dur, num) = (clocks_per_1 / g, clocks / g)
143 if not dur in self.allowed_durs:
144 dur = 4; num = clocks; den = clocks_per_4
145 return (dur, num, den)
151 elif self.num == 3 and self.dur != 1:
152 s = '%d.' % (self.dur / 2)
154 s = '%d*%d' % (self.dur, self.num)
156 s = '%d*%d/%d' % (self.dur, self.num, self.den)
158 global reference_note
159 reference_note.duration = self
163 def compare (self, other):
164 return self.clocks - other.clocks
173 names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
174 alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
175 alteration_names = ('eses', 'es', '', 'is' , 'isis')
176 def __init__ (self, clocks, pitch, velocity):
178 self.velocity = velocity
181 self.duration = Duration (clocks)
182 (self.octave, self.notename, self.alteration) = self.o_n_a ()
186 # minor scale: la-la (= + 5) '''
188 n = self.names[(self.pitch) % 12]
189 a = self.alterations[(self.pitch) % 12]
191 if a and global_options.key.flats:
192 a = - self.alterations[(self.pitch) % 12]
195 # By tradition, all scales now consist of a sequence
196 # of 7 notes each with a distinct name, from amongst
197 # a b c d e f g. But, minor scales have a wide
198 # second interval at the top - the 'leading note' is
199 # sharped. (Why? it just works that way! Anything
200 # else doesn't sound as good and isn't as flexible at
201 # saying things. In medieval times, scales only had 6
202 # notes to avoid this problem - the hexachords.)
204 # So, the d minor scale is d e f g a b-flat c-sharp d
205 # - using d-flat for the leading note would skip the
206 # name c and duplicate the name d. Why isn't c-sharp
207 # put in the key signature? Tradition. (It's also
208 # supposedly based on the Pythagorean theory of the
209 # cycle of fifths, but that really only applies to
210 # major scales...) Anyway, g minor is g a b-flat c d
211 # e-flat f-sharp g, and all the other flat minor keys
212 # end up with a natural leading note. And there you
215 # John Sankey <bf250@freenet.carleton.ca>
217 # Let's also do a-minor: a b c d e f gis a
221 o = self.pitch / 12 - 4
223 key = global_options.key
226 if (key.sharps == 0 and key.flats == 0
227 and n == 5 and a == -1):
230 elif key.flats == 1 and n == 1 and a == -1:
233 elif key.flats == 2 and n == 4 and a == -1:
236 elif key.sharps == 5 and n == 4 and a == 0:
239 elif key.sharps == 6 and n == 1 and a == 0:
242 elif key.sharps == 7 and n == 5 and a == 0:
246 if key.flats >= 6 and n == 6 and a == 0:
247 n = 0; a = -1; o = o + 1
249 if key.flats >= 7 and n == 2 and a == 0:
253 if key.sharps >= 3 and n == 3 and a == 0:
256 if key.sharps >= 4 and n == 0 and a == 0:
257 n = 6; a = 1; o = o - 1
262 s = chr ((self.notename + 2) % 7 + ord ('a'))
263 return 'Note(%s %s)' % (s, self.duration.dump())
265 def dump (self, dump_dur = 1):
266 global reference_note
267 s = chr ((self.notename + 2) % 7 + ord ('a'))
268 s = s + self.alteration_names[self.alteration + 2]
269 if global_options.absolute_pitches:
272 delta = self.pitch - reference_note.pitch
273 commas = sign (delta) * (abs (delta) / 12)
275 * (self.notename - reference_note.notename) + 7) \
277 or ((self.notename == reference_note.notename) \
278 and (abs (delta) > 4) and (abs (delta) < 12)):
279 commas = commas + sign (delta)
284 s = s + "," * -commas
286 ## FIXME: compile fix --jcn
287 if dump_dur and (global_options.explicit_durations \
288 or self.duration.compare (reference_note.duration)):
289 s = s + self.duration.dump ()
291 reference_note = self
298 def __init__ (self, num, den):
303 def bar_clocks (self):
304 return clocks_per_1 * self.num / self.den
307 return 'Time(%d/%d)' % (self.num, self.den)
312 return '\n ' + '\\time %d/%d ' % (self.num, self.den) + '\n '
315 def __init__ (self, seconds_per_1):
317 self.seconds_per_1 = seconds_per_1
320 return 'Tempo(%d)' % self.bpm ()
323 return 4 * 60 / self.seconds_per_1
326 return '\n ' + '\\tempo 4 = %d ' % (self.bpm()) + '\n '
329 clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
330 def __init__ (self, type):
334 return 'Clef(%s)' % self.clefs[self.type]
337 return '\n \\clef %s\n ' % self.clefs[self.type]
340 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
341 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
343 def __init__ (self, sharps, flats, minor):
350 global_options.key = self
353 if self.sharps and self.flats:
357 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
359 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
362 name = chr ((k + 2) % 7 + ord ('a'))
364 name = chr ((k + 2) % 7 + ord ('a'))
366 # fis cis gis dis ais eis bis
367 sharps = (2, 4, 6, 1, 3, 5, 7)
368 # bes es as des ges ces fes
369 flats = (6, 4, 2, 7, 5, 3, 1)
372 if flats[k] <= self.flats:
375 if sharps[k] <= self.sharps:
379 name = name + Note.alteration_names[a + 2]
387 return '\n\n ' + s + '\n '
395 'SEQUENCE_TRACK_NAME',
401 def __init__ (self, type, text):
407 # urg, we should be sure that we're in a lyrics staff
408 if self.type == midi.LYRIC:
409 s = '"%s"' % self.text
410 d = Duration (self.clocks)
411 if global_options.explicit_durations \
412 or d.compare (reference_note.duration):
413 s = s + Duration (self.clocks).dump ()
416 s = '\n % [' + self.text_types[self.type] + '] ' + self.text + '\n '
420 return 'Text(%d=%s)' % (self.type, self.text)
424 def split_track (track):
431 if data[0] > 0x7f and data[0] < 0xf0:
433 e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
443 for v in chs.values ():
444 events = events_on_channel (v)
445 thread = unthread_notes (events)
447 threads.append (thread)
451 def quantise_clocks (clocks, quant):
452 q = int (clocks / quant) * quant
454 for tquant in allowed_tuplet_clocks:
455 if int (clocks / tquant) * tquant == clocks:
457 if 2 * (clocks - q) > quant:
461 def end_note (pitches, notes, t, e):
463 (lt, vel) = pitches[e]
473 if duration_quant_clocks:
474 d = quantise_clocks (d, duration_quant_clocks)
476 d = duration_quant_clocks
479 (lt, Note (d, e, vel)))
484 def events_on_channel (channel):
494 if start_quant_clocks:
495 t = quantise_clocks (t, start_quant_clocks)
498 if e[1][0] == midi.NOTE_OFF \
499 or (e[1][0] == midi.NOTE_ON and e[1][2] == 0):
500 end_note (pitches, notes, t, e[1][1])
502 elif e[1][0] == midi.NOTE_ON:
503 if not pitches.has_key (e[1][1]):
504 pitches[e[1][1]] = (t, e[1][2])
506 # all include ALL_NOTES_OFF
507 elif e[1][0] >= midi.ALL_SOUND_OFF \
508 and e[1][0] <= midi.POLY_MODE_ON:
509 for i in pitches.keys ():
510 end_note (pitches, notes, t, i)
512 elif e[1][0] == midi.META_EVENT:
513 if e[1][1] == midi.END_OF_TRACK:
514 for i in pitches.keys ():
515 end_note (pitches, notes, t, i)
518 elif e[1][1] == midi.SET_TEMPO:
519 (u0, u1, u2) = map (ord, e[1][2])
520 us_per_4 = u2 + 256 * (u1 + 256 * u0)
521 seconds_per_1 = us_per_4 * 4 / 1e6
522 events.append ((t, Tempo (seconds_per_1)))
523 elif e[1][1] == midi.TIME_SIGNATURE:
524 (num, dur, clocks4, count32) = map (ord, e[1][2])
526 events.append ((t, Time (num, den)))
527 elif e[1][1] == midi.KEY_SIGNATURE:
528 (alterations, minor) = map (ord, e[1][2])
531 if alterations < 127:
534 flats = 256 - alterations
536 k = Key (sharps, flats, minor)
537 events.append ((t, k))
539 # ugh, must set key while parsing
540 # because Note init uses key
541 # Better do Note.calc () at dump time?
542 global_options.key = k
544 elif e[1][1] == midi.LYRIC \
545 or (global_options.text_lyrics and e[1][1] == midi.TEXT_EVENT):
547 last_lyric.clocks = t - last_time
548 events.append ((last_time, last_lyric))
550 last_lyric = Text (midi.LYRIC, e[1][2])
552 elif e[1][1] >= midi.SEQUENCE_NUMBER \
553 and e[1][1] <= midi.CUE_POINT:
554 events.append ((t, Text (e[1][1], e[1][2])))
556 if global_options.verbose:
557 sys.stderr.write ("SKIP: %s\n" % `e`)
560 if global_options.verbose:
561 sys.stderr.write ("SKIP: %s\n" % `e`)
565 # last_lyric.clocks = t - last_time
567 last_lyric.clocks = clocks_per_4
568 events.append ((last_time, last_lyric))
573 if i < len (events) and notes[0][0] >= events[i][0]:
576 events.insert (i, notes[0])
580 def unthread_notes (channel):
589 if e[1].__class__ == Note \
590 and ((t == start_busy_t \
591 and e[1].clocks + t == end_busy_t) \
595 end_busy_t = t + e[1].clocks
596 elif e[1].__class__ == Time \
597 or e[1].__class__ == Key \
598 or e[1].__class__ == Text \
599 or e[1].__class__ == Tempo:
603 threads.append (thread)
618 def dump_skip (skip, clocks):
619 return skip + Duration (clocks).dump () + ' '
628 if i.__class__ == Note:
633 s = s + dump (notes[0])
634 elif len (notes) > 1:
635 global reference_note
637 s = s + notes[0].dump (dump_dur = 0)
640 s = s + i.dump (dump_dur = 0 )
643 s = s + notes[0].duration.dump() + ' '
647 def dump_bar_line (last_bar_t, t, bar_count):
649 bar_t = time.bar_clocks ()
650 if t - last_bar_t >= bar_t:
651 bar_count = bar_count + (t - last_bar_t) / bar_t
653 if t - last_bar_t == bar_t:
654 s = '|\n %% %d\n ' % bar_count
657 # urg, this will barf at meter changes
658 last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
660 return (s, last_bar_t, bar_count)
663 def dump_channel (thread, skip):
664 global reference_note, time
666 global_options.key = Key (0, 0, 0)
668 # urg LilyPond doesn't start at c4, but
669 # remembers from previous tracks!
670 # reference_note = Note (clocks_per_4, 4*12, 0)
671 reference_note = Note (0, 4*12, 0)
677 if last_e and last_e[0] == e[0]:
681 chs.append ((last_e[0], ch))
688 chs.append ((last_e[0], ch))
698 i = string.rfind (lines[-1], '\n') + 1
699 if len (lines[-1][i:]) > LINE_BELL:
703 lines[-1] = lines[-1] + dump_skip (skip, t-last_t)
705 errorport.write ('BUG: time skew')
707 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
709 lines[-1] = lines[-1] + s
711 lines[-1] = lines[-1] + dump_chord (ch[1])
715 if i.clocks > clocks:
720 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
722 lines[-1] = lines[-1] + s
724 return string.join (lines, '\n ') + '\n'
727 return 'track%c' % (i + ord ('A'))
729 def channel_name (i):
730 return 'channel%c' % (i + ord ('A'))
732 def dump_track (channels, n):
734 track = track_name (n)
735 clef = guess_clef (channels)
737 for i in range (len (channels)):
738 channel = channel_name (i)
739 item = thread_first_item (channels[i])
741 if item and item.__class__ == Note:
743 s = s + '%s = ' % (track + channel)
744 if not global_options.absolute_pitches:
745 s = s + '\\relative c '
746 elif item and item.__class__ == Text:
748 s = s + '%s = \\lyricmode ' % (track + channel)
751 s = s + '%s = ' % (track + channel)
753 s = s + ' ' + dump_channel (channels[i][0], skip)
756 s = s + '%s = <<\n' % track
759 s = s + clef.dump () + '\n'
761 for i in range (len (channels)):
762 channel = channel_name (i)
763 item = thread_first_item (channels[i])
764 if item and item.__class__ == Text:
765 s = s + ' \\context Lyrics = %s \\%s\n' % (channel,
768 s = s + ' \\context Voice = %s \\%s\n' % (channel,
773 def thread_first_item (thread):
776 if (event[1].__class__ == Note
777 or (event[1].__class__ == Text
778 and event[1].type == midi.LYRIC)):
783 def track_first_item (track):
785 first = thread_first_item (thread)
790 def guess_clef (track):
796 if event[1].__class__ == Note:
798 p = p + event[1].pitch
799 if i and p / i <= 3*12:
801 elif i and p / i <= 5*12:
803 elif i and p / i >= 7*12:
809 def convert_midi (in_file, out_file):
810 global clocks_per_1, clocks_per_4, key
811 global start_quant_clocks
812 global duration_quant_clocks
813 global allowed_tuplet_clocks
815 str = open (in_file).read ()
816 midi_dump = midi.parse (str)
818 clocks_per_1 = midi_dump[0][1]
819 clocks_per_4 = clocks_per_1 / 4
821 if global_options.start_quant:
822 start_quant_clocks = clocks_per_1 / global_options.start_quant
824 if global_options.duration_quant:
825 duration_quant_clocks = clocks_per_1 / global_options.duration_quant
827 allowed_tuplet_clocks = []
828 for (dur, num, den) in global_options.allowed_tuplets:
829 allowed_tuplet_clocks.append (clocks_per_1 / den)
832 for t in midi_dump[1]:
833 global_options.key = Key (0, 0, 0)
834 tracks.append (split_track (t))
836 tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, in_file)
840 s = tag + '\n\\version "2.7.18"\n\n'
841 for i in range (len (tracks)):
842 s = s + dump_track (tracks[i], i)
844 s = s + '\n\\score {\n <<\n'
848 track = track_name (i)
849 item = track_first_item (t)
851 if item and item.__class__ == Note:
852 s = s + ' \\context Staff=%s \\%s\n' % (track, track)
853 elif item and item.__class__ == Text:
854 s = s + ' \\context Lyrics=%s \\%s\n' % (track, track)
859 progress (_ ("%s output to `%s'...") % ('LY', out_file))
864 handle = open (out_file, 'w')
870 def get_option_parser ():
871 p = ly.get_option_parser (usage='midi2ly [OPTIONS] FILE',
872 version="midi2ly (LilyPond) @TOPLEVEL_VERSION@",
873 description=_('''Convert MIDI to LilyPond source.'''))
875 p.add_option ('-a', '--absolute-pitches',
877 help=_ ("print absolute pitches"))
878 p.add_option ('-d', '--duration-quant',
880 help=_("quantise note durations on DUR"))
881 p.add_option ('-e', '--explicit-durations',
883 help=_ ("print explicit durations"))
884 p.add_option('-k', '--key', help=_ ("set key: ALT=+sharps|-flats; MINOR=1"),
885 metavar=_ ("ALT[:MINOR]"),
887 p.add_option ('-o', '--output', help=_("write output to FILE"),
890 p.add_option ('-s', '--start-quant',help= _ ("quantise note starts on DUR"),
892 p.add_option ('-t', '--allow-tuplet',
893 metavar=_ ("DUR*NUM/DEN"),
895 dest="allowed_tuplets",
896 help=_ ("allow tuplet durations DUR*NUM/DEN"),
898 p.add_option ('-V', '--verbose', help=_("be verbose"),
901 p.add_option ('-w', '--warranty', help=_("show warranty"),
904 p.add_option ('-x', '--text-lyrics', help=_("treat every text as a lyric"),
907 p.add_option_group (_ ("example"),
909 midi2ly --key=-2:1 --duration-quant=32 \
910 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
913 p.add_option_group ('bugs',
914 description='''Report bugs via http://post.gmane.org/post.php'''
915 '''?group=gmane.comp.gnu.lilypond.bugs\n''')
922 opt_parser = get_option_parser()
923 (options, args) = opt_parser.parse_args ()
925 if not args or args[0] == '-':
926 opt_parser.print_help ()
927 sys.stderr.write ('\n%s: %s %s\n' % (program_name, _ ("error: "),
928 _ ("no files specified on command line.")))
931 if options.duration_quant:
932 options.duration_quant = int (options.duration_quant)
938 (alterations, minor) = map (int, string.split (options.key + ':0', ':'))[0:2]
944 flats = - alterations
946 options.key = Key (sharps, flats, minor)
949 if options.start_quant:
950 options.start_quant = int (options.start_quant)
952 options.allowed_tuplets = [map (int, a.replace ('/','*').split ('*'))
953 for a in options.allowed_tuplets]
955 global global_options
956 global_options = options
965 g = strip_extension (g, '.midi')
966 g = strip_extension (g, '.mid')
967 g = strip_extension (g, '.MID')
968 (outdir, outbase) = ('','')
972 outbase = os.path.basename (g)
973 o = os.path.join (outdir, outbase + '-midi.ly')
974 elif output_name[-1] == os.sep:
976 outbase = os.path.basename (g)
977 os.path.join (outdir, outbase + '-gen.ly')
980 (outdir, outbase) = os.path.split (o)
982 if outdir != '.' and outdir != '':
984 os.mkdir (outdir, 0777)
989 if __name__ == '__main__':