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