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