3 # midi2ly.py -- LilyPond midi import script
5 # This file is part of LilyPond, the GNU music typesetter.
7 # Copyright (C) 1998--2015 Han-Wen Nienhuys <hanwen@xs4all.nl>
8 # Jan Nieuwenhuizen <janneke@gnu.org>
10 # LilyPond is free software: you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation, either version 3 of the License, or
13 # (at your option) any later version.
15 # LilyPond is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with LilyPond. If not, see <http://www.gnu.org/licenses/>.
38 ################################################################
43 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 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
64 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
66 errorport = sys.stderr
69 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
73 ly.encoded_write (sys.stdout, '''
80 ''' % ( _ ('Copyright (c) %s by') % '1998--2015',
82 _ ('Distributed under terms of the GNU General Public License.'),
83 _ ('It comes with NO WARRANTY.')))
86 ly.encoded_write (errorport, s + '\n')
89 progress (_ ("warning: ") + s)
92 progress (_ ("error: ") + s)
93 raise Exception (_ ("Exiting... "))
96 if global_options.debug:
97 progress ("debug: " + s)
99 def system (cmd, ignore_error = 0):
100 return ly.system (cmd, ignore_error=ignore_error)
102 def strip_extension (f, ext):
103 (p, e) = os.path.splitext (f)
110 allowed_durs = (1, 2, 4, 8, 16, 32, 64, 128)
111 def __init__ (self, clocks):
113 (self.dur, self.num, self.den) = self.dur_num_den (clocks)
115 def dur_num_den (self, clocks):
116 for i in range (len (allowed_tuplet_clocks)):
117 if clocks == allowed_tuplet_clocks[i]:
118 return global_options.allowed_tuplets[i]
120 dur = 0; num = 1; den = 1;
121 g = gcd (clocks, clocks_per_1)
123 (dur, num) = (clocks_per_1 / g, clocks / g)
124 if not dur in self.allowed_durs:
125 dur = 4; num = clocks; den = clocks_per_4
126 return (dur, num, den)
132 elif self.num == 3 and self.dur != 1:
133 s = '%d.' % (self.dur / 2)
135 s = '%d*%d' % (self.dur, self.num)
137 s = '%d*%d/%d' % (self.dur, self.num, self.den)
139 global reference_note
140 reference_note.duration = self
144 def compare (self, other):
145 return self.clocks - other.clocks
154 names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
155 alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
156 alteration_names = ('eses', 'es', '', 'is' , 'isis')
157 def __init__ (self, clocks, pitch, velocity):
159 self.velocity = velocity
162 self.duration = Duration (clocks)
163 (self.octave, self.notename, self.alteration) = self.o_n_a ()
167 # minor scale: la-la (= + 5) '''
169 n = self.names[(self.pitch) % 12]
170 a = self.alterations[(self.pitch) % 12]
172 key = global_options.key
177 a = - self.alterations[(self.pitch) % 12]
180 # By tradition, all scales now consist of a sequence
181 # of 7 notes each with a distinct name, from amongst
182 # a b c d e f g. But, minor scales have a wide
183 # second interval at the top - the 'leading note' is
184 # sharped. (Why? it just works that way! Anything
185 # else doesn't sound as good and isn't as flexible at
186 # saying things. In medieval times, scales only had 6
187 # notes to avoid this problem - the hexachords.)
189 # So, the d minor scale is d e f g a b-flat c-sharp d
190 # - using d-flat for the leading note would skip the
191 # name c and duplicate the name d. Why isn't c-sharp
192 # put in the key signature? Tradition. (It's also
193 # supposedly based on the Pythagorean theory of the
194 # cycle of fifths, but that really only applies to
195 # major scales...) Anyway, g minor is g a b-flat c d
196 # e-flat f-sharp g, and all the other flat minor keys
197 # end up with a natural leading note. And there you
200 # John Sankey <bf250@freenet.carleton.ca>
202 # Let's also do a-minor: a b c d e f gis a
206 o = self.pitch / 12 - 4
210 if (key.sharps == 0 and key.flats == 0
211 and n == 5 and a == -1):
214 elif key.flats == 1 and n == 1 and a == -1:
217 elif key.flats == 2 and n == 4 and a == -1:
220 elif key.sharps == 5 and n == 4 and a == 0:
223 elif key.sharps == 6 and n == 1 and a == 0:
226 elif key.sharps == 7 and n == 5 and a == 0:
230 if key.flats >= 6 and n == 6 and a == 0:
231 n = 0; a = -1; o = o + 1
233 if key.flats >= 7 and n == 2 and a == 0:
237 if key.sharps >= 3 and n == 3 and a == 0:
240 if key.sharps >= 4 and n == 0 and a == 0:
241 n = 6; a = 1; o = o - 1
246 s = chr ((self.notename + 2) % 7 + ord ('a'))
247 return 'Note(%s %s)' % (s, self.duration.dump ())
249 def dump (self, dump_dur=True):
250 global reference_note
251 s = chr ((self.notename + 2) % 7 + ord ('a'))
252 s = s + self.alteration_names[self.alteration + 2]
253 if global_options.absolute_pitches:
256 delta = self.pitch - reference_note.pitch
257 commas = sign (delta) * (abs (delta) / 12)
259 * (self.notename - reference_note.notename) + 7)
261 or ((self.notename == reference_note.notename)
262 and (abs (delta) > 4) and (abs (delta) < 12))):
263 commas = commas + sign (delta)
268 s = s + "," * -commas
271 and self.duration.compare (reference_note.duration))
272 or global_options.explicit_durations):
273 s = s + self.duration.dump ()
275 reference_note = self
282 def __init__ (self, num, den):
287 def bar_clocks (self):
288 return clocks_per_1 * self.num / self.den
291 return 'Time(%d/%d)' % (self.num, self.den)
296 return '\n ' + '\\time %d/%d ' % (self.num, self.den) + '\n '
299 def __init__ (self, seconds_per_1):
301 self.seconds_per_1 = seconds_per_1
304 return 'Tempo(%d)' % self.bpm ()
307 return 4 * 60 / self.seconds_per_1
310 return '\n ' + '\\tempo 4 = %d ' % (self.bpm ()) + '\n '
313 clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
314 def __init__ (self, type):
318 return 'Clef(%s)' % self.clefs[self.type]
321 return '\n \\clef %s\n ' % self.clefs[self.type]
324 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
325 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
327 def __init__ (self, sharps, flats, minor):
334 global_options.key = self
337 if self.sharps and self.flats:
341 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
343 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
346 name = chr ((k + 2) % 7 + ord ('a'))
348 name = chr ((k + 2) % 7 + ord ('a'))
350 # fis cis gis dis ais eis bis
351 sharps = (2, 4, 6, 1, 3, 5, 7)
352 # bes es as des ges ces fes
353 flats = (6, 4, 2, 7, 5, 3, 1)
356 if flats[k] <= self.flats:
359 if sharps[k] <= self.sharps:
363 name = name + Note.alteration_names[a + 2]
371 return '\n\n ' + s + '\n '
379 'SEQUENCE_TRACK_NAME',
385 def __init__ (self, type, text):
391 # urg, we should be sure that we're in a lyrics staff
393 if self.type == midi.LYRIC:
394 s = '"%s"' % self.text
395 d = Duration (self.clocks)
396 if (global_options.explicit_durations
397 or d.compare (reference_note.duration)):
398 s = s + Duration (self.clocks).dump ()
400 elif (self.text.strip ()
401 and self.type == midi.SEQUENCE_TRACK_NAME
402 and not self.text == 'control track'
403 and not self.track.lyrics_p_):
404 text = self.text.replace ('(MIDI)', '').strip ()
406 s = '\n \\set Staff.instrumentName = "%(text)s"\n ' % locals ()
407 elif self.text.strip ():
408 s = '\n % [' + self.text_types[self.type] + '] ' + self.text + '\n '
412 return 'Text(%d=%s)' % (self.type, self.text)
414 def get_voice (channel, music):
415 debug ('channel: ' + str (channel) + '\n')
416 return unthread_notes (music)
419 def __init__ (self, number):
423 def add (self, event):
424 self.events.append (event)
425 def get_voice (self):
427 self.music = self.parse ()
428 return get_voice (self.number, self.music)
435 for e in self.events:
438 if start_quant_clocks:
439 t = quantise_clocks (t, start_quant_clocks)
441 if (e[1][0] == midi.NOTE_OFF
442 or (e[1][0] == midi.NOTE_ON and e[1][2] == 0)):
443 debug ('%d: NOTE OFF: %s' % (t, e[1][1]))
445 debug (' ...treated as OFF')
446 end_note (pitches, notes, t, e[1][1])
448 elif e[1][0] == midi.NOTE_ON:
449 if not pitches.has_key (e[1][1]):
450 debug ('%d: NOTE ON: %s' % (t, e[1][1]))
451 pitches[e[1][1]] = (t, e[1][2])
455 # all include ALL_NOTES_OFF
456 elif (e[1][0] >= midi.ALL_SOUND_OFF
457 and e[1][0] <= midi.POLY_MODE_ON):
459 end_note (pitches, notes, t, i)
461 elif e[1][0] == midi.META_EVENT:
462 if e[1][1] == midi.END_OF_TRACK:
464 end_note (pitches, notes, t, i)
467 elif e[1][1] == midi.SET_TEMPO:
468 (u0, u1, u2) = map (ord, e[1][2])
469 us_per_4 = u2 + 256 * (u1 + 256 * u0)
470 seconds_per_1 = us_per_4 * 4 / 1e6
471 music.append ((t, Tempo (seconds_per_1)))
472 elif e[1][1] == midi.TIME_SIGNATURE:
473 (num, dur, clocks4, count32) = map (ord, e[1][2])
475 music.append ((t, Time (num, den)))
476 elif e[1][1] == midi.KEY_SIGNATURE:
477 (alterations, minor) = map (ord, e[1][2])
480 if alterations < 127:
483 flats = 256 - alterations
485 k = Key (sharps, flats, minor)
486 if not t and global_options.key:
487 # At t == 0, a set --key overrides us
488 k = global_options.key
489 music.append ((t, k))
491 # ugh, must set key while parsing
492 # because Note init uses key
493 # Better do Note.calc () at dump time?
494 global_options.key = k
496 elif (e[1][1] == midi.LYRIC
497 or (global_options.text_lyrics
498 and e[1][1] == midi.TEXT_EVENT)):
499 self.lyrics_p_ = True
501 last_lyric.clocks = t - last_time
502 music.append ((last_time, last_lyric))
504 last_lyric = Text (midi.LYRIC, e[1][2])
506 elif (e[1][1] >= midi.SEQUENCE_NUMBER
507 and e[1][1] <= midi.CUE_POINT):
508 text = Text (e[1][1], e[1][2])
510 music.append ((t, text))
511 if (text.type == midi.SEQUENCE_TRACK_NAME):
512 self.name = text.text
514 if global_options.verbose:
515 sys.stderr.write ("SKIP: %s\n" % `e`)
517 if global_options.verbose:
518 sys.stderr.write ("SKIP: %s\n" % `e`)
521 # last_lyric.clocks = t - last_time
523 last_lyric.clocks = clocks_per_4
524 music.append ((last_time, last_lyric))
529 if i < len (music) and notes[0][0] >= music[i][0]:
532 music.insert (i, notes[0])
536 class Track (Channel):
538 Channel.__init__ (self, None)
541 self.lyrics_p_ = False
542 def _add (self, event):
543 self.events.append (event)
544 def add (self, event, channel=None):
548 self.channels[channel] = self.channels.get (channel, Channel (channel))
549 self.channels[channel].add (event)
550 def get_voices (self):
551 return ([self.get_voice ()]
552 + [self.channels[k].get_voice ()
553 for k in sorted (self.channels.keys ())])
555 def create_track (events):
559 if data[0] > 0x7f and data[0] < 0xf0:
560 channel = data[0] & 0x0f
561 e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
562 track.add (e, channel)
567 def quantise_clocks (clocks, quant):
568 q = int (clocks / quant) * quant
570 for tquant in allowed_tuplet_clocks:
571 if int (clocks / tquant) * tquant == clocks:
573 if 2 * (clocks - q) > quant:
577 def end_note (pitches, notes, t, e):
579 (lt, vel) = pitches[e]
589 if duration_quant_clocks:
590 d = quantise_clocks (d, duration_quant_clocks)
592 d = duration_quant_clocks
595 (lt, Note (d, e, vel)))
600 def unthread_notes (channel):
609 if (e[1].__class__ == Note
610 and ((t == start_busy_t
611 and e[1].clocks + t == end_busy_t)
612 or t >= end_busy_t)):
615 end_busy_t = t + e[1].clocks
616 elif (e[1].__class__ == Time
617 or e[1].__class__ == Key
618 or e[1].__class__ == Text
619 or e[1].__class__ == Tempo):
623 threads.append (thread)
638 def dump_skip (skip, clocks):
639 return skip + Duration (clocks).dump () + ' '
648 if i.__class__ == Note:
653 s = s + dump (notes[0])
654 elif len (notes) > 1:
655 global reference_note
657 s = s + notes[0].dump (dump_dur=False)
660 s = s + i.dump (dump_dur=False)
662 s = s + notes[0].duration.dump () + ' '
666 def dump_bar_line (last_bar_t, t, bar_count):
668 bar_t = time.bar_clocks ()
669 if t - last_bar_t >= bar_t:
670 bar_count = bar_count + (t - last_bar_t) / bar_t
672 if t - last_bar_t == bar_t:
673 s = '\n | %% %(bar_count)d\n ' % locals ()
676 # urg, this will barf at meter changes
677 last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
679 return (s, last_bar_t, bar_count)
682 def dump_voice (thread, skip):
683 global reference_note, time
684 ref = Note (0, 4*12, 0)
685 if not reference_note:
688 ref.duration = reference_note.duration
695 if last_e and last_e[0] == e[0]:
699 chs.append ((last_e[0], ch))
706 chs.append ((last_e[0], ch))
716 i = lines[-1].rfind ('\n') + 1
717 if len (lines[-1][i:]) > LINE_BELL:
722 if bar_max and t > time.bar_clocks () * bar_max:
723 d = time.bar_clocks () * bar_max - last_t
724 lines[-1] = lines[-1] + dump_skip (skip, d)
726 errorport.write ('BUG: time skew')
728 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
731 if bar_max and bar_count > bar_max:
734 lines[-1] = lines[-1] + s
735 lines[-1] = lines[-1] + dump_chord (ch[1])
739 if i.clocks > clocks:
744 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
746 lines[-1] = lines[-1] + s
748 return '\n '.join (lines) + '\n'
750 def number2ascii (i):
755 s = '%c' % (m + ord ('A')) + s
759 def get_track_name (i):
760 return 'track' + number2ascii (i)
762 def get_channel_name (i):
763 return 'channel' + number2ascii (i)
765 def get_voice_name (i, zero_too_p=False):
767 return 'voice' + number2ascii (i)
770 def lst_append (lst, x):
774 def get_voice_layout (average_pitch):
776 for i in range (len (average_pitch)):
777 d[average_pitch[i]] = lst_append (d.get (average_pitch[i], []), i)
778 s = list (reversed (sorted (average_pitch)))
779 non_empty = len (filter (lambda x: x, s))
780 names = ['One', 'Two']
782 names = ['One', 'Three', 'Four', 'Two']
783 layout = map (lambda x: '', range (len (average_pitch)))
784 for i, n in zip (s, names):
793 def dump_track (track, n):
795 track_name = get_track_name (n)
797 average_pitch = track_average_pitch (track)
798 voices = len (filter (lambda x: x, average_pitch[1:]))
799 clef = get_best_clef (average_pitch[0])
803 for channel in track:
805 channel_name = get_channel_name (c)
807 for voice in channel:
808 voice_name = get_voice_name (v)
809 voice_id = track_name + channel_name + voice_name
810 item = voice_first_item (voice)
812 if item and item.__class__ == Note:
814 if global_options.skip:
816 s += '%(voice_id)s = ' % locals ()
817 if not global_options.absolute_pitches:
819 elif item and item.__class__ == Text:
821 s += '%(voice_id)s = \\lyricmode ' % locals ()
824 s += '%(voice_id)s = ' % locals ()
826 if not n and not vv and global_options.key:
827 s += global_options.key.dump ()
828 if average_pitch[vv+1] and voices > 1:
829 vl = get_voice_layout (average_pitch[1:])[vv]
831 s += ' \\voice' + vl + '\n'
833 if not global_options.quiet:
834 warning (_ ('found more than 5 voices on a staff, expect bad output'))
835 s += ' ' + dump_voice (voice, skip)
840 s += '%(track_name)s = <<\n' % locals ()
843 s += clef.dump () + '\n'
847 for channel in track:
849 channel_name = get_channel_name (c)
851 for voice in channel:
852 voice_context_name = get_voice_name (vv, zero_too_p=True)
853 voice_name = get_voice_name (v)
856 voice_id = track_name + channel_name + voice_name
857 item = voice_first_item (voice)
859 if item and item.__class__ == Text:
861 s += ' \\context %(context)s = %(voice_context_name)s \\%(voice_id)s\n' % locals ()
865 def voice_first_item (voice):
867 if (event[1].__class__ == Note
868 or (event[1].__class__ == Text
869 and event[1].type == midi.LYRIC)):
873 def channel_first_item (channel):
874 for voice in channel:
875 first = voice_first_item (voice)
880 def track_first_item (track):
881 for channel in track:
882 first = channel_first_item (channel)
887 def track_average_pitch (track):
891 for channel in track:
892 for voice in channel:
896 if event[1].__class__ == Note:
899 p[v] += event[1].pitch
908 def get_best_clef (average_pitch):
910 if average_pitch <= 3*12:
912 elif average_pitch <= 5*12:
914 elif average_pitch >= 7*12:
919 def __init__ (self, track):
920 self.voices = track.get_voices ()
922 return dump_track (self.voices, i)
924 def convert_midi (in_file, out_file):
928 global clocks_per_1, clocks_per_4, key
929 global start_quant_clocks
930 global duration_quant_clocks
931 global allowed_tuplet_clocks
934 str = open (in_file, 'rb').read ()
935 clocks_max = bar_max * clocks_per_1 * 2
936 midi_dump = midi.parse (str, clocks_max)
938 clocks_per_1 = midi_dump[0][1]
939 clocks_per_4 = clocks_per_1 / 4
942 if global_options.start_quant:
943 start_quant_clocks = clocks_per_1 / global_options.start_quant
945 if global_options.duration_quant:
946 duration_quant_clocks = clocks_per_1 / global_options.duration_quant
948 allowed_tuplet_clocks = []
949 for (dur, num, den) in global_options.allowed_tuplets:
950 allowed_tuplet_clocks.append (clocks_per_1 / dur * num / den)
952 if global_options.verbose:
953 print 'allowed tuplet clocks:', allowed_tuplet_clocks
955 tracks = [create_track (t) for t in midi_dump[1]]
956 # urg, parse all global track events, such as Key first
957 # this fixes key in different voice/staff problem
963 voices = t.get_voices ()
964 if ((t.name and prev and prev.name)
965 and t.name.split (':')[0] == prev.name.split (':')[0]):
966 # staves[-1].voices += voices
967 # all global track events first
968 staves[-1].voices = ([staves[-1].voices[0]]
970 + staves[-1].voices[1:]
973 staves.append (Staff (t))
976 tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, in_file)
988 \remove "Note_heads_engraver"
989 \consists "Completion_heads_engraver"
990 \remove "Rest_engraver"
991 \consists "Completion_rest_engraver"
996 for i in global_options.include_header:
997 s += '\n%% included from %(i)s\n' % locals ()
998 s += open (i).read ()
1003 for i, t in enumerate (staves):
1006 s += '\n\\score {\n <<\n'
1008 control_track = False
1010 for i, staff in enumerate (staves):
1011 track_name = get_track_name (i)
1012 item = track_first_item (staff.voices)
1013 staff_name = track_name
1015 if not i and not item and len (staves) > 1:
1016 control_track = track_name
1018 elif (item and item.__class__ == Note):
1021 s += ' \\context %(context)s=%(staff_name)s \\%(control_track)s\n' % locals ()
1022 elif item and item.__class__ == Text:
1025 s += ' \\context %(context)s=%(staff_name)s \\%(track_name)s\n' % locals ()
1033 if not global_options.quiet:
1034 progress (_ ("%s output to `%s'...") % ('LY', out_file))
1039 handle = open (out_file, 'w')
1045 def get_option_parser ():
1046 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'midi2ly',
1047 description=_ ("Convert %s to LilyPond input.\n") % 'MIDI',
1048 add_help_option=False)
1050 p.add_option ('-a', '--absolute-pitches',
1051 action='store_true',
1052 help=_ ('print absolute pitches'))
1053 p.add_option ('-d', '--duration-quant',
1055 help=_ ('quantise note durations on DUR'))
1056 p.add_option ('-D', '--debug',
1057 action='store_true',
1058 help=_ ('debug printing'))
1059 p.add_option ('-e', '--explicit-durations',
1060 action='store_true',
1061 help=_ ('print explicit durations'))
1062 p.add_option('-h', '--help',
1064 help=_ ('show this help and exit'))
1065 p.add_option('-i', '--include-header',
1066 help=_ ('prepend FILE to output'),
1070 p.add_option('-k', '--key', help=_ ('set key: ALT=+sharps|-flats; MINOR=1'),
1071 metavar=_ ('ALT[:MINOR]'),
1073 p.add_option ('-o', '--output', help=_ ('write output to FILE'),
1076 p.add_option ('-p', '--preview', help=_ ('preview of first 4 bars'),
1077 action='store_true')
1078 p.add_option ('-q', '--quiet',
1079 action="store_true",
1080 help=_ ("suppress progress messages and warnings about excess voices"))
1081 p.add_option ('-s', '--start-quant',help= _ ('quantise note starts on DUR'),
1083 p.add_option ('-S', '--skip',
1084 action = "store_true",
1085 help =_ ("use s instead of r for rests"))
1086 p.add_option ('-t', '--allow-tuplet',
1087 metavar=_ ('DUR*NUM/DEN'),
1089 dest='allowed_tuplets',
1090 help=_ ('allow tuplet durations DUR*NUM/DEN'),
1092 p.add_option ('-V', '--verbose', help=_ ('be verbose'),
1093 action='store_true')
1094 p.version = 'midi2ly (LilyPond) @TOPLEVEL_VERSION@'
1095 p.add_option ('--version',
1097 help=_ ('show version number and exit'))
1098 p.add_option ('-w', '--warranty', help=_ ('show warranty and copyright'),
1099 action='store_true',)
1100 p.add_option ('-x', '--text-lyrics', help=_ ('treat every text as a lyric'),
1101 action='store_true')
1103 p.add_option_group (ly.display_encode (_ ('Examples')),
1105 $ midi2ly --key=-2:1 --duration-quant=32 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
1107 p.add_option_group ('',
1109 _ ('Report bugs via %s')
1110 % 'http://post.gmane.org/post.php'
1111 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
1117 opt_parser = get_option_parser ()
1118 (options, args) = opt_parser.parse_args ()
1120 if options.warranty:
1124 if not args or args[0] == '-':
1125 opt_parser.print_help ()
1126 ly.stderr_write ('\n%s: %s %s\n' % (program_name, _ ('error: '),
1127 _ ('no files specified on command line.')))
1130 if options.duration_quant:
1131 options.duration_quant = int (options.duration_quant)
1134 (alterations, minor) = map (int, (options.key + ':0').split (':'))[0:2]
1137 if alterations >= 0:
1138 sharps = alterations
1140 flats = - alterations
1141 options.key = Key (sharps, flats, minor)
1143 if options.start_quant:
1144 options.start_quant = int (options.start_quant)
1150 options.allowed_tuplets = [map (int, a.replace ('/','*').split ('*'))
1151 for a in options.allowed_tuplets]
1154 sys.stderr.write ('Allowed tuplets: %s\n' % `options.allowed_tuplets`)
1156 global global_options
1157 global_options = options
1162 files = do_options ()
1164 exts = ['.midi', '.mid', '.MID']
1168 g = strip_extension (g, e)
1169 if not os.path.exists (f):
1172 if os.path.exists (n):
1176 if not global_options.output:
1178 outbase = os.path.basename (g)
1179 o = outbase + '-midi.ly'
1180 elif (global_options.output[-1] == os.sep
1181 or os.path.isdir (global_options.output)):
1182 outdir = global_options.output
1183 outbase = os.path.basename (g)
1184 o = os.path.join (outdir, outbase + '-midi.ly')
1186 o = global_options.output
1187 (outdir, outbase) = os.path.split (o)
1189 if outdir and outdir != '.' and not os.path.exists (outdir):
1190 os.mkdir (outdir, 0777)
1194 if __name__ == '__main__':