3 # midi2ly.py -- LilyPond midi import script
5 # source file of the GNU LilyPond music typesetter
7 # convert MIDI to LilyPond source
13 * test on weird and unquantised midi input (lily-devel)
15 * update doc and manpage
17 * simply insert clef changes whenever too many ledger lines
18 [to avoid tex capacity exceeded]
19 * do not ever quant skips
20 * better lyrics handling
21 * [see if it is feasible to] move ly-classes to library for use in
22 other converters, while leaving midi specific stuff here
28 # if set, LILYPONDPREFIX must take prevalence
29 # if datadir is not set, we're doing a build and LILYPONDPREFIX
31 if os.environ.has_key ('LILYPONDPREFIX') \
32 or '@datadir@' == '@' + 'datadir' + '@':
33 datadir = os.environ['LILYPONDPREFIX']
37 sys.path.append (os.path.join (datadir, 'python'))
38 sys.path.append (os.path.join (datadir, 'python/out'))
48 localedir = '@localedir@'
51 gettext.bindtextdomain ('lilypond', localedir)
52 gettext.textdomain ('lilypond')
58 program_name = 'midi2ly'
59 program_version = '@TOPLEVEL_VERSION@'
61 errorport = sys.stderr
64 # temp_dir = os.path.join (original_dir, '%s.dir' % program_name)
65 # original_dir = os.getcwd ()
69 help_summary = _ ("Convert MIDI to LilyPond source")
71 option_definitions = [
72 ('', 'a', 'absolute-pitches', _ ("print absolute pitches")),
73 (_ ("DUR"), 'd', 'duration-quant', _ ("quantise note durations on DUR")),
74 ('', 'e', 'explicit-durations', _ ("print explicit durations")),
75 ('', 'h', 'help', _ ("this help")),
76 (_ ("ALT[:MINOR]"), 'k', 'key', _ ("set key: ALT=+sharps|-flats; MINOR=1")),
77 (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
78 (_ ("DUR"), 's', 'start-quant', _ ("quantise note starts on DUR")),
79 (_ ("DUR*NUM/DEN"), 't', 'allow-tuplet', _ ("allow tuplet durations DUR*NUM/DEN")),
80 ('', 'V', 'verbose', _ ("verbose")),
81 ('', 'v', 'version', _ ("print version number")),
82 ('', 'w', 'warranty', _ ("show warranty and copyright")),
83 ('', 'x', 'text-lyrics', _ ("treat every text as a lyric")),
86 # from lilylib import *
92 allowed_durs = (1, 2, 4, 8, 16, 32, 64, 128)
93 def __init__ (self, clocks):
96 self.clocks = duration_quant_clocks
97 (self.dur, self.num, self.den) = self.dur_num_den (clocks)
99 def dur_num_den (self, clocks):
100 for i in range (len (allowed_tuplet_clocks)):
101 if clocks == allowed_tuplet_clocks[i]:
102 return allowed_tuplets[i]
104 dur = 0; num = 1; den = 1;
105 g = gcd (clocks, clocks_per_1)
107 (dur, num) = (clocks_per_1 / g, clocks / g)
108 if not dur in self.allowed_durs:
109 dur = 4; num = clocks; den = clocks_per_4
110 return (dur, num, den)
116 elif self.num == 3 and self.dur != 1:
117 s = '%d.' % (self.dur / 2)
119 s = '%d*%d' % (self.dur, self.num)
121 s = '%d*%d/%d' % (self.dur, self.num, self.den)
123 global reference_note
124 reference_note.duration = self
128 def compare (self, other):
129 return self.clocks - other.clocks
138 names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
139 alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
140 alteration_names = ('eses', 'es', '', 'is' , 'isis')
142 def __init__ (self, clocks, pitch, velocity):
144 self.velocity = velocity
147 self.duration = Duration (clocks)
148 (self.octave, self.notename, self.alteration) = self.o_n_a ()
152 # minor scale: la-la (= + 5) '''
154 n = self.names[(self.pitch) % 12]
155 a = self.alterations[(self.pitch) % 12]
158 a = - self.alterations[(self.pitch) % 12]
161 # By tradition, all scales now consist of a sequence
162 # of 7 notes each with a distinct name, from amongst
163 # a b c d e f g. But, minor scales have a wide
164 # second interval at the top - the 'leading note' is
165 # sharped. (Why? it just works that way! Anything
166 # else doesn't sound as good and isn't as flexible at
167 # saying things. In medieval times, scales only had 6
168 # notes to avoid this problem - the hexachords.)
170 # So, the d minor scale is d e f g a b-flat c-sharp d
171 # - using d-flat for the leading note would skip the
172 # name c and duplicate the name d. Why isn't c-sharp
173 # put in the key signature? Tradition. (It's also
174 # supposedly based on the Pythagorean theory of the
175 # cycle of fifths, but that really only applies to
176 # major scales...) Anyway, g minor is g a b-flat c d
177 # e-flat f-sharp g, and all the other flat minor keys
178 # end up with a natural leading note. And there you
181 # John Sankey <bf250@freenet.carleton.ca>
183 # Let's also do a-minor: a b c d e f gis a
187 o = self.pitch / 12 - 4
191 if key.sharps == 0 and key.flats == 0 \
192 and n == 5 and a == -1:
195 elif key.flats == 1 and n == 1 and a == -1:
198 elif key.flats == 2 and n == 4 and a == -1:
201 elif key.sharps == 5 and n == 4 and a == 0:
204 elif key.sharps == 6 and n == 1 and a == 0:
207 elif key.sharps == 7 and n == 5 and a == 0:
211 if key.flats >= 6 and n == 6 and a == 0:
212 n = 0; a = -1; o = o + 1
214 if key.flats >= 7 and n == 2 and a == 0:
218 if key.sharps >= 3 and n == 3 and a == 0:
221 if key.sharps >= 4 and n == 0 and a == 0:
222 n = 6; a = 1; o = o - 1
227 s = chr ((self.notename + 2) % 7 + ord ('a'))
228 s = s + self.alteration_names[self.alteration + 2]
232 delta = self.pitch - reference_note.pitch
233 commas = sign (delta) * (abs (delta) / 12)
235 * (self.notename - reference_note.notename) + 7) \
237 or ((self.notename == reference_note.notename) \
238 and (abs (delta) > 4) and (abs (delta) < 12)):
239 commas = commas + sign (delta)
244 s = s + "," * -commas
246 if explicit_durations_p \
247 or Duration.compare (self.duration, reference_note.duration):
248 s = s + self.duration.dump ()
250 global reference_note
251 reference_note = self
257 def __init__ (self, num, den):
262 def bar_clocks (self):
263 return clocks_per_1 * self.num / self.den
268 return '\n ' + '\\time %d/%d ' % (self.num, self.den) + '\n '
271 def __init__ (self, seconds_per_1):
273 self.seconds_per_1 = seconds_per_1
276 return '\n ' + '\\tempo 4 = %d ' % (4 * 60 / self.seconds_per_1) + '\n '
279 clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
280 def __init__ (self, type):
284 return '\n \\clef %s\n ' % self.clefs[self.type]
287 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
288 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
290 def __init__ (self, sharps, flats, minor):
301 if self.sharps and self.flats:
302 s = '\\keysignature %s ' % 'TODO'
306 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
308 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
311 name = chr ((k + 2) % 7 + ord ('a'))
313 name = chr ((k + 2) % 7 + ord ('a'))
315 # fis cis gis dis ais eis bis
316 sharps = (2, 4, 6, 1, 3, 5, 7)
317 # bes es as des ges ces fes
318 flats = (6, 4, 2, 7, 5, 3, 1)
321 if flats[k] <= self.flats:
324 if sharps[k] <= self.sharps:
328 name = name + Note.alteration_names[a + 2]
336 return '\n\n ' + s + '\n '
344 'SEQUENCE_TRACK_NAME',
350 def __init__ (self, type, text):
356 # urg, we should be sure that we're in a lyrics staff
357 if self.type == midi.LYRIC:
358 s = '"%s"' % self.text
359 d = Duration (self.clocks)
360 if explicit_durations_p \
361 or Duration.compare (d,
362 reference_note.duration):
363 s = s + Duration (self.clocks).dump ()
366 s = '\n % [' + self.text_types[self.type] + '] ' + self.text + '\n '
372 scale_steps = [0,2,4,5,7,9,11]
380 start_quant_clocks = 0
382 duration_quant_clocks = 0
384 allowed_tuplet_clocks = []
386 explicit_durations_p = 0
389 def split_track (track):
396 if data[0] > 0x7f and data[0] < 0xf0:
398 e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
408 for v in chs.values ():
409 events = events_on_channel (v)
410 thread = unthread_notes (events)
412 threads.append (thread)
416 def quantise_clocks (clocks, quant):
417 q = int (clocks / quant) * quant
419 for tquant in allowed_tuplet_clocks:
420 if int (clocks / tquant) * tquant == clocks:
422 if 2 * (clocks - q) > quant:
426 def end_note (pitches, notes, t, e):
428 (lt, vel) = pitches[e]
438 if duration_quant_clocks:
439 d = quantise_clocks (d, duration_quant_clocks)
441 d = duration_quant_clocks
444 (lt, Note (d, e, vel)))
449 def events_on_channel (channel):
459 if start_quant_clocks:
460 t = quantise_clocks (t, start_quant_clocks)
463 if e[1][0] == midi.NOTE_OFF \
464 or (e[1][0] == midi.NOTE_ON and e[1][2] == 0):
465 end_note (pitches, notes, t, e[1][1])
467 elif e[1][0] == midi.NOTE_ON:
468 if not pitches.has_key (e[1][1]):
469 pitches[e[1][1]] = (t, e[1][2])
471 # all include ALL_NOTES_OFF
472 elif e[1][0] >= midi.ALL_SOUND_OFF \
473 and e[1][0] <= midi.POLY_MODE_ON:
474 for i in pitches.keys ():
475 end_note (pitches, notes, t, i)
477 elif e[1][0] == midi.META_EVENT:
478 if e[1][1] == midi.END_OF_TRACK:
479 for i in pitches.keys ():
480 end_note (pitches, notes, t, i)
483 elif e[1][1] == midi.SET_TEMPO:
484 (u0, u1, u2) = map (ord, e[1][2])
485 us_per_4 = u2 + 256 * (u1 + 256 * u0)
486 seconds_per_1 = us_per_4 * 4 / 1e6
487 events.append ((t, Tempo (seconds_per_1)))
488 elif e[1][1] == midi.TIME_SIGNATURE:
489 (num, dur, clocks4, count32) = map (ord, e[1][2])
491 events.append ((t, Time (num, den)))
492 elif e[1][1] == midi.KEY_SIGNATURE:
493 (alterations, minor) = map (ord, e[1][2])
496 if alterations < 127:
499 flats = 256 - alterations
501 k = Key (sharps, flats, minor)
502 events.append ((t, k))
504 # ugh, must set key while parsing
505 # because Note init uses key
506 # Better do Note.calc () at dump time?
510 elif e[1][1] == midi.LYRIC \
511 or (text_lyrics_p and e[1][1] == midi.TEXT_EVENT):
513 last_lyric.clocks = t - last_time
514 events.append ((last_time, last_lyric))
516 last_lyric = Text (midi.LYRIC, e[1][2])
518 elif e[1][1] >= midi.SEQUENCE_NUMBER \
519 and e[1][1] <= midi.CUE_POINT:
520 events.append ((t, Text (e[1][1], e[1][2])))
523 sys.stderr.write ("SKIP: %s\n" % `e`)
527 sys.stderr.write ("SKIP: %s\n" % `e`)
531 # last_lyric.clocks = t - last_time
533 last_lyric.clocks = clocks_per_4
534 events.append ((last_time, last_lyric))
539 if i < len (events) and notes[0][0] >= events[i][0]:
542 events.insert (i, notes[0])
546 def unthread_notes (channel):
555 if e[1].__class__ == Note \
556 and ((t == start_busy_t \
557 and e[1].clocks + t == end_busy_t) \
561 end_busy_t = t + e[1].clocks
562 elif e[1].__class__ == Time \
563 or e[1].__class__ == Key \
564 or e[1].__class__ == Text \
565 or e[1].__class__ == Tempo:
569 threads.append (thread)
584 def dump_skip (skip, clocks):
585 return skip + Duration (clocks).dump () + ' '
594 if i.__class__ == Note:
599 s = s + dump (notes[0])
600 elif len (notes) > 1:
601 global reference_note
603 s = s + notes[0].dump ()
611 def dump_bar_line (last_bar_t, t, bar_count):
613 bar_t = time.bar_clocks ()
614 if t - last_bar_t >= bar_t:
615 bar_count = bar_count + (t - last_bar_t) / bar_t
617 if t - last_bar_t == bar_t:
618 s = '|\n %% %d\n ' % bar_count
621 # urg, this will barf at meter changes
622 last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
624 return (s, last_bar_t, bar_count)
627 def dump_channel (thread, skip):
628 global key, reference_note, time
632 # urg LilyPond doesn't start at c4, but
633 # remembers from previous tracks!
634 # reference_note = Note (clocks_per_4, 4*12, 0)
635 reference_note = Note (0, 4*12, 0)
641 if last_e and last_e[0] == e[0]:
645 chs.append ((last_e[0], ch))
652 chs.append ((last_e[0], ch))
662 i = string.rfind (lines[-1], '\n') + 1
663 if len (lines[-1][i:]) > LINE_BELL:
667 lines[-1] = lines[-1] + dump_skip (skip, t-last_t)
669 errorport.write ('BUG: time skew')
671 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
673 lines[-1] = lines[-1] + s
675 lines[-1] = lines[-1] + dump_chord (ch[1])
679 if i.clocks > clocks:
684 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
686 lines[-1] = lines[-1] + s
688 return string.join (lines, '\n ') + '\n'
691 return 'track%c' % (i + ord ('A'))
693 def channel_name (i):
694 return 'channel%c' % (i + ord ('A'))
696 def dump_track (channels, n):
698 track = track_name (n)
699 clef = guess_clef (channels)
701 for i in range (len (channels)):
702 channel = channel_name (i)
703 item = thread_first_item (channels[i])
705 if item and item.__class__ == Note:
707 s = s + '%s = \\notes' % (track + channel)
709 s = s + '\\relative c '
710 elif item and item.__class__ == Text:
712 s = s + '%s = \\lyrics ' % (track + channel)
715 # must be in \notes mode for parsing \skip
716 s = s + '%s = \\notes ' % (track + channel)
718 s = s + ' ' + dump_channel (channels[i][0], skip)
721 s = s + '%s = <\n' % track
724 s = s + clef.dump () + '\n'
726 for i in range (len (channels)):
727 channel = channel_name (i)
728 item = thread_first_item (channels[i])
729 if item and item.__class__ == Text:
730 s = s + ' \\context Lyrics = %s \\%s\n' % (channel,
733 s = s + ' \\context Voice = %s \\%s\n' % (channel,
738 def thread_first_item (thread):
741 if event[1].__class__ == Note \
742 or (event[1].__class__ == Text \
743 and event[1].type == midi.LYRIC):
747 def track_first_item (track):
749 return thread_first_item (thread)
751 def guess_clef (track):
757 if event[1].__class__ == Note:
759 p = p + event[1].pitch
760 if i and p / i <= 3*12:
762 elif i and p / i <= 5*12:
764 elif i and p / i >= 7*12:
770 def convert_midi (f, o):
771 global clocks_per_1, clocks_per_4, key
773 str = open (f).read ()
774 midi_dump = midi.parse (str)
776 clocks_per_1 = midi_dump[0][1]
777 clocks_per_4 = clocks_per_1 / 4
779 global start_quant, start_quant_clocks
781 start_quant_clocks = clocks_per_1 / start_quant
783 global duration_quant, duration_quant_clocks
785 duration_quant_clocks = clocks_per_1 / duration_quant
787 global allowed_tuplet_clocks
788 allowed_tuplet_clocks = []
789 for (dur, num, den) in allowed_tuplets:
790 allowed_tuplet_clocks.append (clocks_per_1 * num / (dur * den))
793 for t in midi_dump[1]:
795 tracks.append (split_track (t))
797 tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, f)
801 for i in range (len (tracks)):
802 s = s + dump_track (tracks[i], i)
804 s = s + '\n\\score {\n <\n'
805 for i in range (len (tracks)):
806 track = track_name (i)
807 item = track_first_item (tracks[i])
808 if item and item.__class__ == Note:
809 s = s + ' \\context Staff=%s \\%s\n' % (track, track)
810 elif item and item.__class__ == Text:
811 s = s + ' \\context Lyrics=%s \\%s\n' % (track, track)
814 lilylib.progress (_ ("%s output to `%s'...") % ('LY', o))
825 (sh, long) = lilylib.getopt_args (option_definitions)
827 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
828 except getopt.error, s:
829 errorport.write ('\n')
830 errorport.write (_ ("error: ") + _ ("getopt says: `%s\'" % s))
831 errorport.write ('\n')
832 errorport.write ('\n')
842 elif o == '--help' or o == '-h':
844 errorport.write ('\n')
845 errorport.write (_ ("Example:"))
846 errorport.write (r'''
847 midi2ly --key=-2:1 --duration-quant=32 \
848 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
851 elif o == '--output' or o == '-o':
853 elif o == '--verbose' or o == '-V':
855 elif o == '--version' or o == '-v':
858 elif o == '--warranty' or o == '-w':
859 status = system ('lilypond -w', ignore_error = 1)
865 elif o == '--absolute-pitches' or o == '-a':
868 elif o == '--duration-quant' or o == '-d':
869 global duration_quant
870 duration_quant = string.atoi (a)
871 elif o == '--explicit-durations' or o == '-e':
872 global explicit_durations_p
873 explicit_durations_p = 1
874 elif o == '--key' or o == '-k':
875 (alterations, minor) = map (string.atoi, string.split (a + ':0', ':'))[0:2]
881 flats = - alterations
883 key = Key (sharps, flats, minor)
884 elif o == '--start-quant' or o == '-s':
885 global start_quant, start_quant_clocks
886 start_quant = string.atoi (a)
887 elif o == '--allow-tuplet' or o == '-t':
888 global allowed_tuplets
889 a = string.replace (a, '/', '*')
890 tuplet = map (string.atoi, string.split (a, '*'))
891 allowed_tuplets.append (tuplet)
892 # lots of midi files use plain text for lyric events
893 elif o == '--text-lyrics' or o == '-x':
897 if not files or files[0] == '-':
899 # FIXME: read from stdin when files[0] = '-'
901 errorport.write (program_name + ":" + _ ("error: ") + _ ("no files specified on command line.") + '\n')
908 g = lilylib.strip_extension (g, '.midi')
909 g = lilylib.strip_extension (g, '.mid')
910 g = lilylib.strip_extension (g, '.MID')
911 (outdir, outbase) = ('','')
915 outbase = os.path.basename (g)
916 o = os.path.join (outdir, outbase + '-midi.ly')
917 elif output_name[-1] == os.sep:
919 outbase = os.path.basename (g)
920 os.path.join (outdir, outbase + '-gen.ly')
923 (outdir, outbase) = os.path.split (o)
926 mkdir_p (outdir, 0777)