]> git.donarmstrong.com Git - lilypond.git/blob - scripts/midi2ly.py
Merge remote branch 'origin' into release/unstable
[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--2010  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--2010',
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 track_name (i):
716     return 'track%c' % (i + ord ('A'))
717
718 def channel_name (i):
719     return 'channel%c' % (i + ord ('A'))
720
721 def dump_track (channels, n):
722     s = '\n'
723     track = track_name (n)
724     clef = guess_clef (channels)
725
726     for i in range (len (channels)):
727         channel = channel_name (i)
728         item = thread_first_item (channels[i])
729
730         if item and item.__class__ == Note:
731             skip = 's'
732             s = s + '%s = ' % (track + channel)
733             if not global_options.absolute_pitches:
734                 s = s + '\\relative c '
735         elif item and item.__class__ == Text:
736             skip = '" "'
737             s = s + '%s = \\lyricmode ' % (track + channel)
738         else:
739             skip = '\\skip '
740             s = s + '%s =  ' % (track + channel)
741         s = s + '{\n'
742         s = s + '  ' + dump_channel (channels[i][0], skip)
743         s = s + '}\n\n'
744
745     s = s + '%s = <<\n' % track
746
747     if clef.type != 2:
748         s = s + clef.dump () + '\n'
749
750     for i in range (len (channels)):
751         channel = channel_name (i)
752         item = thread_first_item (channels[i])
753         if item and item.__class__ == Text:
754             s = s + '  \\context Lyrics = %s \\%s\n' % (channel,
755                                   track + channel)
756         else:
757             s = s + '  \\context Voice = %s \\%s\n' % (channel,
758                                  track + channel)
759     s = s + '>>\n\n'
760     return s
761
762 def thread_first_item (thread):
763     for chord in thread:
764         for event in chord:
765             if (event[1].__class__ == Note 
766               or (event[1].__class__ == Text 
767                 and event[1].type == midi.LYRIC)):
768                 
769               return event[1]
770     return None
771
772 def track_first_item (track):
773     for thread in track:
774         first = thread_first_item (thread)
775         if first:
776             return first
777     return None
778
779 def guess_clef (track):
780     i = 0
781     p = 0
782     for thread in track:
783         for chord in thread:
784             for event in chord:
785                 if event[1].__class__ == Note:
786                     i = i + 1
787                     p = p + event[1].pitch
788     if i and p / i <= 3*12:
789         return Clef (0)
790     elif i and p / i <= 5*12:
791         return Clef (1)
792     elif i and p / i >= 7*12:
793         return Clef (3)
794     else:
795         return Clef (2)
796     
797
798 def convert_midi (in_file, out_file):
799     global clocks_per_1, clocks_per_4, key
800     global start_quant_clocks
801     global  duration_quant_clocks
802     global allowed_tuplet_clocks
803
804     str = open (in_file, 'rb').read ()
805     midi_dump = midi.parse (str)
806     
807     clocks_per_1 = midi_dump[0][1]
808     clocks_per_4 = clocks_per_1 / 4
809     
810     if global_options.start_quant:
811         start_quant_clocks = clocks_per_1 / global_options.start_quant
812
813     if global_options.duration_quant:
814         duration_quant_clocks = clocks_per_1 / global_options.duration_quant
815
816     allowed_tuplet_clocks = []
817     for (dur, num, den) in global_options.allowed_tuplets:
818         allowed_tuplet_clocks.append (clocks_per_1 / den)
819
820     tracks = []
821     for t in midi_dump[1]:
822         global_options.key = Key (0, 0, 0)
823         tracks.append (split_track (t))
824
825     tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, in_file)
826
827     
828     s = ''
829     s = tag + '\n\\version "2.7.38"\n\n'
830     for i in range (len (tracks)):
831         s = s + dump_track (tracks[i], i)
832
833     s = s + '\n\\score {\n  <<\n'
834     
835     i = 0
836     for t in tracks:
837         track = track_name (i)
838         item = track_first_item (t)
839         
840         if item and item.__class__ == Note:
841             s = s + '    \\context Staff=%s \\%s\n' % (track, track)
842         elif item and item.__class__ == Text:
843             s = s + '    \\context Lyrics=%s \\%s\n' % (track, track)
844
845         i += 1
846     s = s + '  >>\n}\n'
847
848     progress (_ ("%s output to `%s'...") % ('LY', out_file))
849
850     if out_file == '-':
851         handle = sys.stdout
852     else:
853         handle = open (out_file, 'w')
854
855     handle.write (s)
856     handle.close ()
857
858
859 def get_option_parser ():
860     p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'midi2ly',
861                  description=_ ("Convert %s to LilyPond input.\n") % 'MIDI',
862                  add_help_option=False)
863
864     p.add_option ('-a', '--absolute-pitches',
865            action='store_true',
866            help=_ ("print absolute pitches"))
867     p.add_option ('-d', '--duration-quant',
868            metavar= _("DUR"),
869            help=_ ("quantise note durations on DUR"))
870     p.add_option ('-e', '--explicit-durations',
871            action='store_true',
872            help=_ ("print explicit durations"))
873     p.add_option("-h", "--help",
874                  action="help",
875                  help=_ ("show this help and exit"))
876     p.add_option('-k', '--key', help=_ ("set key: ALT=+sharps|-flats; MINOR=1"),
877           metavar=_ ("ALT[:MINOR]"),
878           default='0'),
879     p.add_option ('-o', '--output', help=_ ("write output to FILE"),
880            metavar=_("FILE"),
881            action='store')
882     p.add_option ('-s', '--start-quant',help= _ ("quantise note starts on DUR"),
883            metavar=_ ("DUR"))
884     p.add_option ('-t', '--allow-tuplet',
885            metavar=_ ("DUR*NUM/DEN"),
886            action = "append",
887            dest="allowed_tuplets",
888            help=_ ("allow tuplet durations DUR*NUM/DEN"),
889            default=[])
890     p.add_option ('-V', '--verbose', help=_ ("be verbose"),
891            action='store_true'
892            ),
893     p.version = "midi2ly (LilyPond) @TOPLEVEL_VERSION@"
894     p.add_option("--version",
895                  action="version",
896                  help=_ ("show version number and exit"))
897     p.add_option ('-w', '--warranty', help=_ ("show warranty and copyright"),
898            action='store_true',
899            ),
900     p.add_option ('-x', '--text-lyrics', help=_ ("treat every text as a lyric"),
901            action='store_true')
902
903     p.add_option_group (ly.display_encode (_ ("Examples")),
904               description = r'''
905   $ midi2ly --key=-2:1 --duration-quant=32 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
906 ''')
907     p.add_option_group ('',
908                         description=(
909             _ ('Report bugs via %s')
910             % 'http://post.gmane.org/post.php'
911             '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
912     return p
913
914
915
916 def do_options ():
917     opt_parser = get_option_parser()
918     (options, args) = opt_parser.parse_args ()
919
920     if not args or args[0] == '-':
921         opt_parser.print_help ()
922         ly.stderr_write ('\n%s: %s %s\n' % (program_name, _ ("error: "),
923                          _ ("no files specified on command line.")))
924         sys.exit (2)
925
926     if options.duration_quant:
927         options.duration_quant = int (options.duration_quant)
928
929     if options.warranty:
930         warranty ()
931         sys.exit (0)
932     if 1:
933         (alterations, minor) = map (int, (options.key + ':0').split (':'))[0:2]
934         sharps = 0
935         flats = 0
936         if alterations >= 0:
937             sharps = alterations
938         else:
939             flats = - alterations
940
941         options.key = Key (sharps, flats, minor)
942
943         
944     if options.start_quant:
945         options.start_quant = int (options.start_quant)
946         
947     options.allowed_tuplets = [map (int, a.replace ('/','*').split ('*'))
948                 for a in options.allowed_tuplets]
949     
950     global global_options
951     global_options = options
952
953     return args
954
955 def main():
956     files = do_options()
957
958     for f in files:
959         g = f
960         g = strip_extension (g, '.midi')
961         g = strip_extension (g, '.mid')
962         g = strip_extension (g, '.MID')
963         (outdir, outbase) = ('','')
964
965         if not global_options.output:
966             outdir = '.'
967             outbase = os.path.basename (g)
968             o = os.path.join (outdir, outbase + '-midi.ly')
969         elif global_options.output[-1] == os.sep:
970             outdir = global_options.output
971             outbase = os.path.basename (g)
972             os.path.join (outdir, outbase + '-gen.ly')
973         else:
974             o = global_options.output
975             (outdir, outbase) = os.path.split (o)
976
977         if outdir != '.' and outdir != '':
978             try:
979                 os.mkdir (outdir, 0777)
980             except OSError:
981                 pass
982
983         convert_midi (f, o)
984 if __name__ == '__main__':
985     main()