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