]> git.donarmstrong.com Git - lilypond.git/blob - scripts/midi2ly.py
4a0d956211a3b185a318ecd8c3f5626d4b51ad98
[lilypond.git] / scripts / midi2ly.py
1 #!@TARGET_PYTHON@
2 #
3 # msdi2ly.py -- LilyPond midi import script
4
5 # source file of the GNU LilyPond music typesetter
6 #
7 # (c) 1998--2006  Han-Wen Nienhuys <hanwen@cs.uu.nl>
8 #                 Jan Nieuwenhuizen <janneke@gnu.org>
9
10
11 '''
12 TODO:
13     * test on weird and unquantised midi input (lily-devel)
14     * update doc and manpage
15
16     * simply insert clef changes whenever too many ledger lines
17         [to avoid tex capacity exceeded]
18     * do not ever quant skips
19     * better lyrics handling
20     * [see if it is feasible to] move ly-classes to library for use in
21         other converters, while leaving midi specific stuff here
22 '''
23
24 import os
25 import string
26 import sys
27
28 ################################################################
29 # Users of python modules should include this snippet.
30 #
31
32 for d in ['@lilypond_datadir@',
33           '@lilypond_libdir@']:
34     sys.path.insert (0, os.path.join (d, 'python'))
35
36 # dynamic relocation, for GUB binaries.
37 bindir = os.path.abspath (os.path.split (sys.argv[0])[0])
38 for p in ['share', 'lib']:
39     datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % p)
40     sys.path.insert (0, datadir)
41
42
43 import midi
44 import lilylib as ly
45
46 ################################################################
47 ################ CONSTANTS
48
49
50 output_name = ''
51 LINE_BELL = 60
52 scale_steps = [0,2,4,5,7,9,11]
53 global_options = None
54
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 localedir = '@localedir@'
70 try:
71     import gettext
72     gettext.bindtextdomain ('lilypond', localedir)
73     gettext.textdomain ('lilypond')
74     _ = gettext.gettext
75 except:
76     def _ (s):
77         return s
78
79 program_name = sys.argv[0]
80 program_version = '@TOPLEVEL_VERSION@'
81
82 errorport = sys.stderr
83
84 def identify ():
85     sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
86
87 def warranty ():
88     identify ()
89     sys.stdout.write ('''
90 Copyright (c) %s by
91
92  Han-Wen Nienhuys
93  Jan Nieuwenhuizen
94
95 %s
96 %s
97 '''  ( '2001--2006',
98    _('Distributed under terms of the GNU General Public License.'),
99    _('It comes with NO WARRANTY.')))
100
101
102 def progress (s):
103     errorport.write (s + '\n')
104
105 def warning (s):
106     progress (_ ("warning: ") + s)
107         
108 def error (s):
109     progress (_ ("error: ") + s)
110     raise _ ("Exiting ... ")
111
112 def system (cmd, ignore_error = 0):
113     return ly.system (cmd, ignore_error=ignore_error)
114
115 def strip_extension (f, ext):
116     (p, e) = os.path.splitext (f)
117     if e == ext:
118         e = ''
119     return p + e
120
121 \f
122
123
124 class Duration:
125     allowed_durs = (1, 2, 4, 8, 16, 32, 64, 128)
126     def __init__ (self, clocks):
127         self.clocks = clocks
128         if clocks <= 0:
129             self.clocks = duration_quant_clocks
130         (self.dur, self.num, self.den) = self.dur_num_den (clocks)
131         
132     def dur_num_den (self, clocks):
133         for i in range (len (allowed_tuplet_clocks)):
134             if clocks == allowed_tuplet_clocks[i]:
135                 return global_options.allowed_tuplets[i]
136
137         dur = 0; num = 1; den = 1;
138         g = gcd (clocks, clocks_per_1)
139         if g:
140             (dur, num) = (clocks_per_1 / g, clocks / g)
141         if not dur in self.allowed_durs:
142             dur = 4; num = clocks; den = clocks_per_4
143         return (dur, num, den)
144
145     def dump (self):
146         if self.den == 1:
147             if self.num == 1:
148                 s = '%d' % self.dur
149             elif self.num == 3 and self.dur != 1:
150                 s = '%d.' % (self.dur / 2)
151             else:
152                 s = '%d*%d' % (self.dur, self.num)
153         else:
154             s = '%d*%d/%d' % (self.dur, self.num, self.den)
155             
156         global reference_note
157         reference_note.duration = self
158
159         return s
160
161     def compare (self, other):
162         return self.clocks - other.clocks
163
164 def sign (x):
165     if x >= 0:
166         return 1
167     else:
168         return -1
169
170 class Note:
171     names = (0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6)
172     alterations = (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0)
173     alteration_names = ('eses', 'es', '', 'is' , 'isis')
174     def __init__ (self, clocks, pitch, velocity):
175         self.pitch = pitch
176         self.velocity = velocity
177         # hmm
178         self.clocks = clocks
179         self.duration = Duration (clocks)
180         (self.octave, self.notename, self.alteration) = self.o_n_a ()
181
182     def o_n_a (self):
183         # major scale: do-do
184         # minor scale: la-la  (= + 5) '''
185
186         n = self.names[(self.pitch) % 12]
187         a = self.alterations[(self.pitch) % 12]
188
189         if a and global_options.key.flats:
190             a = - self.alterations[(self.pitch) % 12]
191             n = (n - a) % 7
192
193         #  By tradition, all scales now consist of a sequence
194         #  of 7 notes each with a distinct name, from amongst
195         #  a b c d e f g.  But, minor scales have a wide
196         #  second interval at the top - the 'leading note' is
197         #  sharped. (Why? it just works that way! Anything
198         #  else doesn't sound as good and isn't as flexible at
199         #  saying things. In medieval times, scales only had 6
200         #  notes to avoid this problem - the hexachords.)
201
202         #  So, the d minor scale is d e f g a b-flat c-sharp d
203         #  - using d-flat for the leading note would skip the
204         #  name c and duplicate the name d.  Why isn't c-sharp
205         #  put in the key signature? Tradition. (It's also
206         #  supposedly based on the Pythagorean theory of the
207         #  cycle of fifths, but that really only applies to
208         #  major scales...)  Anyway, g minor is g a b-flat c d
209         #  e-flat f-sharp g, and all the other flat minor keys
210         #  end up with a natural leading note. And there you
211         #  have it.
212
213         #  John Sankey <bf250@freenet.carleton.ca>
214         #
215         #  Let's also do a-minor: a b c d e f gis a
216         #
217         #  --jcn
218
219         o = self.pitch / 12 - 4
220
221         key = global_options.key
222         if key.minor:
223             # as -> gis
224             if (key.sharps == 0 and key.flats == 0
225                 and n == 5 and a == -1):
226                 n = 4; a = 1
227             # des -> cis
228             elif key.flats == 1 and n == 1 and a == -1:
229                 n = 0; a = 1
230             # ges -> fis
231             elif key.flats == 2 and n == 4 and a == -1:
232                 n = 3; a = 1
233             # g -> fisis
234             elif key.sharps == 5 and n == 4 and a == 0:
235                 n = 3; a = 2
236             # d -> cisis
237             elif key.sharps == 6 and n == 1 and a == 0:
238                 n = 0; a = 2
239             # a -> gisis
240             elif key.sharps == 7 and n == 5 and a == 0:
241                 n = 4; a = 2
242
243         # b -> ces
244         if key.flats >= 6 and n == 6 and a == 0:
245             n = 0; a = -1; o = o + 1
246         # e -> fes
247         if key.flats >= 7 and n == 2 and a == 0:
248             n = 3; a = -1
249
250         # f -> eis
251         if key.sharps >= 3 and n == 3 and a == 0:
252             n = 2; a = 1
253         # c -> bis
254         if key.sharps >= 4 and n == 0 and a == 0:
255             n = 6; a = 1; o = o - 1
256
257         return (o, n, a)
258         
259     def __repr__ (self):
260         s = chr ((self.notename + 2)  % 7 + ord ('a'))
261         return 'Note(%s %s)' % (s, self.duration.dump())
262
263     def dump (self, dump_dur = 1):
264         global reference_note
265         s = chr ((self.notename + 2)  % 7 + ord ('a'))
266         s = s + self.alteration_names[self.alteration + 2]
267         if global_options.absolute_pitches:
268             commas = self.octave
269         else:
270             delta = self.pitch - reference_note.pitch
271             commas = sign (delta) * (abs (delta) / 12)
272             if ((sign (delta) \
273               * (self.notename - reference_note.notename) + 7) \
274               % 7 >= 4) \
275               or ((self.notename == reference_note.notename) \
276                 and (abs (delta) > 4) and (abs (delta) < 12)):
277                 commas = commas + sign (delta)
278             
279         if commas > 0:
280             s = s + "'" * commas
281         elif commas < 0:
282             s = s + "," * -commas
283
284         ## FIXME: compile fix --jcn
285         if dump_dur and (global_options.explicit_durations \
286          or self.duration.compare (reference_note.duration)):
287             s = s + self.duration.dump ()
288
289         reference_note = self
290         
291         # TODO: move space
292         return s + ' '
293
294
295 class Time:
296     def __init__ (self, num, den):
297         self.clocks = 0
298         self.num = num
299         self.den = den
300
301     def bar_clocks (self):
302         return clocks_per_1 * self.num / self.den
303
304     def __repr__ (self):
305         return 'Time(%d/%d)' % (self.num, self.den)
306     
307     def dump (self):
308         global time
309         time = self
310         return '\n  ' + '\\time %d/%d ' % (self.num, self.den) + '\n  '
311
312 class Tempo:
313     def __init__ (self, seconds_per_1):
314         self.clocks = 0
315         self.seconds_per_1 = seconds_per_1
316
317     def __repr__ (self):
318         return 'Tempo(%d)' % self.bpm ()
319     
320     def bpm (self):
321         return 4 * 60 / self.seconds_per_1
322     
323     def dump (self):
324         return '\n  ' + '\\tempo 4 = %d ' % (self.bpm()) + '\n  '
325
326 class Clef:
327     clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
328     def __init__ (self, type):
329         self.type = type
330
331     def __repr__ (self):
332         return 'Clef(%s)' % self.clefs[self.type]
333     
334     def dump (self):
335         return '\n  \\clef %s\n  ' % self.clefs[self.type]
336
337 class Key:
338     key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
339     key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
340
341     def __init__ (self, sharps, flats, minor):
342         self.clocks = 0
343         self.flats = flats
344         self.sharps = sharps
345         self.minor = minor
346
347     def dump (self):
348         global_options.key = self
349
350         s = ''
351         if self.sharps and self.flats:
352             pass
353         else:
354             if self.flats:
355                 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
356             else:
357                 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
358  
359             if not self.minor:
360                 name = chr ((k + 2) % 7 + ord ('a'))
361             else:
362                 name = chr ((k + 2) % 7 + ord ('a'))
363
364             # fis cis gis dis ais eis bis
365             sharps = (2, 4, 6, 1, 3, 5, 7)
366             # bes es as des ges ces fes
367             flats = (6, 4, 2, 7, 5, 3, 1)
368             a = 0
369             if self.flats:
370                 if flats[k] <= self.flats:
371                     a = -1
372             else:
373                 if sharps[k] <= self.sharps:
374                     a = 1
375
376             if a:
377                 name = name + Note.alteration_names[a + 2]
378
379             s = '\\key ' + name
380             if self.minor:
381                 s = s + ' \\minor'
382             else:
383                 s = s + ' \\major'
384
385         return '\n\n  ' + s + '\n  '
386
387
388 class Text:
389     text_types = (
390         'SEQUENCE_NUMBER',
391         'TEXT_EVENT',
392         'COPYRIGHT_NOTICE',
393         'SEQUENCE_TRACK_NAME',
394         'INSTRUMENT_NAME',
395         'LYRIC',
396         'MARKER',
397         'CUE_POINT',)
398     
399     def __init__ (self, type, text):
400         self.clocks = 0
401         self.type = type
402         self.text = text
403
404     def dump (self):
405         # urg, we should be sure that we're in a lyrics staff
406         if self.type == midi.LYRIC:
407             s = '"%s"' % self.text
408             d = Duration (self.clocks)
409             if global_options.explicit_durations \
410              or d.compare (reference_note.duration):
411                 s = s + Duration (self.clocks).dump ()
412             s = s + ' '
413         else:
414             s = '\n  % [' + self.text_types[self.type] + '] ' + self.text + '\n  '
415         return s
416
417     def __repr__ (self):
418         return 'Text(%d=%s)' % (self.type, self.text)
419
420
421
422 def split_track (track):
423     chs = {}
424     for i in range(16):
425         chs[i] = []
426         
427     for e in track:
428         data = list (e[1])
429         if data[0] > 0x7f and data[0] < 0xf0:
430             c = data[0] & 0x0f
431             e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
432             chs[c].append (e)
433         else:
434             chs[0].append (e)
435
436     for i in range (16):
437         if chs[i] == []:
438             del chs[i]
439
440     threads = []
441     for v in chs.values ():
442         events = events_on_channel (v)
443         thread = unthread_notes (events)
444         if len (thread):
445             threads.append (thread)
446     return threads
447
448
449 def quantise_clocks (clocks, quant):
450     q = int (clocks / quant) * quant
451     if q != clocks:
452         for tquant in allowed_tuplet_clocks:
453             if int (clocks / tquant) * tquant == clocks:
454                 return clocks
455         if 2 * (clocks - q) > quant:
456             q = q + quant
457     return q
458
459 def end_note (pitches, notes, t, e):
460     try:
461         (lt, vel) = pitches[e]
462         del pitches[e]
463
464         i = len (notes) - 1 
465         while i > 0:
466             if notes[i][0] > lt:
467                 i = i -1
468             else:
469                 break
470         d = t - lt
471         if duration_quant_clocks:
472             d = quantise_clocks (d, duration_quant_clocks)
473             if not d:
474                 d = duration_quant_clocks
475
476         notes.insert (i + 1,
477               (lt, Note (d, e, vel)))
478
479     except KeyError:
480         pass
481
482 def events_on_channel (channel):
483     pitches = {}
484
485     notes = []
486     events = []
487     last_lyric = 0
488     last_time = 0
489     for e in channel:
490         t = e[0]
491
492         if start_quant_clocks:
493             t = quantise_clocks (t, start_quant_clocks)
494
495
496         if e[1][0] == midi.NOTE_OFF \
497          or (e[1][0] == midi.NOTE_ON and e[1][2] == 0):
498             end_note (pitches, notes, t, e[1][1])
499             
500         elif e[1][0] == midi.NOTE_ON:
501             if not pitches.has_key (e[1][1]):
502                 pitches[e[1][1]] = (t, e[1][2])
503                 
504         # all include ALL_NOTES_OFF
505         elif e[1][0] >= midi.ALL_SOUND_OFF \
506           and e[1][0] <= midi.POLY_MODE_ON:
507             for i in pitches.keys ():
508                 end_note (pitches, notes, t, i)
509                 
510         elif e[1][0] == midi.META_EVENT:
511             if e[1][1] == midi.END_OF_TRACK:
512                 for i in pitches.keys ():
513                     end_note (pitches, notes, t, i)
514                 break
515
516             elif e[1][1] == midi.SET_TEMPO:
517                 (u0, u1, u2) = map (ord, e[1][2])
518                 us_per_4 = u2 + 256 * (u1 + 256 * u0)
519                 seconds_per_1 = us_per_4 * 4 / 1e6
520                 events.append ((t, Tempo (seconds_per_1)))
521             elif e[1][1] == midi.TIME_SIGNATURE:
522                 (num, dur, clocks4, count32) = map (ord, e[1][2])
523                 den = 2 ** dur 
524                 events.append ((t, Time (num, den)))
525             elif e[1][1] == midi.KEY_SIGNATURE:
526                 (alterations, minor) = map (ord, e[1][2])
527                 sharps = 0
528                 flats = 0
529                 if alterations < 127:
530                     sharps = alterations
531                 else:
532                     flats = 256 - alterations
533
534                 k = Key (sharps, flats, minor)
535                 events.append ((t, k))
536
537                 # ugh, must set key while parsing
538                 # because Note init uses key
539                 # Better do Note.calc () at dump time?
540                 global_options.key = k
541
542             elif e[1][1] == midi.LYRIC \
543               or (global_options.text_lyrics and e[1][1] == midi.TEXT_EVENT):
544                 if last_lyric:
545                     last_lyric.clocks = t - last_time
546                     events.append ((last_time, last_lyric))
547                 last_time = t
548                 last_lyric = Text (midi.LYRIC, e[1][2])
549
550             elif e[1][1] >= midi.SEQUENCE_NUMBER \
551               and e[1][1] <= midi.CUE_POINT:
552                 events.append ((t, Text (e[1][1], e[1][2])))
553             else:
554                 if global_options.verbose:
555                     sys.stderr.write ("SKIP: %s\n" % `e`)
556                 pass
557         else:
558             if global_options.verbose:
559                 sys.stderr.write ("SKIP: %s\n" % `e`)
560             pass
561
562     if last_lyric:
563         # last_lyric.clocks = t - last_time
564         # hmm
565         last_lyric.clocks = clocks_per_4
566         events.append ((last_time, last_lyric))
567         last_lyric = 0
568         
569     i = 0
570     while len (notes):
571         if i < len (events) and notes[0][0] >= events[i][0]:
572             i = i + 1
573         else:
574             events.insert (i, notes[0])
575             del notes[0]
576     return events
577
578 def unthread_notes (channel):
579     threads = []
580     while channel:
581         thread = []
582         end_busy_t = 0
583         start_busy_t = 0
584         todo = []
585         for e in channel:
586             t = e[0]
587             if e[1].__class__ == Note \
588              and ((t == start_busy_t \
589                 and e[1].clocks + t == end_busy_t) \
590               or t >= end_busy_t):
591                 thread.append (e)
592                 start_busy_t = t
593                 end_busy_t = t + e[1].clocks
594             elif e[1].__class__ == Time \
595               or e[1].__class__ == Key \
596               or e[1].__class__ == Text \
597               or e[1].__class__ == Tempo:
598                 thread.append (e)
599             else:
600                 todo.append (e)
601         threads.append (thread)
602         channel = todo
603
604     return threads
605
606 def gcd (a,b):
607     if b == 0:
608         return a
609     c = a
610     while c: 
611         c = a % b
612         a = b
613         b = c
614     return a
615     
616 def dump_skip (skip, clocks):
617     return skip + Duration (clocks).dump () + ' '
618
619 def dump (d):
620     return d.dump ()
621
622 def dump_chord (ch):
623     s = ''
624     notes = []
625     for i in ch:
626         if i.__class__ == Note:
627             notes.append (i)
628         else:
629             s = s + i.dump ()
630     if len (notes) == 1:
631         s = s + dump (notes[0])
632     elif len (notes) > 1:
633         global reference_note
634         s = s + '<'
635         s = s + notes[0].dump (dump_dur = 0)
636         r = reference_note
637         for i in notes[1:]:
638             s = s + i.dump (dump_dur = 0 )
639         s = s + '>'
640
641         s = s + notes[0].duration.dump() + ' '
642         reference_note = r
643     return s
644
645 def dump_bar_line (last_bar_t, t, bar_count):
646     s = ''
647     bar_t = time.bar_clocks ()
648     if t - last_bar_t >= bar_t:
649         bar_count = bar_count + (t - last_bar_t) / bar_t
650         
651         if t - last_bar_t == bar_t:
652             s = '|\n  %% %d\n  ' % bar_count
653             last_bar_t = t
654         else:
655             # urg, this will barf at meter changes
656             last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
657             
658     return (s, last_bar_t, bar_count)
659
660             
661 def dump_channel (thread, skip):
662     global reference_note, time
663
664     global_options.key = Key (0, 0, 0)
665     time = Time (4, 4)
666     # urg LilyPond doesn't start at c4, but
667     # remembers from previous tracks!
668     # reference_note = Note (clocks_per_4, 4*12, 0)
669     reference_note = Note (0, 4*12, 0)
670     last_e = None
671     chs = []
672     ch = []
673
674     for e in thread:
675         if last_e and last_e[0] == e[0]:
676             ch.append (e[1])
677         else:
678             if ch:
679                 chs.append ((last_e[0], ch))
680                 
681             ch = [e[1]]
682             
683         last_e = e
684
685     if ch:
686         chs.append ((last_e[0], ch))
687     t = 0
688     last_t = 0
689     last_bar_t = 0
690     bar_count = 1
691     
692     lines = ['']
693     for ch in chs: 
694         t = ch[0]
695
696         i = string.rfind (lines[-1], '\n') + 1
697         if len (lines[-1][i:]) > LINE_BELL:
698             lines.append ('')
699             
700         if t - last_t > 0:
701             lines[-1] = lines[-1] + dump_skip (skip, t-last_t)
702         elif t - last_t < 0:
703             errorport.write ('BUG: time skew')
704
705         (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
706                               t, bar_count)
707         lines[-1] = lines[-1] + s
708         
709         lines[-1] = lines[-1] + dump_chord (ch[1])
710
711         clocks = 0
712         for i in ch[1]:
713             if i.clocks > clocks:
714                 clocks = i.clocks
715                 
716         last_t = t + clocks
717         
718         (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
719                               last_t, bar_count)
720         lines[-1] = lines[-1] + s
721
722     return string.join (lines, '\n  ') + '\n'
723
724 def track_name (i):
725     return 'track%c' % (i + ord ('A'))
726
727 def channel_name (i):
728     return 'channel%c' % (i + ord ('A'))
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).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.18"\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='midi2ly [OPTIONS] FILE',
870                  version="midi2ly (LilyPond) @TOPLEVEL_VERSION@",
871                  description=_('''Convert MIDI to LilyPond source.'''))
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('-k', '--key', help=_ ("set key: ALT=+sharps|-flats; MINOR=1"),
883           metavar=_ ("ALT[:MINOR]"),
884           default='0'),
885     p.add_option ('-o', '--output', help=_("write output to FILE"),
886            metavar=_("FILE"),
887            action='store')
888     p.add_option ('-s', '--start-quant',help= _ ("quantise note starts on DUR"),
889            metavar=_ ("DUR"))
890     p.add_option ('-t', '--allow-tuplet',
891            metavar=_ ("DUR*NUM/DEN"),
892            action = "append",
893            dest="allowed_tuplets",
894            help=_ ("allow tuplet durations DUR*NUM/DEN"),
895            default=[])
896     p.add_option ('-V', '--verbose', help=_("be verbose"),
897            action='store_true'
898            ),
899     p.add_option ('-w', '--warranty', help=_("show warranty"),
900            action='store_true',
901            ),
902     p.add_option ('-x', '--text-lyrics', help=_("treat every text as a lyric"),
903            action='store_true')
904
905     p.add_option_group (_ ("example"),
906               description = r'''
907   midi2ly --key=-2:1 --duration-quant=32 \
908     --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
909 ''')
910     
911     p.add_option_group  ('bugs',
912               description='''Report bugs via http://post.gmane.org/post.php'''
913               '''?group=gmane.comp.gnu.lilypond.bugs\n''')
914     
915     return p
916
917
918
919 def do_options ():
920     opt_parser = get_option_parser()
921     (options, args) = opt_parser.parse_args ()
922
923     if not args or args[0] == '-':
924         opt_parser.print_help ()
925         sys.stderr.write ('\n%s: %s %s\n' % (program_name, _ ("error: "),
926                           _ ("no files specified on command line.")))
927         sys.exit (2)
928
929     if options.duration_quant:
930         options.duration_quant = int (options.duration_quant)
931
932     if options.warranty:
933         warranty ()
934         sys.exit (0)
935     if 1:
936         (alterations, minor) = map (int, string.split (options.key + ':0', ':'))[0:2]
937         sharps = 0
938         flats = 0
939         if alterations >= 0:
940             sharps = alterations
941         else:
942             flats = - alterations
943
944         options.key = Key (sharps, flats, minor)
945
946         
947     if options.start_quant:
948         options.start_quant = int (options.start_quant)
949         
950     options.allowed_tuplets = [map (int, a.replace ('/','*').split ('*'))
951                 for a in options.allowed_tuplets]
952     
953     global global_options
954     global_options = options
955
956     return args
957
958 def main():
959     files = do_options()
960
961     for f in files:
962         g = f
963         g = strip_extension (g, '.midi')
964         g = strip_extension (g, '.mid')
965         g = strip_extension (g, '.MID')
966         (outdir, outbase) = ('','')
967
968         if not output_name:
969             outdir = '.'
970             outbase = os.path.basename (g)
971             o = os.path.join (outdir, outbase + '-midi.ly')
972         elif output_name[-1] == os.sep:
973             outdir = output_name
974             outbase = os.path.basename (g)
975             os.path.join (outdir, outbase + '-gen.ly')
976         else:
977             o = output_name
978             (outdir, outbase) = os.path.split (o)
979
980         if outdir != '.' and outdir != '':
981             try:
982                 os.mkdir (outdir, 0777)
983             except OSError:
984                 pass
985
986         convert_midi (f, o)
987 if __name__ == '__main__':
988     main()