Midi2ly: bug fix for --allow-tuplets.
[lilypond/patrick.git] / scripts / midi2ly.py
blobafe5c5af3550b3c8a4f106acebc28df91d17ad52
1 #!@TARGET_PYTHON@
3 # midi2ly.py -- LilyPond midi import script
5 # This file is part of LilyPond, the GNU music typesetter.
7 # Copyright (C) 1998--2011 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/>.
24 '''
25 TODO:
26 * test on weird and unquantised midi input (lily-devel)
27 * update doc and manpage
29 * simply insert clef changes whenever too many ledger lines
30 [to avoid tex capacity exceeded]
31 * do not ever quant skips
32 * better lyrics handling
33 * [see if it is feasible to] move ly-classes to library for use in
34 other converters, while leaving midi specific stuff here
35 '''
37 import os
38 import sys
40 """
41 @relocate-preamble@
42 """
44 import midi
45 import lilylib as ly
46 global _;_=ly._
48 ################################################################
49 ## CONSTANTS
52 LINE_BELL = 60
53 scale_steps = [0, 2, 4, 5, 7, 9, 11]
54 global_options = None
56 clocks_per_1 = 1536
57 clocks_per_4 = 0
59 time = 0
60 reference_note = 0
61 start_quant_clocks = 0
63 duration_quant_clocks = 0
64 allowed_tuplet_clocks = []
65 bar_max = 0
67 ################################################################
70 program_name = sys.argv[0]
71 program_version = '@TOPLEVEL_VERSION@'
73 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
74 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
76 errorport = sys.stderr
78 def identify ():
79 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
81 def warranty ():
82 identify ()
83 ly.encoded_write (sys.stdout, '''
90 ''' % ( _ ('Copyright (c) %s by') % '1998--2011',
91 '\n '.join (authors),
92 _ ('Distributed under terms of the GNU General Public License.'),
93 _ ('It comes with NO WARRANTY.')))
95 def progress (s):
96 ly.encoded_write (errorport, s + '\n')
98 def warning (s):
99 progress (_ ("warning: ") + s)
101 def error (s):
102 progress (_ ("error: ") + s)
103 raise Exception (_ ("Exiting... "))
105 def system (cmd, ignore_error = 0):
106 return ly.system (cmd, ignore_error=ignore_error)
108 def strip_extension (f, ext):
109 (p, e) = os.path.splitext (f)
110 if e == ext:
111 e = ''
112 return p + e
115 class Duration:
116 allowed_durs = (1, 2, 4, 8, 16, 32, 64, 128)
117 def __init__ (self, clocks):
118 self.clocks = clocks
119 if clocks <= 0:
120 self.clocks = duration_quant_clocks
121 (self.dur, self.num, self.den) = self.dur_num_den (clocks)
123 def dur_num_den (self, clocks):
124 for i in range (len (allowed_tuplet_clocks)):
125 if clocks == allowed_tuplet_clocks[i]:
126 return global_options.allowed_tuplets[i]
128 dur = 0; num = 1; den = 1;
129 g = gcd (clocks, clocks_per_1)
130 if g:
131 (dur, num) = (clocks_per_1 / g, clocks / g)
132 if not dur in self.allowed_durs:
133 dur = 4; num = clocks; den = clocks_per_4
134 return (dur, num, den)
136 def dump (self):
137 if self.den == 1:
138 if self.num == 1:
139 s = '%d' % self.dur
140 elif self.num == 3 and self.dur != 1:
141 s = '%d.' % (self.dur / 2)
142 else:
143 s = '%d*%d' % (self.dur, self.num)
144 else:
145 s = '%d*%d/%d' % (self.dur, self.num, self.den)
147 global reference_note
148 reference_note.duration = self
150 return s
152 def compare (self, other):
153 return self.clocks - other.clocks
155 def sign (x):
156 if x >= 0:
157 return 1
158 else:
159 return -1
161 class Note:
162 names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
163 alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
164 alteration_names = ('eses', 'es', '', 'is' , 'isis')
165 def __init__ (self, clocks, pitch, velocity):
166 self.pitch = pitch
167 self.velocity = velocity
168 # hmm
169 self.clocks = clocks
170 self.duration = Duration (clocks)
171 (self.octave, self.notename, self.alteration) = self.o_n_a ()
173 def o_n_a (self):
174 # major scale: do-do
175 # minor scale: la-la (= + 5) '''
177 n = self.names[(self.pitch) % 12]
178 a = self.alterations[(self.pitch) % 12]
180 if a and global_options.key.flats:
181 a = - self.alterations[(self.pitch) % 12]
182 n = (n - a) % 7
184 # By tradition, all scales now consist of a sequence
185 # of 7 notes each with a distinct name, from amongst
186 # a b c d e f g. But, minor scales have a wide
187 # second interval at the top - the 'leading note' is
188 # sharped. (Why? it just works that way! Anything
189 # else doesn't sound as good and isn't as flexible at
190 # saying things. In medieval times, scales only had 6
191 # notes to avoid this problem - the hexachords.)
193 # So, the d minor scale is d e f g a b-flat c-sharp d
194 # - using d-flat for the leading note would skip the
195 # name c and duplicate the name d. Why isn't c-sharp
196 # put in the key signature? Tradition. (It's also
197 # supposedly based on the Pythagorean theory of the
198 # cycle of fifths, but that really only applies to
199 # major scales...) Anyway, g minor is g a b-flat c d
200 # e-flat f-sharp g, and all the other flat minor keys
201 # end up with a natural leading note. And there you
202 # have it.
204 # John Sankey <bf250@freenet.carleton.ca>
206 # Let's also do a-minor: a b c d e f gis a
208 # --jcn
210 o = self.pitch / 12 - 4
212 key = global_options.key
213 if key.minor:
214 # as -> gis
215 if (key.sharps == 0 and key.flats == 0
216 and n == 5 and a == -1):
217 n = 4; a = 1
218 # des -> cis
219 elif key.flats == 1 and n == 1 and a == -1:
220 n = 0; a = 1
221 # ges -> fis
222 elif key.flats == 2 and n == 4 and a == -1:
223 n = 3; a = 1
224 # g -> fisis
225 elif key.sharps == 5 and n == 4 and a == 0:
226 n = 3; a = 2
227 # d -> cisis
228 elif key.sharps == 6 and n == 1 and a == 0:
229 n = 0; a = 2
230 # a -> gisis
231 elif key.sharps == 7 and n == 5 and a == 0:
232 n = 4; a = 2
234 # b -> ces
235 if key.flats >= 6 and n == 6 and a == 0:
236 n = 0; a = -1; o = o + 1
237 # e -> fes
238 if key.flats >= 7 and n == 2 and a == 0:
239 n = 3; a = -1
241 # f -> eis
242 if key.sharps >= 3 and n == 3 and a == 0:
243 n = 2; a = 1
244 # c -> bis
245 if key.sharps >= 4 and n == 0 and a == 0:
246 n = 6; a = 1; o = o - 1
248 return (o, n, a)
250 def __repr__ (self):
251 s = chr ((self.notename + 2) % 7 + ord ('a'))
252 return 'Note(%s %s)' % (s, self.duration.dump ())
254 def dump (self, dump_dur = 1):
255 global reference_note
256 s = chr ((self.notename + 2) % 7 + ord ('a'))
257 s = s + self.alteration_names[self.alteration + 2]
258 if global_options.absolute_pitches:
259 commas = self.octave
260 else:
261 delta = self.pitch - reference_note.pitch
262 commas = sign (delta) * (abs (delta) / 12)
263 if (((sign (delta)
264 * (self.notename - reference_note.notename) + 7)
265 % 7 >= 4)
266 or ((self.notename == reference_note.notename)
267 and (abs (delta) > 4) and (abs (delta) < 12))):
268 commas = commas + sign (delta)
270 if commas > 0:
271 s = s + "'" * commas
272 elif commas < 0:
273 s = s + "," * -commas
275 ## FIXME: compile fix --jcn
276 if (dump_dur and (global_options.explicit_durations
277 or self.duration.compare (reference_note.duration))):
278 s = s + self.duration.dump ()
280 reference_note = self
282 # TODO: move space
283 return s + ' '
286 class Time:
287 def __init__ (self, num, den):
288 self.clocks = 0
289 self.num = num
290 self.den = den
292 def bar_clocks (self):
293 return clocks_per_1 * self.num / self.den
295 def __repr__ (self):
296 return 'Time(%d/%d)' % (self.num, self.den)
298 def dump (self):
299 global time
300 time = self
301 return '\n ' + '\\time %d/%d ' % (self.num, self.den) + '\n '
303 class Tempo:
304 def __init__ (self, seconds_per_1):
305 self.clocks = 0
306 self.seconds_per_1 = seconds_per_1
308 def __repr__ (self):
309 return 'Tempo(%d)' % self.bpm ()
311 def bpm (self):
312 return 4 * 60 / self.seconds_per_1
314 def dump (self):
315 return '\n ' + '\\tempo 4 = %d ' % (self.bpm ()) + '\n '
317 class Clef:
318 clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
319 def __init__ (self, type):
320 self.type = type
322 def __repr__ (self):
323 return 'Clef(%s)' % self.clefs[self.type]
325 def dump (self):
326 return '\n \\clef %s\n ' % self.clefs[self.type]
328 class Key:
329 key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
330 key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
332 def __init__ (self, sharps, flats, minor):
333 self.clocks = 0
334 self.flats = flats
335 self.sharps = sharps
336 self.minor = minor
338 def dump (self):
339 global_options.key = self
341 s = ''
342 if self.sharps and self.flats:
343 pass
344 else:
345 if self.flats:
346 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
347 else:
348 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
350 if not self.minor:
351 name = chr ((k + 2) % 7 + ord ('a'))
352 else:
353 name = chr ((k + 2) % 7 + ord ('a'))
355 # fis cis gis dis ais eis bis
356 sharps = (2, 4, 6, 1, 3, 5, 7)
357 # bes es as des ges ces fes
358 flats = (6, 4, 2, 7, 5, 3, 1)
359 a = 0
360 if self.flats:
361 if flats[k] <= self.flats:
362 a = -1
363 else:
364 if sharps[k] <= self.sharps:
365 a = 1
367 if a:
368 name = name + Note.alteration_names[a + 2]
370 s = '\\key ' + name
371 if self.minor:
372 s = s + ' \\minor'
373 else:
374 s = s + ' \\major'
376 return '\n\n ' + s + '\n '
379 class Text:
380 text_types = (
381 'SEQUENCE_NUMBER',
382 'TEXT_EVENT',
383 'COPYRIGHT_NOTICE',
384 'SEQUENCE_TRACK_NAME',
385 'INSTRUMENT_NAME',
386 'LYRIC',
387 'MARKER',
388 'CUE_POINT',)
390 def __init__ (self, type, text):
391 self.clocks = 0
392 self.type = type
393 self.text = text
395 def dump (self):
396 # urg, we should be sure that we're in a lyrics staff
397 if self.type == midi.LYRIC:
398 s = '"%s"' % self.text
399 d = Duration (self.clocks)
400 if (global_options.explicit_durations
401 or d.compare (reference_note.duration)):
402 s = s + Duration (self.clocks).dump ()
403 s = s + ' '
404 else:
405 s = '\n % [' + self.text_types[self.type] + '] ' + self.text + '\n '
406 return s
408 def __repr__ (self):
409 return 'Text(%d=%s)' % (self.type, self.text)
413 def split_track (track):
414 chs = {}
415 for i in range (16):
416 chs[i] = []
418 for e in track:
419 data = list (e[1])
420 if data[0] > 0x7f and data[0] < 0xf0:
421 c = data[0] & 0x0f
422 e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
423 chs[c].append (e)
424 else:
425 chs[0].append (e)
427 for i in range (16):
428 if chs[i] == []:
429 del chs[i]
431 threads = []
432 for v in chs.values ():
433 events = events_on_channel (v)
434 thread = unthread_notes (events)
435 if len (thread):
436 threads.append (thread)
437 return threads
440 def quantise_clocks (clocks, quant):
441 q = int (clocks / quant) * quant
442 if q != clocks:
443 for tquant in allowed_tuplet_clocks:
444 if int (clocks / tquant) * tquant == clocks:
445 return clocks
446 if 2 * (clocks - q) > quant:
447 q = q + quant
448 return q
450 def end_note (pitches, notes, t, e):
451 try:
452 (lt, vel) = pitches[e]
453 del pitches[e]
455 i = len (notes) - 1
456 while i > 0:
457 if notes[i][0] > lt:
458 i = i -1
459 else:
460 break
461 d = t - lt
462 if duration_quant_clocks:
463 d = quantise_clocks (d, duration_quant_clocks)
464 if not d:
465 d = duration_quant_clocks
467 notes.insert (i + 1,
468 (lt, Note (d, e, vel)))
470 except KeyError:
471 pass
473 def events_on_channel (channel):
474 pitches = {}
476 notes = []
477 events = []
478 last_lyric = 0
479 last_time = 0
480 for e in channel:
481 t = e[0]
483 if start_quant_clocks:
484 t = quantise_clocks (t, start_quant_clocks)
487 if (e[1][0] == midi.NOTE_OFF
488 or (e[1][0] == midi.NOTE_ON and e[1][2] == 0)):
489 end_note (pitches, notes, t, e[1][1])
491 elif e[1][0] == midi.NOTE_ON:
492 if not pitches.has_key (e[1][1]):
493 pitches[e[1][1]] = (t, e[1][2])
495 # all include ALL_NOTES_OFF
496 elif (e[1][0] >= midi.ALL_SOUND_OFF
497 and e[1][0] <= midi.POLY_MODE_ON):
498 for i in pitches:
499 end_note (pitches, notes, t, i)
501 elif e[1][0] == midi.META_EVENT:
502 if e[1][1] == midi.END_OF_TRACK:
503 for i in pitches:
504 end_note (pitches, notes, t, i)
505 break
507 elif e[1][1] == midi.SET_TEMPO:
508 (u0, u1, u2) = map (ord, e[1][2])
509 us_per_4 = u2 + 256 * (u1 + 256 * u0)
510 seconds_per_1 = us_per_4 * 4 / 1e6
511 events.append ((t, Tempo (seconds_per_1)))
512 elif e[1][1] == midi.TIME_SIGNATURE:
513 (num, dur, clocks4, count32) = map (ord, e[1][2])
514 den = 2 ** dur
515 events.append ((t, Time (num, den)))
516 elif e[1][1] == midi.KEY_SIGNATURE:
517 (alterations, minor) = map (ord, e[1][2])
518 sharps = 0
519 flats = 0
520 if alterations < 127:
521 sharps = alterations
522 else:
523 flats = 256 - alterations
525 k = Key (sharps, flats, minor)
526 events.append ((t, k))
528 # ugh, must set key while parsing
529 # because Note init uses key
530 # Better do Note.calc () at dump time?
531 global_options.key = k
533 elif (e[1][1] == midi.LYRIC
534 or (global_options.text_lyrics and e[1][1] == midi.TEXT_EVENT)):
535 if last_lyric:
536 last_lyric.clocks = t - last_time
537 events.append ((last_time, last_lyric))
538 last_time = t
539 last_lyric = Text (midi.LYRIC, e[1][2])
541 elif (e[1][1] >= midi.SEQUENCE_NUMBER
542 and e[1][1] <= midi.CUE_POINT):
543 events.append ((t, Text (e[1][1], e[1][2])))
544 else:
545 if global_options.verbose:
546 sys.stderr.write ("SKIP: %s\n" % `e`)
547 pass
548 else:
549 if global_options.verbose:
550 sys.stderr.write ("SKIP: %s\n" % `e`)
551 pass
553 if last_lyric:
554 # last_lyric.clocks = t - last_time
555 # hmm
556 last_lyric.clocks = clocks_per_4
557 events.append ((last_time, last_lyric))
558 last_lyric = 0
560 i = 0
561 while len (notes):
562 if i < len (events) and notes[0][0] >= events[i][0]:
563 i = i + 1
564 else:
565 events.insert (i, notes[0])
566 del notes[0]
567 return events
569 def unthread_notes (channel):
570 threads = []
571 while channel:
572 thread = []
573 end_busy_t = 0
574 start_busy_t = 0
575 todo = []
576 for e in channel:
577 t = e[0]
578 if (e[1].__class__ == Note
579 and ((t == start_busy_t
580 and e[1].clocks + t == end_busy_t)
581 or t >= end_busy_t)):
582 thread.append (e)
583 start_busy_t = t
584 end_busy_t = t + e[1].clocks
585 elif (e[1].__class__ == Time
586 or e[1].__class__ == Key
587 or e[1].__class__ == Text
588 or e[1].__class__ == Tempo):
589 thread.append (e)
590 else:
591 todo.append (e)
592 threads.append (thread)
593 channel = todo
595 return threads
597 def gcd (a,b):
598 if b == 0:
599 return a
600 c = a
601 while c:
602 c = a % b
603 a = b
604 b = c
605 return a
607 def dump_skip (skip, clocks):
608 return skip + Duration (clocks).dump () + ' '
610 def dump (d):
611 return d.dump ()
613 def dump_chord (ch):
614 s = ''
615 notes = []
616 for i in ch:
617 if i.__class__ == Note:
618 notes.append (i)
619 else:
620 s = s + i.dump ()
621 if len (notes) == 1:
622 s = s + dump (notes[0])
623 elif len (notes) > 1:
624 global reference_note
625 s = s + '<'
626 s = s + notes[0].dump (dump_dur = 0)
627 r = reference_note
628 for i in notes[1:]:
629 s = s + i.dump (dump_dur = 0 )
630 s = s + '>'
632 s = s + notes[0].duration.dump () + ' '
633 reference_note = r
634 return s
636 def dump_bar_line (last_bar_t, t, bar_count):
637 s = ''
638 bar_t = time.bar_clocks ()
639 if t - last_bar_t >= bar_t:
640 bar_count = bar_count + (t - last_bar_t) / bar_t
642 if t - last_bar_t == bar_t:
643 s = '|\n %% %d\n ' % bar_count
644 last_bar_t = t
645 else:
646 # urg, this will barf at meter changes
647 last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
649 return (s, last_bar_t, bar_count)
652 def dump_channel (thread, skip):
653 global reference_note, time
655 global_options.key = Key (0, 0, 0)
656 time = Time (4, 4)
657 # urg LilyPond doesn't start at c4, but
658 # remembers from previous tracks!
659 # reference_note = Note (clocks_per_4, 4*12, 0)
660 reference_note = Note (0, 4*12, 0)
661 last_e = None
662 chs = []
663 ch = []
665 for e in thread:
666 if last_e and last_e[0] == e[0]:
667 ch.append (e[1])
668 else:
669 if ch:
670 chs.append ((last_e[0], ch))
672 ch = [e[1]]
674 last_e = e
676 if ch:
677 chs.append ((last_e[0], ch))
678 t = 0
679 last_t = 0
680 last_bar_t = 0
681 bar_count = 1
683 lines = ['']
684 for ch in chs:
685 t = ch[0]
687 i = lines[-1].rfind ('\n') + 1
688 if len (lines[-1][i:]) > LINE_BELL:
689 lines.append ('')
691 if t - last_t > 0:
692 d = t - last_t
693 if bar_max and t > time.bar_clocks () * bar_max:
694 d = time.bar_clocks () * bar_max - last_t
695 lines[-1] = lines[-1] + dump_skip (skip, d)
696 elif t - last_t < 0:
697 errorport.write ('BUG: time skew')
699 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
700 t, bar_count)
702 if bar_max and bar_count > bar_max:
703 break
705 lines[-1] = lines[-1] + s
706 lines[-1] = lines[-1] + dump_chord (ch[1])
708 clocks = 0
709 for i in ch[1]:
710 if i.clocks > clocks:
711 clocks = i.clocks
713 last_t = t + clocks
715 (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
716 last_t, bar_count)
717 lines[-1] = lines[-1] + s
719 return '\n '.join (lines) + '\n'
721 def number2ascii (i):
722 s = ''
723 i += 1
724 while i > 0:
725 m = (i - 1) % 26
726 s = '%c' % (m + ord ('A')) + s
727 i = (i - m)/26
728 return s
730 def track_name (i):
731 return 'track' + number2ascii (i)
733 def channel_name (i):
734 return 'channel' + number2ascii (i)
736 def dump_track (channels, n):
737 s = '\n'
738 track = track_name (n)
739 clef = guess_clef (channels)
741 for i in range (len (channels)):
742 channel = channel_name (i)
743 item = thread_first_item (channels[i])
745 if item and item.__class__ == Note:
746 skip = 's'
747 s = s + '%s = ' % (track + channel)
748 if not global_options.absolute_pitches:
749 s = s + '\\relative c '
750 elif item and item.__class__ == Text:
751 skip = '" "'
752 s = s + '%s = \\lyricmode ' % (track + channel)
753 else:
754 skip = '\\skip '
755 s = s + '%s = ' % (track + channel)
756 s = s + '{\n'
757 s = s + ' ' + dump_channel (channels[i][0], skip)
758 s = s + '}\n\n'
760 s = s + '%s = <<\n' % track
762 if clef.type != 2:
763 s = s + clef.dump () + '\n'
765 for i in range (len (channels)):
766 channel = channel_name (i)
767 item = thread_first_item (channels[i])
768 if item and item.__class__ == Text:
769 s = s + ' \\context Lyrics = %s \\%s\n' % (channel,
770 track + channel)
771 else:
772 s = s + ' \\context Voice = %s \\%s\n' % (channel,
773 track + channel)
774 s = s + '>>\n\n'
775 return s
777 def thread_first_item (thread):
778 for chord in thread:
779 for event in chord:
780 if (event[1].__class__ == Note
781 or (event[1].__class__ == Text
782 and event[1].type == midi.LYRIC)):
784 return event[1]
785 return None
787 def track_first_item (track):
788 for thread in track:
789 first = thread_first_item (thread)
790 if first:
791 return first
792 return None
794 def guess_clef (track):
795 i = 0
796 p = 0
797 for thread in track:
798 for chord in thread:
799 for event in chord:
800 if event[1].__class__ == Note:
801 i = i + 1
802 p = p + event[1].pitch
803 if i and p / i <= 3*12:
804 return Clef (0)
805 elif i and p / i <= 5*12:
806 return Clef (1)
807 elif i and p / i >= 7*12:
808 return Clef (3)
809 else:
810 return Clef (2)
813 def convert_midi (in_file, out_file):
814 global clocks_per_1, clocks_per_4, key
815 global start_quant_clocks
816 global duration_quant_clocks
817 global allowed_tuplet_clocks
819 str = open (in_file, 'rb').read ()
820 midi_dump = midi.parse (str)
822 clocks_per_1 = midi_dump[0][1]
823 clocks_per_4 = clocks_per_1 / 4
825 if global_options.start_quant:
826 start_quant_clocks = clocks_per_1 / global_options.start_quant
828 if global_options.duration_quant:
829 duration_quant_clocks = clocks_per_1 / global_options.duration_quant
831 allowed_tuplet_clocks = []
832 for (dur, num, den) in global_options.allowed_tuplets:
833 allowed_tuplet_clocks.append (clocks_per_1 / dur * num / den)
835 if global_options.verbose:
836 print 'allowed tuplet clocks:', allowed_tuplet_clocks
838 tracks = []
839 for t in midi_dump[1]:
840 global_options.key = Key (0, 0, 0)
841 tracks.append (split_track (t))
843 tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, in_file)
846 s = ''
847 s = tag + '\n\\version "2.7.38"\n\n'
848 for i in range (len (tracks)):
849 s = s + dump_track (tracks[i], i)
851 s = s + '\n\\score {\n <<\n'
853 i = 0
854 for t in tracks:
855 track = track_name (i)
856 item = track_first_item (t)
858 if item and item.__class__ == Note:
859 s = s + ' \\context Staff=%s \\%s\n' % (track, track)
860 elif item and item.__class__ == Text:
861 s = s + ' \\context Lyrics=%s \\%s\n' % (track, track)
863 i += 1
864 s = s + ' >>\n}\n'
866 progress (_ ("%s output to `%s'...") % ('LY', out_file))
868 if out_file == '-':
869 handle = sys.stdout
870 else:
871 handle = open (out_file, 'w')
873 handle.write (s)
874 handle.close ()
877 def get_option_parser ():
878 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'midi2ly',
879 description=_ ("Convert %s to LilyPond input.\n") % 'MIDI',
880 add_help_option=False)
882 p.add_option ('-a', '--absolute-pitches',
883 action='store_true',
884 help=_ ('print absolute pitches'))
885 p.add_option ('-d', '--duration-quant',
886 metavar=_ ('DUR'),
887 help=_ ('quantise note durations on DUR'))
888 p.add_option ('-e', '--explicit-durations',
889 action='store_true',
890 help=_ ('print explicit durations'))
891 p.add_option('-h', '--help',
892 action='help',
893 help=_ ('show this help and exit'))
894 p.add_option('-k', '--key', help=_ ('set key: ALT=+sharps|-flats; MINOR=1'),
895 metavar=_ ('ALT[:MINOR]'),
896 default='0'),
897 p.add_option ('-o', '--output', help=_ ('write output to FILE'),
898 metavar=_ ('FILE'),
899 action='store')
900 p.add_option ('-p', '--preview', help=_ ('preview of first 4 bars'),
901 action='store_true')
902 p.add_option ('-s', '--start-quant',help= _ ('quantise note starts on DUR'),
903 metavar=_ ('DUR'))
904 p.add_option ('-t', '--allow-tuplet',
905 metavar=_ ('DUR*NUM/DEN'),
906 action = 'append',
907 dest='allowed_tuplets',
908 help=_ ('allow tuplet durations DUR*NUM/DEN'),
909 default=[])
910 p.add_option ('-V', '--verbose', help=_ ('be verbose'),
911 action='store_true'
913 p.version = 'midi2ly (LilyPond) @TOPLEVEL_VERSION@'
914 p.add_option ('--version',
915 action='version',
916 help=_ ('show version number and exit'))
917 p.add_option ('-w', '--warranty', help=_ ('show warranty and copyright'),
918 action='store_true',
920 p.add_option ('-x', '--text-lyrics', help=_ ('treat every text as a lyric'),
921 action='store_true')
923 p.add_option_group (ly.display_encode (_ ('Examples')),
924 description = r'''
925 $ midi2ly --key=-2:1 --duration-quant=32 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
926 ''')
927 p.add_option_group ('',
928 description=(
929 _ ('Report bugs via %s')
930 % 'http://post.gmane.org/post.php'
931 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
932 return p
936 def do_options ():
937 opt_parser = get_option_parser ()
938 (options, args) = opt_parser.parse_args ()
940 if not args or args[0] == '-':
941 opt_parser.print_help ()
942 ly.stderr_write ('\n%s: %s %s\n' % (program_name, _ ('error: '),
943 _ ('no files specified on command line.')))
944 sys.exit (2)
946 if options.duration_quant:
947 options.duration_quant = int (options.duration_quant)
949 if options.warranty:
950 warranty ()
951 sys.exit (0)
952 if 1:
953 (alterations, minor) = map (int, (options.key + ':0').split (':'))[0:2]
954 sharps = 0
955 flats = 0
956 if alterations >= 0:
957 sharps = alterations
958 else:
959 flats = - alterations
961 options.key = Key (sharps, flats, minor)
963 if options.start_quant:
964 options.start_quant = int (options.start_quant)
966 global bar_max
967 if options.preview:
968 bar_max = 4
970 options.allowed_tuplets = [map (int, a.replace ('/','*').split ('*'))
971 for a in options.allowed_tuplets]
973 if options.verbose:
974 sys.stderr.write ('Allowed tuplets: %s\n' % `options.allowed_tuplets`)
976 global global_options
977 global_options = options
979 return args
981 def main ():
982 files = do_options ()
984 for f in files:
985 g = f
986 g = strip_extension (g, '.midi')
987 g = strip_extension (g, '.mid')
988 g = strip_extension (g, '.MID')
989 (outdir, outbase) = ('','')
991 if not global_options.output:
992 outdir = '.'
993 outbase = os.path.basename (g)
994 o = os.path.join (outdir, outbase + '-midi.ly')
995 elif global_options.output[-1] == os.sep:
996 outdir = global_options.output
997 outbase = os.path.basename (g)
998 os.path.join (outdir, outbase + '-gen.ly')
999 else:
1000 o = global_options.output
1001 (outdir, outbase) = os.path.split (o)
1003 if outdir != '.' and outdir != '':
1004 try:
1005 os.mkdir (outdir, 0777)
1006 except OSError:
1007 pass
1009 convert_midi (f, o)
1011 if __name__ == '__main__':
1012 main ()