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