]> git.donarmstrong.com Git - lilypond.git/blob - scripts/midi2ly.py
Midi2ly: grok midi files with up to 256 tracks, was 32. Fixes #1479.
[lilypond.git] / scripts / midi2ly.py
1 #!@TARGET_PYTHON@
2 #
3 # midi2ly.py -- LilyPond midi import script
4
5 # This file is part of LilyPond, the GNU music typesetter.
6 #
7 # Copyright (C) 1998--2011  Han-Wen Nienhuys <hanwen@xs4all.nl>
8 #                 Jan Nieuwenhuizen <janneke@gnu.org>
9 #
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.
14 #
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.
19 #
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/>.
22
23
24 '''
25 TODO:
26     * test on weird and unquantised midi input (lily-devel)
27     * update doc and manpage
28
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 '''
36
37 import os
38 import sys
39
40 """
41 @relocate-preamble@
42 """
43
44 import midi
45 import lilylib as ly
46 global _;_=ly._
47
48 ################################################################
49 ## CONSTANTS
50
51
52 LINE_BELL = 60
53 scale_steps = [0, 2, 4, 5, 7, 9, 11]
54 global_options = None
55
56 clocks_per_1 = 1536
57 clocks_per_4 = 0
58
59 time = 0
60 reference_note = 0
61 start_quant_clocks = 0
62
63 duration_quant_clocks = 0
64 allowed_tuplet_clocks = []
65
66
67 ################################################################
68
69
70 program_name = sys.argv[0]
71 program_version = '@TOPLEVEL_VERSION@'
72
73 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
74            'Han-Wen Nienhuys <hanwen@xs4all.nl>')
75
76 errorport = sys.stderr
77
78 def identify ():
79     sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
80
81 def warranty ():
82     identify ()
83     ly.encoded_write (sys.stdout, '''
84 %s
85
86   %s
87
88 %s
89 %s
90 ''' % ( _ ('Copyright (c) %s by') % '2001--2011',
91         '\n  '.join (authors),
92         _ ('Distributed under terms of the GNU General Public License.'),
93         _ ('It comes with NO WARRANTY.')))
94
95 def progress (s):
96     ly.encoded_write (errorport, s + '\n')
97
98 def warning (s):
99     progress (_ ("warning: ") + s)
100         
101 def error (s):
102     progress (_ ("error: ") + s)
103     raise Exception (_ ("Exiting... "))
104
105 def system (cmd, ignore_error = 0):
106     return ly.system (cmd, ignore_error=ignore_error)
107
108 def strip_extension (f, ext):
109     (p, e) = os.path.splitext (f)
110     if e == ext:
111         e = ''
112     return p + e
113
114
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)
122         
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]
127
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)
135
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)
146             
147         global reference_note
148         reference_note.duration = self
149
150         return s
151
152     def compare (self, other):
153         return self.clocks - other.clocks
154
155 def sign (x):
156     if x >= 0:
157         return 1
158     else:
159         return -1
160
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 ()
172
173     def o_n_a (self):
174         # major scale: do-do
175         # minor scale: la-la  (= + 5) '''
176
177         n = self.names[(self.pitch) % 12]
178         a = self.alterations[(self.pitch) % 12]
179
180         if a and global_options.key.flats:
181             a = - self.alterations[(self.pitch) % 12]
182             n = (n - a) % 7
183
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.)
192
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.
203
204         #  John Sankey <bf250@freenet.carleton.ca>
205         #
206         #  Let's also do a-minor: a b c d e f gis a
207         #
208         #  --jcn
209
210         o = self.pitch / 12 - 4
211
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
233
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
240
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
247
248         return (o, n, a)
249         
250     def __repr__ (self):
251         s = chr ((self.notename + 2)  % 7 + ord ('a'))
252         return 'Note(%s %s)' % (s, self.duration.dump())
253
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)
269             
270         if commas > 0:
271             s = s + "'" * commas
272         elif commas < 0:
273             s = s + "," * -commas
274
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 ()
279
280         reference_note = self
281         
282         # TODO: move space
283         return s + ' '
284
285
286 class Time:
287     def __init__ (self, num, den):
288         self.clocks = 0
289         self.num = num
290         self.den = den
291
292     def bar_clocks (self):
293         return clocks_per_1 * self.num / self.den
294
295     def __repr__ (self):
296         return 'Time(%d/%d)' % (self.num, self.den)
297     
298     def dump (self):
299         global time
300         time = self
301         return '\n  ' + '\\time %d/%d ' % (self.num, self.den) + '\n  '
302
303 class Tempo:
304     def __init__ (self, seconds_per_1):
305         self.clocks = 0
306         self.seconds_per_1 = seconds_per_1
307
308     def __repr__ (self):
309         return 'Tempo(%d)' % self.bpm ()
310     
311     def bpm (self):
312         return 4 * 60 / self.seconds_per_1
313     
314     def dump (self):
315         return '\n  ' + '\\tempo 4 = %d ' % (self.bpm()) + '\n  '
316
317 class Clef:
318     clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
319     def __init__ (self, type):
320         self.type = type
321
322     def __repr__ (self):
323         return 'Clef(%s)' % self.clefs[self.type]
324     
325     def dump (self):
326         return '\n  \\clef %s\n  ' % self.clefs[self.type]
327
328 class Key:
329     key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
330     key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
331
332     def __init__ (self, sharps, flats, minor):
333         self.clocks = 0
334         self.flats = flats
335         self.sharps = sharps
336         self.minor = minor
337
338     def dump (self):
339         global_options.key = self
340
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
349  
350             if not self.minor:
351                 name = chr ((k + 2) % 7 + ord ('a'))
352             else:
353                 name = chr ((k + 2) % 7 + ord ('a'))
354
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
366
367             if a:
368                 name = name + Note.alteration_names[a + 2]
369
370             s = '\\key ' + name
371             if self.minor:
372                 s = s + ' \\minor'
373             else:
374                 s = s + ' \\major'
375
376         return '\n\n  ' + s + '\n  '
377
378
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',)
389     
390     def __init__ (self, type, text):
391         self.clocks = 0
392         self.type = type
393         self.text = text
394
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
407
408     def __repr__ (self):
409         return 'Text(%d=%s)' % (self.type, self.text)
410
411
412
413 def split_track (track):
414     chs = {}
415     for i in range(16):
416         chs[i] = []
417         
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)
426
427     for i in range (16):
428         if chs[i] == []:
429             del chs[i]
430
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
438
439
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
449
450 def end_note (pitches, notes, t, e):
451     try:
452         (lt, vel) = pitches[e]
453         del pitches[e]
454
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
466
467         notes.insert (i + 1,
468               (lt, Note (d, e, vel)))
469
470     except KeyError:
471         pass
472
473 def events_on_channel (channel):
474     pitches = {}
475
476     notes = []
477     events = []
478     last_lyric = 0
479     last_time = 0
480     for e in channel:
481         t = e[0]
482
483         if start_quant_clocks:
484             t = quantise_clocks (t, start_quant_clocks)
485
486
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])
490             
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])
494                 
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)
500                 
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
506
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
524
525                 k = Key (sharps, flats, minor)
526                 events.append ((t, k))
527
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
532
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])
540
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
552
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
559         
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
568
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
594
595     return threads
596
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
606     
607 def dump_skip (skip, clocks):
608     return skip + Duration (clocks).dump () + ' '
609
610 def dump (d):
611     return d.dump ()
612
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 + '>'
631
632         s = s + notes[0].duration.dump() + ' '
633         reference_note = r
634     return s
635
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
641         
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
648             
649     return (s, last_bar_t, bar_count)
650
651             
652 def dump_channel (thread, skip):
653     global reference_note, time
654
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 = []
664
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))
671                 
672             ch = [e[1]]
673             
674         last_e = e
675
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
682     
683     lines = ['']
684     for ch in chs: 
685         t = ch[0]
686
687         i = lines[-1].rfind ('\n') + 1
688         if len (lines[-1][i:]) > LINE_BELL:
689             lines.append ('')
690
691         if t - last_t > 0:
692             lines[-1] = lines[-1] + dump_skip (skip, t-last_t)
693         elif t - last_t < 0:
694             errorport.write ('BUG: time skew')
695
696         (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
697                               t, bar_count)
698         lines[-1] = lines[-1] + s
699         
700         lines[-1] = lines[-1] + dump_chord (ch[1])
701
702         clocks = 0
703         for i in ch[1]:
704             if i.clocks > clocks:
705                 clocks = i.clocks
706                 
707         last_t = t + clocks
708         
709         (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
710                               last_t, bar_count)
711         lines[-1] = lines[-1] + s
712
713     return '\n  '.join (lines) + '\n'
714
715 def number2ascii (i):
716     s = ''
717     i += 1
718     while i > 0:
719         m = (i - 1) % 26
720         s = '%c' % (m + ord ('A')) + s
721         i = (i - m)/26
722     return s
723
724 def track_name (i):
725     return 'track' + number2ascii (i)
726
727 def channel_name (i):
728     return 'channel' + number2ascii (i)
729
730 def dump_track (channels, n):
731     s = '\n'
732     track = track_name (n)
733     clef = guess_clef (channels)
734
735     for i in range (len (channels)):
736         channel = channel_name (i)
737         item = thread_first_item (channels[i])
738
739         if item and item.__class__ == Note:
740             skip = 's'
741             s = s + '%s = ' % (track + channel)
742             if not global_options.absolute_pitches:
743                 s = s + '\\relative c '
744         elif item and item.__class__ == Text:
745             skip = '" "'
746             s = s + '%s = \\lyricmode ' % (track + channel)
747         else:
748             skip = '\\skip '
749             s = s + '%s =  ' % (track + channel)
750         s = s + '{\n'
751         s = s + '  ' + dump_channel (channels[i][0], skip)
752         s = s + '}\n\n'
753
754     s = s + '%s = <<\n' % track
755
756     if clef.type != 2:
757         s = s + clef.dump () + '\n'
758
759     for i in range (len (channels)):
760         channel = channel_name (i)
761         item = thread_first_item (channels[i])
762         if item and item.__class__ == Text:
763             s = s + '  \\context Lyrics = %s \\%s\n' % (channel,
764                                   track + channel)
765         else:
766             s = s + '  \\context Voice = %s \\%s\n' % (channel,
767                                  track + channel)
768     s = s + '>>\n\n'
769     return s
770
771 def thread_first_item (thread):
772     for chord in thread:
773         for event in chord:
774             if (event[1].__class__ == Note 
775               or (event[1].__class__ == Text 
776                 and event[1].type == midi.LYRIC)):
777                 
778               return event[1]
779     return None
780
781 def track_first_item (track):
782     for thread in track:
783         first = thread_first_item (thread)
784         if first:
785             return first
786     return None
787
788 def guess_clef (track):
789     i = 0
790     p = 0
791     for thread in track:
792         for chord in thread:
793             for event in chord:
794                 if event[1].__class__ == Note:
795                     i = i + 1
796                     p = p + event[1].pitch
797     if i and p / i <= 3*12:
798         return Clef (0)
799     elif i and p / i <= 5*12:
800         return Clef (1)
801     elif i and p / i >= 7*12:
802         return Clef (3)
803     else:
804         return Clef (2)
805     
806
807 def convert_midi (in_file, out_file):
808     global clocks_per_1, clocks_per_4, key
809     global start_quant_clocks
810     global  duration_quant_clocks
811     global allowed_tuplet_clocks
812
813     str = open (in_file, 'rb').read ()
814     midi_dump = midi.parse (str)
815     
816     clocks_per_1 = midi_dump[0][1]
817     clocks_per_4 = clocks_per_1 / 4
818     
819     if global_options.start_quant:
820         start_quant_clocks = clocks_per_1 / global_options.start_quant
821
822     if global_options.duration_quant:
823         duration_quant_clocks = clocks_per_1 / global_options.duration_quant
824
825     allowed_tuplet_clocks = []
826     for (dur, num, den) in global_options.allowed_tuplets:
827         allowed_tuplet_clocks.append (clocks_per_1 / den)
828
829     tracks = []
830     for t in midi_dump[1]:
831         global_options.key = Key (0, 0, 0)
832         tracks.append (split_track (t))
833
834     tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, in_file)
835
836     
837     s = ''
838     s = tag + '\n\\version "2.7.38"\n\n'
839     for i in range (len (tracks)):
840         s = s + dump_track (tracks[i], i)
841
842     s = s + '\n\\score {\n  <<\n'
843     
844     i = 0
845     for t in tracks:
846         track = track_name (i)
847         item = track_first_item (t)
848         
849         if item and item.__class__ == Note:
850             s = s + '    \\context Staff=%s \\%s\n' % (track, track)
851         elif item and item.__class__ == Text:
852             s = s + '    \\context Lyrics=%s \\%s\n' % (track, track)
853
854         i += 1
855     s = s + '  >>\n}\n'
856
857     progress (_ ("%s output to `%s'...") % ('LY', out_file))
858
859     if out_file == '-':
860         handle = sys.stdout
861     else:
862         handle = open (out_file, 'w')
863
864     handle.write (s)
865     handle.close ()
866
867
868 def get_option_parser ():
869     p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'midi2ly',
870                  description=_ ("Convert %s to LilyPond input.\n") % 'MIDI',
871                  add_help_option=False)
872
873     p.add_option ('-a', '--absolute-pitches',
874            action='store_true',
875            help=_ ("print absolute pitches"))
876     p.add_option ('-d', '--duration-quant',
877            metavar= _("DUR"),
878            help=_ ("quantise note durations on DUR"))
879     p.add_option ('-e', '--explicit-durations',
880            action='store_true',
881            help=_ ("print explicit durations"))
882     p.add_option("-h", "--help",
883                  action="help",
884                  help=_ ("show this help and exit"))
885     p.add_option('-k', '--key', help=_ ("set key: ALT=+sharps|-flats; MINOR=1"),
886           metavar=_ ("ALT[:MINOR]"),
887           default='0'),
888     p.add_option ('-o', '--output', help=_ ("write output to FILE"),
889            metavar=_("FILE"),
890            action='store')
891     p.add_option ('-s', '--start-quant',help= _ ("quantise note starts on DUR"),
892            metavar=_ ("DUR"))
893     p.add_option ('-t', '--allow-tuplet',
894            metavar=_ ("DUR*NUM/DEN"),
895            action = "append",
896            dest="allowed_tuplets",
897            help=_ ("allow tuplet durations DUR*NUM/DEN"),
898            default=[])
899     p.add_option ('-V', '--verbose', help=_ ("be verbose"),
900            action='store_true'
901            ),
902     p.version = "midi2ly (LilyPond) @TOPLEVEL_VERSION@"
903     p.add_option("--version",
904                  action="version",
905                  help=_ ("show version number and exit"))
906     p.add_option ('-w', '--warranty', help=_ ("show warranty and copyright"),
907            action='store_true',
908            ),
909     p.add_option ('-x', '--text-lyrics', help=_ ("treat every text as a lyric"),
910            action='store_true')
911
912     p.add_option_group (ly.display_encode (_ ("Examples")),
913               description = r'''
914   $ midi2ly --key=-2:1 --duration-quant=32 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
915 ''')
916     p.add_option_group ('',
917                         description=(
918             _ ('Report bugs via %s')
919             % 'http://post.gmane.org/post.php'
920             '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
921     return p
922
923
924
925 def do_options ():
926     opt_parser = get_option_parser()
927     (options, args) = opt_parser.parse_args ()
928
929     if not args or args[0] == '-':
930         opt_parser.print_help ()
931         ly.stderr_write ('\n%s: %s %s\n' % (program_name, _ ("error: "),
932                          _ ("no files specified on command line.")))
933         sys.exit (2)
934
935     if options.duration_quant:
936         options.duration_quant = int (options.duration_quant)
937
938     if options.warranty:
939         warranty ()
940         sys.exit (0)
941     if 1:
942         (alterations, minor) = map (int, (options.key + ':0').split (':'))[0:2]
943         sharps = 0
944         flats = 0
945         if alterations >= 0:
946             sharps = alterations
947         else:
948             flats = - alterations
949
950         options.key = Key (sharps, flats, minor)
951
952         
953     if options.start_quant:
954         options.start_quant = int (options.start_quant)
955         
956     options.allowed_tuplets = [map (int, a.replace ('/','*').split ('*'))
957                 for a in options.allowed_tuplets]
958     
959     global global_options
960     global_options = options
961
962     return args
963
964 def main():
965     files = do_options()
966
967     for f in files:
968         g = f
969         g = strip_extension (g, '.midi')
970         g = strip_extension (g, '.mid')
971         g = strip_extension (g, '.MID')
972         (outdir, outbase) = ('','')
973
974         if not global_options.output:
975             outdir = '.'
976             outbase = os.path.basename (g)
977             o = os.path.join (outdir, outbase + '-midi.ly')
978         elif global_options.output[-1] == os.sep:
979             outdir = global_options.output
980             outbase = os.path.basename (g)
981             os.path.join (outdir, outbase + '-gen.ly')
982         else:
983             o = global_options.output
984             (outdir, outbase) = os.path.split (o)
985
986         if outdir != '.' and outdir != '':
987             try:
988                 os.mkdir (outdir, 0777)
989             except OSError:
990                 pass
991
992         convert_midi (f, o)
993 if __name__ == '__main__':
994     main()