3 # midi2ly.py -- LilyPond midi import script
5 # This file is part of LilyPond, the GNU music typesetter.
7 # Copyright (C) 1998--2012 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/>.
39 ################################################################
44 scale_steps = [0, 2, 4, 5, 7, 9, 11]
52 start_quant_clocks = 0
54 duration_quant_clocks = 0
55 allowed_tuplet_clocks = []
58 ################################################################
61 program_name = sys.argv[0]
62 program_version = '@TOPLEVEL_VERSION@'
64 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
65 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
67 errorport = sys.stderr
70 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
74 ly.encoded_write (sys.stdout, '''
81 ''' % ( _ ('Copyright (c) %s by') % '1998--2012',
83 _ ('Distributed under terms of the GNU General Public License.'),
84 _ ('It comes with NO WARRANTY.')))
87 ly.encoded_write (errorport, s + '\n')
90 progress (_ ("warning: ") + s)
93 progress (_ ("error: ") + s)
94 raise Exception (_ ("Exiting... "))
97 if global_options.debug:
98 progress ("debug: " + s)
100 def system (cmd, ignore_error = 0):
101 return ly.system (cmd, ignore_error=ignore_error)
103 def strip_extension (f, ext):
104 (p, e) = os.path.splitext (f)
111 allowed_durs = (1, 2, 4, 8, 16, 32, 64, 128)
112 def __init__ (self, clocks):
114 (self.dur, self.num, self.den) = self.dur_num_den (clocks)
116 def dur_num_den (self, clocks):
117 for i in range (len (allowed_tuplet_clocks)):
118 if clocks == allowed_tuplet_clocks[i]:
119 return global_options.allowed_tuplets[i]
121 dur = 0; num = 1; den = 1;
122 g = gcd (clocks, clocks_per_1)
124 (dur, num) = (clocks_per_1 / g, clocks / g)
125 if not dur in self.allowed_durs:
126 dur = 4; num = clocks; den = clocks_per_4
127 return (dur, num, den)
133 elif self.num == 3 and self.dur != 1:
134 s = '%d.' % (self.dur / 2)
136 s = '%d*%d' % (self.dur, self.num)
138 s = '%d*%d/%d' % (self.dur, self.num, self.den)
140 global reference_note
141 reference_note.duration = self
145 def compare (self, other):
146 return self.clocks - other.clocks
155 names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
156 alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
157 alteration_names = ('eses', 'es', '', 'is' , 'isis')
158 def __init__ (self, clocks, pitch, velocity):
160 self.velocity = velocity
163 self.duration = Duration (clocks)
164 (self.octave, self.notename, self.alteration) = self.o_n_a ()
168 # minor scale: la-la (= + 5) '''
170 n = self.names[(self.pitch) % 12]
171 a = self.alterations[(self.pitch) % 12]
173 key = global_options.key
178 a = - self.alterations[(self.pitch) % 12]
181 # By tradition, all scales now consist of a sequence
182 # of 7 notes each with a distinct name, from amongst
183 # a b c d e f g. But, minor scales have a wide
184 # second interval at the top - the 'leading note' is
185 # sharped. (Why? it just works that way! Anything
186 # else doesn't sound as good and isn't as flexible at
187 # saying things. In medieval times, scales only had 6
188 # notes to avoid this problem - the hexachords.)
190 # So, the d minor scale is d e f g a b-flat c-sharp d
191 # - using d-flat for the leading note would skip the
192 # name c and duplicate the name d. Why isn't c-sharp
193 # put in the key signature? Tradition. (It's also
194 # supposedly based on the Pythagorean theory of the
195 # cycle of fifths, but that really only applies to
196 # major scales...) Anyway, g minor is g a b-flat c d
197 # e-flat f-sharp g, and all the other flat minor keys
198 # end up with a natural leading note. And there you
201 # John Sankey <bf250@freenet.carleton.ca>
203 # Let's also do a-minor: a b c d e f gis a
207 o = self.pitch / 12 - 4
211 if (key.sharps == 0 and key.flats == 0
212 and n == 5 and a == -1):
215 elif key.flats == 1 and n == 1 and a == -1:
218 elif key.flats == 2 and n == 4 and a == -1:
221 elif key.sharps == 5 and n == 4 and a == 0:
224 elif key.sharps == 6 and n == 1 and a == 0:
227 elif key.sharps == 7 and n == 5 and a == 0:
231 if key.flats >= 6 and n == 6 and a == 0:
232 n = 0; a = -1; o = o + 1
234 if key.flats >= 7 and n == 2 and a == 0:
238 if key.sharps >= 3 and n == 3 and a == 0:
241 if key.sharps >= 4 and n == 0 and a == 0:
242 n = 6; a = 1; o = o - 1
247 s = chr ((self.notename + 2) % 7 + ord ('a'))
248 return 'Note(%s %s)' % (s, self.duration.dump ())
250 def dump (self, dump_dur=True):
251 global reference_note
252 s = chr ((self.notename + 2) % 7 + ord ('a'))
253 s = s + self.alteration_names[self.alteration + 2]
254 if global_options.absolute_pitches:
257 delta = self.pitch - reference_note.pitch
258 commas = sign (delta) * (abs (delta) / 12)
260 * (self.notename - reference_note.notename) + 7)
262 or ((self.notename == reference_note.notename)
263 and (abs (delta) > 4) and (abs (delta) < 12))):
264 commas = commas + sign (delta)
269 s = s + "," * -commas
272 and self.duration.compare (reference_note.duration))
273 or global_options.explicit_durations):
274 s = s + self.duration.dump ()
276 reference_note = self
283 def __init__ (self, num, den):
288 def bar_clocks (self):
289 return clocks_per_1 * self.num / self.den
292 return 'Time(%d/%d)' % (self.num, self.den)
297 return '\n ' + '\\time %d/%d ' % (self.num, self.den) + '\n '
300 def __init__ (self, seconds_per_1):
302 self.seconds_per_1 = seconds_per_1
305 return 'Tempo(%d)' % self.bpm ()
308 return 4 * 60 / self.seconds_per_1
311 return '\n ' + '\\tempo 4 = %d ' % (self.bpm ()) + '\n '
314 clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
315 def __init__ (self, type):
319 return 'Clef(%s)' % self.clefs[self.type]
322 return '\n \\clef %s\n ' % self.clefs[self.type]
325 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
326 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
328 def __init__ (self, sharps, flats, minor):
335 global_options.key = self
338 if self.sharps and self.flats:
342 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
344 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
347 name = chr ((k + 2) % 7 + ord ('a'))
349 name = chr ((k + 2) % 7 + ord ('a'))
351 # fis cis gis dis ais eis bis
352 sharps = (2, 4, 6, 1, 3, 5, 7)
353 # bes es as des ges ces fes
354 flats = (6, 4, 2, 7, 5, 3, 1)
357 if flats[k] <= self.flats:
360 if sharps[k] <= self.sharps:
364 name = name + Note.alteration_names[a + 2]
372 return '\n\n ' + s + '\n '
380 'SEQUENCE_TRACK_NAME',
386 def __init__ (self, type, text):
392 # urg, we should be sure that we're in a lyrics staff
394 if self.type == midi.LYRIC:
395 s = '"%s"' % self.text
396 d = Duration (self.clocks)
397 if (global_options.explicit_durations
398 or d.compare (reference_note.duration)):
399 s = s + Duration (self.clocks).dump ()
401 elif (self.text.strip ()
402 and self.type == midi.SEQUENCE_TRACK_NAME
403 and not self.text == 'control track'
404 and not self.track.lyrics_p_):
405 text = self.text.replace ('(MIDI)', '').strip ()
407 s = '\n \\set Staff.instrumentName = "%(text)s"\n ' % locals ()
408 elif self.text.strip ():
409 s = '\n % [' + self.text_types[self.type] + '] ' + self.text + '\n '
413 return 'Text(%d=%s)' % (self.type, self.text)
415 def get_voice (channel, music):
416 debug ('channel: ' + str (channel) + '\n')
417 return unthread_notes (music)
420 def __init__ (self, number):
424 def add (self, event):
425 self.events.append (event)
426 def get_voice (self):
428 self.music = self.parse ()
429 return get_voice (self.number, self.music)
436 for e in self.events:
439 if start_quant_clocks:
440 t = quantise_clocks (t, start_quant_clocks)
442 if (e[1][0] == midi.NOTE_OFF
443 or (e[1][0] == midi.NOTE_ON and e[1][2] == 0)):
444 debug ('%d: NOTE OFF: %s' % (t, e[1][1]))
446 debug (' ...treated as OFF')
447 end_note (pitches, notes, t, e[1][1])
449 elif e[1][0] == midi.NOTE_ON:
450 if not pitches.has_key (e[1][1]):
451 debug ('%d: NOTE ON: %s' % (t, e[1][1]))
452 pitches[e[1][1]] = (t, e[1][2])
456 # all include ALL_NOTES_OFF
457 elif (e[1][0] >= midi.ALL_SOUND_OFF
458 and e[1][0] <= midi.POLY_MODE_ON):
460 end_note (pitches, notes, t, i)
462 elif e[1][0] == midi.META_EVENT:
463 if e[1][1] == midi.END_OF_TRACK:
465 end_note (pitches, notes, t, i)
468 elif e[1][1] == midi.SET_TEMPO:
469 (u0, u1, u2) = map (ord, e[1][2])
470 us_per_4 = u2 + 256 * (u1 + 256 * u0)
471 seconds_per_1 = us_per_4 * 4 / 1e6
472 music.append ((t, Tempo (seconds_per_1)))
473 elif e[1][1] == midi.TIME_SIGNATURE:
474 (num, dur, clocks4, count32) = map (ord, e[1][2])
476 music.append ((t, Time (num, den)))
477 elif e[1][1] == midi.KEY_SIGNATURE:
478 (alterations, minor) = map (ord, e[1][2])
481 if alterations < 127:
484 flats = 256 - alterations
486 k = Key (sharps, flats, minor)
487 if not t and global_options.key:
488 # At t == 0, a set --key overrides us
489 k = global_options.key
490 music.append ((t, k))
492 # ugh, must set key while parsing
493 # because Note init uses key
494 # Better do Note.calc () at dump time?
495 global_options.key = k
497 elif (e[1][1] == midi.LYRIC
498 or (global_options.text_lyrics
499 and e[1][1] == midi.TEXT_EVENT)):
500 self.lyrics_p_ = True
502 last_lyric.clocks = t - last_time
503 music.append ((last_time, last_lyric))
505 last_lyric = Text (midi.LYRIC, e[1][2])
507 elif (e[1][1] >= midi.SEQUENCE_NUMBER
508 and e[1][1] <= midi.CUE_POINT):
509 text = Text (e[1][1], e[1][2])
511 music.append ((t, text))
512 if (text.type == midi.SEQUENCE_TRACK_NAME):
513 self.name = text.text
515 if global_options.verbose:
516 sys.stderr.write ("SKIP: %s\n" % `e`)
518 if global_options.verbose:
519 sys.stderr.write ("SKIP: %s\n" % `e`)
522 # last_lyric.clocks = t - last_time
524 last_lyric.clocks = clocks_per_4
525 music.append ((last_time, last_lyric))
530 if i < len (music) and notes[0][0] >= music[i][0]:
533 music.insert (i, notes[0])
537 class Track (Channel):
539 Channel.__init__ (self, None)
542 self.lyrics_p_ = False
543 def _add (self, event):
544 self.events.append (event)
545 def add (self, event, channel=None):
549 self.channels[channel] = self.channels.get (channel, Channel (channel))
550 self.channels[channel].add (event)
551 def get_voices (self):
552 return ([self.get_voice ()]
553 + [self.channels[k].get_voice ()
554 for k in sorted (self.channels.keys ())])
556 def create_track (events):
560 if data[0] > 0x7f and data[0] < 0xf0:
561 channel = data[0] & 0x0f
562 e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
563 track.add (e, channel)
568 def quantise_clocks (clocks, quant):
569 q = int (clocks / quant) * quant
571 for tquant in allowed_tuplet_clocks:
572 if int (clocks / tquant) * tquant == clocks:
574 if 2 * (clocks - q) > quant:
578 def end_note (pitches, notes, t, e):
580 (lt, vel) = pitches[e]
590 if duration_quant_clocks:
591 d = quantise_clocks (d, duration_quant_clocks)
593 d = duration_quant_clocks
596 (lt, Note (d, e, vel)))
601 def unthread_notes (channel):
610 if (e[1].__class__ == Note
611 and ((t == start_busy_t
612 and e[1].clocks + t == end_busy_t)
613 or t >= end_busy_t)):
616 end_busy_t = t + e[1].clocks
617 elif (e[1].__class__ == Time
618 or e[1].__class__ == Key
619 or e[1].__class__ == Text
620 or e[1].__class__ == Tempo):
624 threads.append (thread)
639 def dump_skip (skip, clocks):
640 return skip + Duration (clocks).dump () + ' '
649 if i.__class__ == Note:
654 s = s + dump (notes[0])
655 elif len (notes) > 1:
656 global reference_note
658 s = s + notes[0].dump (dump_dur=False)
661 s = s + i.dump (dump_dur=False)
663 s = s + notes[0].duration.dump () + ' '
667 def dump_bar_line (last_bar_t, t, bar_count):
669 bar_t = time.bar_clocks ()
670 if t - last_bar_t >= bar_t:
671 bar_count = bar_count + (t - last_bar_t) / bar_t
673 if t - last_bar_t == bar_t:
674 s = '\n | %% %(bar_count)d\n ' % locals ()
677 # urg, this will barf at meter changes
678 last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
680 return (s, last_bar_t, bar_count)
683 def dump_voice (thread, skip):
684 global reference_note, time
685 ref = Note (0, 4*12, 0)
686 if not reference_note:
689 ref.duration = reference_note.duration
696 if last_e and last_e[0] == e[0]:
700 chs.append ((last_e[0], ch))
707 chs.append ((last_e[0], ch))
717 i = lines[-1].rfind ('\n') + 1
718 if len (lines[-1][i:]) > LINE_BELL:
723 if bar_max and t > time.bar_clocks () * bar_max:
724 d = time.bar_clocks () * bar_max - last_t
725 lines[-1] = lines[-1] + dump_skip (skip, d)
727 errorport.write ('BUG: time skew')
729 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
732 if bar_max and bar_count > bar_max:
735 lines[-1] = lines[-1] + s
736 lines[-1] = lines[-1] + dump_chord (ch[1])
740 if i.clocks > clocks:
745 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
747 lines[-1] = lines[-1] + s
749 return '\n '.join (lines) + '\n'
751 def number2ascii (i):
756 s = '%c' % (m + ord ('A')) + s
760 def get_track_name (i):
761 return 'track' + number2ascii (i)
763 def get_channel_name (i):
764 return 'channel' + number2ascii (i)
766 def get_voice_name (i, zero_too_p=False):
768 return 'voice' + number2ascii (i)
771 def lst_append (lst, x):
775 def get_voice_layout (average_pitch):
777 for i in range (len (average_pitch)):
778 d[average_pitch[i]] = lst_append (d.get (average_pitch[i], []), i)
779 s = list (reversed (sorted (average_pitch)))
780 non_empty = len (filter (lambda x: x, s))
781 names = ['One', 'Two']
783 names = ['One', 'Three', 'Four', 'Two']
784 layout = map (lambda x: '', range (len (average_pitch)))
785 for i, n in zip (s, names):
794 def dump_track (track, n):
796 track_name = get_track_name (n)
798 average_pitch = track_average_pitch (track)
799 voices = len (filter (lambda x: x, average_pitch[1:]))
800 clef = get_best_clef (average_pitch[0])
804 for channel in track:
806 channel_name = get_channel_name (c)
808 for voice in channel:
809 voice_name = get_voice_name (v)
810 voice_id = track_name + channel_name + voice_name
811 item = voice_first_item (voice)
813 if item and item.__class__ == Note:
815 if global_options.skip:
817 s += '%(voice_id)s = ' % locals ()
818 if not global_options.absolute_pitches:
820 elif item and item.__class__ == Text:
822 s += '%(voice_id)s = \\lyricmode ' % locals ()
825 s += '%(voice_id)s = ' % locals ()
827 if not n and not vv and global_options.key:
828 s += global_options.key.dump ()
829 if average_pitch[vv+1] and voices > 1:
830 vl = get_voice_layout (average_pitch[1:])[vv]
832 s += ' \\voice' + vl + '\n'
834 if not global_options.quiet:
835 warning (_ ('found more than 5 voices on a staff, expect bad output'))
836 s += ' ' + dump_voice (voice, skip)
841 s += '%(track_name)s = <<\n' % locals ()
844 s += clef.dump () + '\n'
848 for channel in track:
850 channel_name = get_channel_name (c)
852 for voice in channel:
853 voice_context_name = get_voice_name (vv, zero_too_p=True)
854 voice_name = get_voice_name (v)
857 voice_id = track_name + channel_name + voice_name
858 item = voice_first_item (voice)
860 if item and item.__class__ == Text:
862 s += ' \\context %(context)s = %(voice_context_name)s \\%(voice_id)s\n' % locals ()
866 def voice_first_item (voice):
868 if (event[1].__class__ == Note
869 or (event[1].__class__ == Text
870 and event[1].type == midi.LYRIC)):
874 def channel_first_item (channel):
875 for voice in channel:
876 first = voice_first_item (voice)
881 def track_first_item (track):
882 for channel in track:
883 first = channel_first_item (channel)
888 def track_average_pitch (track):
892 for channel in track:
893 for voice in channel:
897 if event[1].__class__ == Note:
900 p[v] += event[1].pitch
909 def get_best_clef (average_pitch):
911 if average_pitch <= 3*12:
913 elif average_pitch <= 5*12:
915 elif average_pitch >= 7*12:
920 def __init__ (self, track):
921 self.voices = track.get_voices ()
923 return dump_track (self.voices, i)
925 def convert_midi (in_file, out_file):
926 global clocks_per_1, clocks_per_4, key
927 global start_quant_clocks
928 global duration_quant_clocks
929 global allowed_tuplet_clocks
932 str = open (in_file, 'rb').read ()
933 clocks_max = bar_max * clocks_per_1 * 2
934 midi_dump = midi.parse (str, clocks_max)
936 clocks_per_1 = midi_dump[0][1]
937 clocks_per_4 = clocks_per_1 / 4
940 if global_options.start_quant:
941 start_quant_clocks = clocks_per_1 / global_options.start_quant
943 if global_options.duration_quant:
944 duration_quant_clocks = clocks_per_1 / global_options.duration_quant
946 allowed_tuplet_clocks = []
947 for (dur, num, den) in global_options.allowed_tuplets:
948 allowed_tuplet_clocks.append (clocks_per_1 / dur * num / den)
950 if global_options.verbose:
951 print 'allowed tuplet clocks:', allowed_tuplet_clocks
953 tracks = [create_track (t) for t in midi_dump[1]]
954 # urg, parse all global track events, such as Key first
955 # this fixes key in different voice/staff problem
961 voices = t.get_voices ()
962 if ((t.name and prev and prev.name)
963 and t.name.split (':')[0] == prev.name.split (':')[0]):
964 # staves[-1].voices += voices
965 # all global track events first
966 staves[-1].voices = ([staves[-1].voices[0]]
968 + staves[-1].voices[1:]
971 staves.append (Staff (t))
974 tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, in_file)
986 \remove "Note_heads_engraver"
987 \consists "Completion_heads_engraver"
988 \remove "Rest_engraver"
989 \consists "Completion_rest_engraver"
994 for i in global_options.include_header:
995 s += '\n%% included from %(i)s\n' % locals ()
996 s += open (i).read ()
1001 for i, t in enumerate (staves):
1004 s += '\n\\score {\n <<\n'
1006 control_track = False
1008 for i, staff in enumerate (staves):
1009 track_name = get_track_name (i)
1010 item = track_first_item (staff.voices)
1011 staff_name = track_name
1013 if not i and not item and len (staves) > 1:
1014 control_track = track_name
1016 elif (item and item.__class__ == Note):
1019 s += ' \\context %(context)s=%(staff_name)s \\%(control_track)s\n' % locals ()
1020 elif item and item.__class__ == Text:
1023 s += ' \\context %(context)s=%(staff_name)s \\%(track_name)s\n' % locals ()
1031 if not global_options.quiet:
1032 progress (_ ("%s output to `%s'...") % ('LY', out_file))
1037 handle = open (out_file, 'w')
1043 def get_option_parser ():
1044 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'midi2ly',
1045 description=_ ("Convert %s to LilyPond input.\n") % 'MIDI',
1046 add_help_option=False)
1048 p.add_option ('-a', '--absolute-pitches',
1049 action='store_true',
1050 help=_ ('print absolute pitches'))
1051 p.add_option ('-d', '--duration-quant',
1053 help=_ ('quantise note durations on DUR'))
1054 p.add_option ('-D', '--debug',
1055 action='store_true',
1056 help=_ ('debug printing'))
1057 p.add_option ('-e', '--explicit-durations',
1058 action='store_true',
1059 help=_ ('print explicit durations'))
1060 p.add_option('-h', '--help',
1062 help=_ ('show this help and exit'))
1063 p.add_option('-i', '--include-header',
1064 help=_ ('prepend FILE to output'),
1068 p.add_option('-k', '--key', help=_ ('set key: ALT=+sharps|-flats; MINOR=1'),
1069 metavar=_ ('ALT[:MINOR]'),
1071 p.add_option ('-o', '--output', help=_ ('write output to FILE'),
1074 p.add_option ('-p', '--preview', help=_ ('preview of first 4 bars'),
1075 action='store_true')
1076 p.add_option ('-q', '--quiet',
1077 action="store_true",
1078 help=_ ("suppress progress messages and warnings about excess voices"))
1079 p.add_option ('-s', '--start-quant',help= _ ('quantise note starts on DUR'),
1081 p.add_option ('-S', '--skip',
1082 action = "store_true",
1083 help =_ ("use s instead of r for rests"))
1084 p.add_option ('-t', '--allow-tuplet',
1085 metavar=_ ('DUR*NUM/DEN'),
1087 dest='allowed_tuplets',
1088 help=_ ('allow tuplet durations DUR*NUM/DEN'),
1090 p.add_option ('-V', '--verbose', help=_ ('be verbose'),
1091 action='store_true')
1092 p.version = 'midi2ly (LilyPond) @TOPLEVEL_VERSION@'
1093 p.add_option ('--version',
1095 help=_ ('show version number and exit'))
1096 p.add_option ('-w', '--warranty', help=_ ('show warranty and copyright'),
1097 action='store_true',)
1098 p.add_option ('-x', '--text-lyrics', help=_ ('treat every text as a lyric'),
1099 action='store_true')
1101 p.add_option_group (ly.display_encode (_ ('Examples')),
1103 $ midi2ly --key=-2:1 --duration-quant=32 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
1105 p.add_option_group ('',
1107 _ ('Report bugs via %s')
1108 % 'http://post.gmane.org/post.php'
1109 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
1115 opt_parser = get_option_parser ()
1116 (options, args) = opt_parser.parse_args ()
1118 if options.warranty:
1122 if not args or args[0] == '-':
1123 opt_parser.print_help ()
1124 ly.stderr_write ('\n%s: %s %s\n' % (program_name, _ ('error: '),
1125 _ ('no files specified on command line.')))
1128 if options.duration_quant:
1129 options.duration_quant = int (options.duration_quant)
1132 (alterations, minor) = map (int, (options.key + ':0').split (':'))[0:2]
1135 if alterations >= 0:
1136 sharps = alterations
1138 flats = - alterations
1139 options.key = Key (sharps, flats, minor)
1141 if options.start_quant:
1142 options.start_quant = int (options.start_quant)
1148 options.allowed_tuplets = [map (int, a.replace ('/','*').split ('*'))
1149 for a in options.allowed_tuplets]
1152 sys.stderr.write ('Allowed tuplets: %s\n' % `options.allowed_tuplets`)
1154 global global_options
1155 global_options = options
1160 files = do_options ()
1162 exts = ['.midi', '.mid', '.MID']
1166 g = strip_extension (g, e)
1167 if not os.path.exists (f):
1170 if os.path.exists (n):
1174 if not global_options.output:
1176 outbase = os.path.basename (g)
1177 o = outbase + '-midi.ly'
1178 elif (global_options.output[-1] == os.sep
1179 or os.path.isdir (global_options.output)):
1180 outdir = global_options.output
1181 outbase = os.path.basename (g)
1182 o = os.path.join (outdir, outbase + '-midi.ly')
1184 o = global_options.output
1185 (outdir, outbase) = os.path.split (o)
1187 if outdir and outdir != '.' and not os.path.exists (outdir):
1188 os.mkdir (outdir, 0777)
1192 if __name__ == '__main__':