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
30 sys.path.append ('@datadir@/python')
31 sys.path.append ('@datadir@/buildscripts/out')
32 sys.path.append ('@datadir@/modules/out')
38 gettext.bindtextdomain ('lilypond', '@localedir@')
39 gettext.textdomain ('lilypond')
45 # Attempt to fix problems with limited stack size set by Python!
46 # Sets unlimited stack size. Note that the resource module only
47 # is available on UNIX.
50 resource.setrlimit (resource.RLIMIT_STACK, (-1, -1))
54 program_name = 'midi2ly [experimental]'
55 package_name = 'lilypond'
56 help_summary = _ ("Convert MIDI to LilyPond source")
58 option_definitions = [
59 ('', 'a', 'absolute-pitches', _ ("print absolute pitches")),
60 (_ ("DUR"), 'd', 'duration-quant', _ ("quantise note durations on DUR")),
61 ('', 'e', 'explicit-durations', _ ("print explicit durations")),
62 ('', 'h', 'help', _ ("this help")),
63 (_ ("ALT[:MINOR]"), 'k', 'key', _ ("set key: ALT=+sharps|-flats; MINOR=1")),
64 (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
65 (_ ("DUR"), 's', 'start-quant', _ ("quantise note starts on DUR")),
66 (_ ("DUR*NUM/DEN"), 't', 'allow-tuplet', _ ("allow tuplet durations DUR*NUM/DEN")),
67 ('', 'V', 'verbose', _ ("verbose")),
68 ('', 'v', 'version', _ ("print version number")),
69 ('', 'w', 'warranty', _ ("show warranty and copyright")),
70 ('', 'x', 'text-lyrics', _ ("treat every text as a lyric")),
77 allowed_durs = (1, 2, 4, 16, 32, 64, 128)
78 def __init__ (self, clocks):
81 self.clocks = duration_quant_clocks
82 (self.dur, self.num, self.den) = self.dur_num_den (clocks)
84 def dur_num_den (self, clocks):
85 for i in range (len (allowed_tuplet_clocks)):
86 if clocks == allowed_tuplet_clocks[i]:
87 return allowed_tuplets[i]
89 dur = 0; num = 1; den = 1;
90 g = gcd (clocks, clocks_per_1)
91 if g and g > clocks / g:
92 (dur, num) = (clocks_per_1 / g, clocks / g)
93 if not dur in self.allowed_durs:
94 dur = 4; num = clocks; den = clocks_per_4
95 return (dur, num, den)
101 elif self.num == 3 and self.dur != 1:
102 s = '%d.' % (self.dur / 2)
104 s = '%d*%d' % (self.dur, self.num)
106 s = '%d*%d/%d' % (self.dur, self.num, self.den)
108 global reference_note
109 reference_note.duration = self
113 def compare (self, other):
114 return self.clocks - other.clocks
123 names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
124 alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
125 alteration_names = ('eses', 'es', '', 'is' , 'isis')
127 def __init__ (self, clocks, pitch, velocity):
129 self.velocity = velocity
132 self.duration = Duration (clocks)
133 (self.octave, self.notename, self.alteration) = self.o_n_a ()
137 # minor scale: la-la (= + 5) '''
139 n = self.names[(self.pitch) % 12]
140 a = self.alterations[(self.pitch) % 12]
143 a = - self.alterations[(self.pitch) % 12]
146 # By tradition, all scales now consist of a sequence
147 # of 7 notes each with a distinct name, from amongst
148 # a b c d e f g. But, minor scales have a wide
149 # second interval at the top - the 'leading note' is
150 # sharped. (Why? it just works that way! Anything
151 # else doesn't sound as good and isn't as flexible at
152 # saying things. In medieval times, scales only had 6
153 # notes to avoid this problem - the hexachords.)
155 # So, the d minor scale is d e f g a b-flat c-sharp d
156 # - using d-flat for the leading note would skip the
157 # name c and duplicate the name d. Why isn't c-sharp
158 # put in the key signature? Tradition. (It's also
159 # supposedly based on the Pythagorean theory of the
160 # cycle of fifths, but that really only applies to
161 # major scales...) Anyway, g minor is g a b-flat c d
162 # e-flat f-sharp g, and all the other flat minor keys
163 # end up with a natural leading note. And there you
166 # John Sankey <bf250@freenet.carleton.ca>
168 # Let's also do a-minor: a b c d e f gis a
172 o = self.pitch / 12 - 4
176 if key.sharps == 0 and key.flats == 0 \
177 and n == 5 and a == -1:
180 elif key.flats == 1 and n == 1 and a == -1:
183 elif key.flats == 2 and n == 4 and a == -1:
186 elif key.sharps == 5 and n == 4 and a == 0:
189 elif key.sharps == 6 and n == 1 and a == 0:
192 elif key.sharps == 7 and n == 5 and a == 0:
196 if key.flats >= 6 and n == 6 and a == 0:
197 n = 0; a = -1; o = o + 1
199 if key.flats >= 7 and n == 2 and a == 0:
203 if key.sharps >= 3 and n == 3 and a == 0:
206 if key.sharps >= 4 and n == 0 and a == 0:
207 n = 6; a = 1; o = o - 1
212 s = chr ((self.notename + 2) % 7 + ord ('a'))
213 s = s + self.alteration_names[self.alteration + 2]
217 delta = self.pitch - reference_note.pitch
218 commas = sign (delta) * (abs (delta) / 12)
220 * (self.notename - reference_note.notename) + 7) \
222 commas = commas + sign (delta)
227 s = s + "," * -commas
229 if explicit_durations_p \
230 or Duration.compare (self.duration, reference_note.duration):
231 s = s + self.duration.dump ()
233 global reference_note
234 reference_note = self
240 def __init__ (self, num, den):
246 return '\n ' + '\\time %d/%d ' % (self.num, self.den) + '\n '
249 def __init__ (self, seconds_per_1):
251 self.seconds_per_1 = seconds_per_1
254 return '\n ' + '\\tempo 4 = %d ' % (4 * 60 / self.seconds_per_1) + '\n '
257 clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
258 def __init__ (self, type):
262 return '\n \\clef %s\n ' % self.clefs[self.type]
265 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
266 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
268 def __init__ (self, sharps, flats, minor):
279 if self.sharps and self.flats:
280 s = '\\keysignature %s ' % 'TODO'
284 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
286 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
289 name = chr ((k + 2) % 7 + ord ('a'))
291 name = chr ((k + 2) % 7 + ord ('a'))
293 # fis cis gis dis ais eis bis
294 sharps = (2, 4, 6, 1, 3, 5, 7)
295 # bes es as des ges ces fes
296 flats = (6, 4, 2, 7, 5, 3, 1)
299 if flats[k] <= self.flats:
302 if sharps[k] <= self.sharps:
306 name = name + Note.alteration_names[a + 2]
314 return '\n\n ' + s + '\n '
322 'SEQUENCE_TRACK_NAME',
328 def __init__ (self, type, text):
334 # urg, we should be sure that we're in a lyrics staff
335 if self.type == midi.LYRIC:
336 s = '"%s"' % self.text
337 d = Duration (self.clocks)
338 if explicit_durations_p \
339 or Duration.compare (d,
340 reference_note.duration):
341 s = s + Duration (self.clocks).dump ()
344 s = '\n % [' + self.text_types[self.type] + '] ' + self.text + '\n '
350 scale_steps = [0,2,4,5,7,9,11]
357 start_quant_clocks = 0
359 duration_quant_clocks = 0
361 allowed_tuplet_clocks = []
363 explicit_durations_p = 0
366 def split_track (track):
373 if data[0] > 0x7f and data[0] < 0xf0:
375 e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
385 for v in chs.values ():
386 events = events_on_channel (v)
387 thread = unthread_notes (events)
389 threads.append (thread)
393 def quantise_clocks (clocks, quant):
394 q = int (clocks / quant) * quant
396 for tquant in allowed_tuplet_clocks:
397 if int (clocks / tquant) * tquant == clocks:
399 if 2 * (clocks - q) > quant:
403 def end_note (pitches, notes, t, e):
405 (lt, vel) = pitches[e]
415 if duration_quant_clocks:
416 d = quantise_clocks (d, duration_quant_clocks)
418 d = duration_quant_clocks
421 (lt, Note (d, e, vel)))
426 def events_on_channel (channel):
436 if start_quant_clocks:
437 t = quantise_clocks (t, start_quant_clocks)
440 if e[1][0] == midi.NOTE_OFF \
441 or (e[1][0] == midi.NOTE_ON and e[1][2] == 0):
442 end_note (pitches, notes, t, e[1][1])
444 elif e[1][0] == midi.NOTE_ON:
445 if not pitches.has_key (e[1][1]):
446 pitches[e[1][1]] = (t, e[1][2])
448 # all include ALL_NOTES_OFF
449 elif e[1][0] >= midi.ALL_SOUND_OFF \
450 and e[1][0] <= midi.POLY_MODE_ON:
451 for i in pitches.keys ():
452 end_note (pitches, notes, t, i)
454 elif e[1][0] == midi.META_EVENT:
455 if e[1][1] == midi.END_OF_TRACK:
456 for i in pitches.keys ():
457 end_note (pitches, notes, t, i)
460 elif e[1][1] == midi.SET_TEMPO:
461 (u0, u1, u2) = map (ord, e[1][2])
462 us_per_4 = u2 + 256 * (u1 + 256 * u0)
463 seconds_per_1 = us_per_4 * 4 / 1e6
464 events.append ((t, Tempo (seconds_per_1)))
465 elif e[1][1] == midi.TIME_SIGNATURE:
466 (num, dur, clocks4, count32) = map (ord, e[1][2])
468 events.append ((t, Time (num, den)))
469 elif e[1][1] == midi.KEY_SIGNATURE:
470 (alterations, minor) = map (ord, e[1][2])
473 if alterations < 127:
476 flats = 256 - alterations
478 k = Key (sharps, flats, minor)
479 events.append ((t, k))
481 # ugh, must set key while parsing
482 # because Note init uses key
483 # Better do Note.calc () at dump time?
487 elif e[1][1] == midi.LYRIC \
488 or (text_lyrics_p and e[1][1] == midi.TEXT_EVENT):
490 last_lyric.clocks = t - last_time
491 events.append ((last_time, last_lyric))
493 last_lyric = Text (midi.LYRIC, e[1][2])
495 elif e[1][1] >= midi.SEQUENCE_NUMBER \
496 and e[1][1] <= midi.CUE_POINT:
497 events.append ((t, Text (e[1][1], e[1][2])))
500 sys.stderr.write ("SKIP: %s\n" % `e`)
504 sys.stderr.write ("SKIP: %s\n" % `e`)
508 # last_lyric.clocks = t - last_time
510 last_lyric.clocks = clocks_per_4
511 events.append ((last_time, last_lyric))
516 if i < len (events) and notes[0][0] >= events[i][0]:
519 events.insert (i, notes[0])
523 def unthread_notes (channel):
532 if e[1].__class__ == Note \
533 and ((t == start_busy_t \
534 and e[1].clocks + t == end_busy_t) \
538 end_busy_t = t + e[1].clocks
539 elif e[1].__class__ == Time \
540 or e[1].__class__ == Key \
541 or e[1].__class__ == Text \
542 or e[1].__class__ == Tempo:
546 threads.append (thread)
561 def dump_skip (skip, clocks):
562 return skip + Duration (clocks).dump () + ' '
571 if i.__class__ == Note:
576 s = s + dump (notes[0])
577 elif len (notes) > 1:
578 global reference_note
580 s = s + notes[0].dump ()
588 def dump_channel (thread, skip):
589 global key, reference_note
592 # urg LilyPond doesn't start at c4, but
593 # remembers from previous tracks!
594 # reference_note = Note (clocks_per_4, 4*12, 0)
595 reference_note = Note (0, 4*12, 0)
601 if last_e and last_e[0] == e[0]:
605 chs.append ((last_e[0], ch))
612 chs.append ((last_e[0], ch))
618 i = string.rfind (lines[-1], '\n') + 1
619 if len (lines[-1][i:]) > LINE_BELL:
624 lines[-1] = lines[-1] + dump_skip (skip, t-last_t)
626 errorport.write ('BUG: time skew')
628 lines[-1] = lines[-1] + dump_chord (ch[1])
632 if i.clocks > clocks:
637 return string.join (lines, '\n ') + '\n'
640 return 'track%c' % (i + ord ('A'))
642 def channel_name (i):
643 return 'channel%c' % (i + ord ('A'))
645 def dump_track (channels, n):
647 track = track_name (n)
648 clef = guess_clef (channels)
650 for i in range (len (channels)):
651 channel = channel_name (i)
652 item = thread_first_item (channels[i])
654 if item and item.__class__ == Note:
656 s = s + '%s = \\notes' % (track + channel)
658 s = s + '\\relative c '
659 elif item and item.__class__ == Text:
661 s = s + '%s = \\lyrics ' % (track + channel)
664 # must be in \notes mode for parsing \skip
665 s = s + '%s = \\notes ' % (track + channel)
667 s = s + ' ' + dump_channel (channels[i][0], skip)
670 s = s + '%s = <\n' % track
673 s = s + clef.dump () + '\n'
675 for i in range (len (channels)):
676 channel = channel_name (i)
677 item = thread_first_item (channels[i])
678 if item and item.__class__ == Text:
679 s = s + ' \\context Lyrics = %s \\%s\n' % (channel,
682 s = s + ' \\context Voice = %s \\%s\n' % (channel,
687 def thread_first_item (thread):
690 if event[1].__class__ == Note \
691 or (event[1].__class__ == Text \
692 and event[1].type == midi.LYRIC):
696 def track_first_item (track):
698 return thread_first_item (thread)
700 def guess_clef (track):
706 if event[1].__class__ == Note:
708 p = p + event[1].pitch
709 if i and p / i <= 3*12:
711 elif i and p / i <= 5*12:
713 elif i and p / i >= 7*12:
719 def convert_midi (f, o):
720 global clocks_per_1, clocks_per_4, key
722 str = open (f).read ()
723 midi_dump = midi.parse (str)
725 clocks_per_1 = midi_dump[0][1]
726 clocks_per_4 = clocks_per_1 / 4
728 global start_quant, start_quant_clocks
730 start_quant_clocks = clocks_per_1 / start_quant
732 global duration_quant, duration_quant_clocks
734 duration_quant_clocks = clocks_per_1 / duration_quant
736 global allowed_tuplet_clocks
737 allowed_tuplet_clocks = []
738 for (dur, num, den) in allowed_tuplets:
739 allowed_tuplet_clocks.append (clocks_per_1 * num / (dur * den))
742 for t in midi_dump[1]:
744 tracks.append (split_track (t))
746 tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, f)
750 for i in range (len (tracks)):
751 s = s + dump_track (tracks[i], i)
753 s = s + '\n\\score {\n <\n'
754 for i in range (len (tracks)):
755 track = track_name (i)
756 item = track_first_item (tracks[i])
757 if item and item.__class__ == Note:
758 s = s + ' \\context Staff=%s \\%s\n' % (track, track)
759 elif item and item.__class__ == Text:
760 s = s + ' \\context Lyrics=%s \\%s\n' % (track, track)
763 progress (_ ("%s output to `%s'...") % ('LY', o))
774 (sh, long) = getopt_args (__main__.option_definitions)
776 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
777 except getopt.error, s:
778 errorport.write ('\n')
779 errorport.write (_ ("error: ") + _ ("getopt says: `%s\'" % s))
780 errorport.write ('\n')
781 errorport.write ('\n')
791 elif o == '--help' or o == '-h':
793 errorport.write ('\n')
794 errorport.write (_ ("Example:"))
795 errorport.write (r'''
796 midi2ly --key=-2:1 --duration-quant=32 \
797 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
800 elif o == '--output' or o == '-o':
802 elif o == '--verbose' or o == '-V':
804 elif o == '--version' or o == '-v':
807 elif o == '--warranty' or o == '-w':
808 status = system ('lilypond -w', ignore_error = 1)
814 elif o == '--absolute-pitches' or o == '-a':
817 elif o == '--duration-quant' or o == '-d':
818 global duration_quant
819 duration_quant = string.atoi (a)
820 elif o == '--explicit-durations' or o == '-e':
821 global explicit_durations_p
822 explicit_durations_p = 1
823 elif o == '--key' or o == '-k':
824 (alterations, minor) = map (string.atoi, string.split (a + ':0', ':'))[0:2]
830 flats = - alterations
832 key = Key (sharps, flats, minor)
833 elif o == '--start-quant' or o == '-s':
834 global start_quant, start_quant_clocks
835 start_quant = string.atoi (a)
836 elif o == '--allow-tuplet' or o == '-t':
837 global allowed_tuplets
838 a = string.replace (a, '/', '*')
839 tuplet = map (string.atoi, string.split (a, '*'))
840 allowed_tuplets.append (tuplet)
841 # lots of midi files use plain text for lyric events
842 elif o == '--text-lyrics' or o == '-x':
846 if not files or files[0] == '-':
848 # FIXME: read from stdin when files[0] = '-'
850 errorport.write (program_name + ":" + _ ("error: ") + _ ("no files specified on command line.") + '\n')
857 g = strip_extension (g, '.midi')
858 g = strip_extension (g, '.mid')
859 g = strip_extension (g, '.MID')
860 (outdir, outbase) = ('','')
864 outbase = os.path.basename (g)
865 o = os.path.join (outdir, outbase + '-midi.ly')
866 elif output_name[-1] == os.sep:
868 outbase = os.path.basename (g)
869 os.path.join (outdir, outbase + '-gen.ly')
872 (outdir, outbase) = os.path.split (o)
875 mkdir_p (outdir, 0777)