]> git.donarmstrong.com Git - lilypond.git/blob - scripts/midi2ly.py
Issue4986: Fix XeLaTex option consistent with XeTeX option
[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
387     def __init__ (self, type, text):
388         self.clocks = 0
389         self.type = type
390         self.text = text
391
392     def dump (self):
393         # urg, we should be sure that we're in a lyrics staff
394         s = ''
395         if self.type == midi.LYRIC:
396             s = '"%s"' % self.text
397             d = Duration (self.clocks)
398             if (global_options.explicit_durations
399                 or d.compare (reference_note.duration)):
400                 s = s + Duration (self.clocks).dump ()
401             s = s + ' '
402         elif (self.text.strip ()
403               and self.type == midi.SEQUENCE_TRACK_NAME
404               and not self.text == 'control track'
405               and not self.track.lyrics_p_):
406             text = self.text.replace ('(MIDI)', '').strip ()
407             if text:
408                 s = '\n  \\set Staff.instrumentName = "%(text)s"\n  ' % locals ()
409         elif self.text.strip ():
410             s = '\n  % [' + self.text_types[self.type] + '] ' + self.text + '\n  '
411         return s
412
413     def __repr__ (self):
414         return 'Text(%d=%s)' % (self.type, self.text)
415
416 def get_voice (channel, music):
417     debug ('channel: ' + str (channel) + '\n')
418     return unthread_notes (music)
419
420 class Channel:
421     def __init__ (self, number):
422         self.number = number
423         self.events = []
424         self.music = None
425     def add (self, event):
426         self.events.append (event)
427     def get_voice (self):
428         if not self.music:
429             self.music = self.parse ()
430         return get_voice (self.number, self.music)
431     def parse (self):
432         pitches = {}
433         notes = []
434         music = []
435         last_lyric = 0
436         last_time = 0
437         for e in self.events:
438             t = e[0]
439
440             if start_quant_clocks:
441                 t = quantise_clocks (t, start_quant_clocks)
442
443             if (e[1][0] == midi.NOTE_OFF
444                 or (e[1][0] == midi.NOTE_ON and e[1][2] == 0)):
445                 debug ('%d: NOTE OFF: %s' % (t, e[1][1]))
446                 if not e[1][2]:
447                     debug ('   ...treated as OFF')
448                 end_note (pitches, notes, t, e[1][1])
449
450             elif e[1][0] == midi.NOTE_ON:
451                 if not pitches.has_key (e[1][1]):
452                     debug ('%d: NOTE ON: %s' % (t, e[1][1]))
453                     pitches[e[1][1]] = (t, e[1][2])
454                 else:
455                     debug ('...ignored')
456
457             # all include ALL_NOTES_OFF
458             elif (e[1][0] >= midi.ALL_SOUND_OFF
459               and e[1][0] <= midi.POLY_MODE_ON):
460                 for i in pitches:
461                     end_note (pitches, notes, t, i)
462
463             elif e[1][0] == midi.META_EVENT:
464                 if e[1][1] == midi.END_OF_TRACK:
465                     for i in pitches:
466                         end_note (pitches, notes, t, i)
467                     break
468
469                 elif e[1][1] == midi.SET_TEMPO:
470                     (u0, u1, u2) = map (ord, e[1][2])
471                     us_per_4 = u2 + 256 * (u1 + 256 * u0)
472                     seconds_per_1 = us_per_4 * 4 / 1e6
473                     music.append ((t, Tempo (seconds_per_1)))
474                 elif e[1][1] == midi.TIME_SIGNATURE:
475                     (num, dur, clocks4, count32) = map (ord, e[1][2])
476                     den = 2 ** dur
477                     music.append ((t, Time (num, den)))
478                 elif e[1][1] == midi.KEY_SIGNATURE:
479                     (alterations, minor) = map (ord, e[1][2])
480                     sharps = 0
481                     flats = 0
482                     if alterations < 127:
483                         sharps = alterations
484                     else:
485                         flats = 256 - alterations
486
487                     k = Key (sharps, flats, minor)
488                     if not t and global_options.key:
489                         # At t == 0, a set --key overrides us
490                         k = global_options.key
491                     music.append ((t, k))
492
493                     # ugh, must set key while parsing
494                     # because Note init uses key
495                     # Better do Note.calc () at dump time?
496                     global_options.key = k
497
498                 elif (e[1][1] == midi.LYRIC
499                       or (global_options.text_lyrics
500                           and e[1][1] == midi.TEXT_EVENT)):
501                     self.lyrics_p_ = True
502                     if last_lyric:
503                         last_lyric.clocks = t - last_time
504                         music.append ((last_time, last_lyric))
505                     last_time = t
506                     last_lyric = Text (midi.LYRIC, e[1][2])
507
508                 elif (e[1][1] >= midi.SEQUENCE_NUMBER
509                       and e[1][1] <= midi.CUE_POINT):
510                     text = Text (e[1][1], e[1][2])
511                     text.track = self
512                     music.append ((t, text))
513                     if (text.type == midi.SEQUENCE_TRACK_NAME):
514                         self.name = text.text
515                 else:
516                     if global_options.verbose:
517                         sys.stderr.write ("SKIP: %s\n" % `e`)
518             else:
519                 if global_options.verbose:
520                     sys.stderr.write ("SKIP: %s\n" % `e`)
521
522         if last_lyric:
523             # last_lyric.clocks = t - last_time
524             # hmm
525             last_lyric.clocks = clocks_per_4
526             music.append ((last_time, last_lyric))
527             last_lyric = 0
528
529         i = 0
530         while len (notes):
531             if i < len (music) and notes[0][0] >= music[i][0]:
532                 i = i + 1
533             else:
534                 music.insert (i, notes[0])
535                 del notes[0]
536         return music
537     
538 class Track (Channel):
539     def __init__ (self):
540         Channel.__init__ (self, None)
541         self.name = None
542         self.channels = {}
543         self.lyrics_p_ = False
544     def _add (self, event):
545         self.events.append (event)
546     def add (self, event, channel=None):
547         if channel == None:
548             self._add (event)
549         else:
550             self.channels[channel] = self.channels.get (channel, Channel (channel))
551             self.channels[channel].add (event)
552     def get_voices (self):
553         return ([self.get_voice ()]
554                 + [self.channels[k].get_voice ()
555                    for k in sorted (self.channels.keys ())])
556
557 def create_track (events):
558     track = Track ()
559     for e in events:
560         data = list (e[1])
561         if data[0] > 0x7f and data[0] < 0xf0:
562             channel = data[0] & 0x0f
563             e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
564             track.add (e, channel)
565         else:
566             track.add (e)
567     return track
568
569 def quantise_clocks (clocks, quant):
570     q = int (clocks / quant) * quant
571     if q != clocks:
572         for tquant in allowed_tuplet_clocks:
573             if int (clocks / tquant) * tquant == clocks:
574                 return clocks
575         if 2 * (clocks - q) > quant:
576             q = q + quant
577     return q
578
579 def end_note (pitches, notes, t, e):
580     try:
581         (lt, vel) = pitches[e]
582         del pitches[e]
583
584         i = len (notes) - 1
585         while i > 0:
586             if notes[i][0] > lt:
587                 i = i -1
588             else:
589                 break
590         d = t - lt
591         if duration_quant_clocks:
592             d = quantise_clocks (d, duration_quant_clocks)
593             if not d:
594                 d = duration_quant_clocks
595
596         notes.insert (i + 1,
597               (lt, Note (d, e, vel)))
598
599     except KeyError:
600         pass
601
602 def unthread_notes (channel):
603     threads = []
604     while channel:
605         thread = []
606         end_busy_t = 0
607         start_busy_t = 0
608         todo = []
609         for e in channel:
610             t = e[0]
611             if (e[1].__class__ == Note
612                 and ((t == start_busy_t
613                       and e[1].clocks + t == end_busy_t)
614                      or t >= end_busy_t)):
615                 thread.append (e)
616                 start_busy_t = t
617                 end_busy_t = t + e[1].clocks
618             elif (e[1].__class__ == Time
619                   or e[1].__class__ == Key
620                   or e[1].__class__ == Text
621                   or e[1].__class__ == Tempo):
622                 thread.append (e)
623             else:
624                 todo.append (e)
625         threads.append (thread)
626         channel = todo
627
628     return threads
629
630 def gcd (a,b):
631     if b == 0:
632         return a
633     c = a
634     while c:
635         c = a % b
636         a = b
637         b = c
638     return a
639
640 def dump_skip (skip, clocks):
641     return skip + Duration (clocks).dump () + ' '
642
643 def dump (d):
644     return d.dump ()
645
646 def dump_chord (ch):
647     s = ''
648     notes = []
649     for i in ch:
650         if i.__class__ == Note:
651             notes.append (i)
652         else:
653             s = s + i.dump ()
654     if len (notes) == 1:
655         s = s + dump (notes[0])
656     elif len (notes) > 1:
657         global reference_note
658         reference_dur = reference_note.duration
659         s = s + '<'
660         s = s + notes[0].dump (dump_dur=False)
661         r = reference_note
662         for i in notes[1:]:
663             s = s + i.dump (dump_dur=False)
664         s = s + '>'
665         if (r.duration.compare (reference_dur)
666             or global_options.explicit_durations):
667             s = s + r.duration.dump ()
668         s = s + ' '
669         reference_note = r
670     return s
671
672 def dump_bar_line (last_bar_t, t, bar_count):
673     s = ''
674     bar_t = time.bar_clocks ()
675     if t - last_bar_t >= bar_t:
676         bar_count = bar_count + (t - last_bar_t) / bar_t
677
678         if t - last_bar_t == bar_t:
679             s = '\n  | %% %(bar_count)d\n  ' % locals ()
680             last_bar_t = t
681         else:
682             # urg, this will barf at meter changes
683             last_bar_t = last_bar_t + (t - last_bar_t) / bar_t * bar_t
684
685     return (s, last_bar_t, bar_count)
686
687
688 def dump_voice (thread, skip):
689     global reference_note, time
690     ref = Note (0, 4*12, 0)
691     if not reference_note:
692         reference_note = ref
693     else:
694         ref.duration = reference_note.duration
695         reference_note = ref
696     last_e = None
697     chs = []
698     ch = []
699
700     for e in thread:
701         if last_e and last_e[0] == e[0]:
702             ch.append (e[1])
703         else:
704             if ch:
705                 chs.append ((last_e[0], ch))
706
707             ch = [e[1]]
708
709         last_e = e
710
711     if ch:
712         chs.append ((last_e[0], ch))
713     t = 0
714     last_t = 0
715     last_bar_t = 0
716     bar_count = 1
717
718     lines = ['']
719     for ch in chs:
720         t = ch[0]
721
722         i = lines[-1].rfind ('\n') + 1
723         if len (lines[-1][i:]) > LINE_BELL:
724             lines.append ('')
725
726         if t - last_t > 0:
727             d = t - last_t
728             if bar_max and t > time.bar_clocks () * bar_max:
729                 d = time.bar_clocks () * bar_max - last_t
730             lines[-1] = lines[-1] + dump_skip (skip, d)
731         elif t - last_t < 0:
732             errorport.write ('BUG: time skew')
733
734         (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
735                               t, bar_count)
736
737         if bar_max and bar_count > bar_max:
738             break
739
740         lines[-1] = lines[-1] + s
741         lines[-1] = lines[-1] + dump_chord (ch[1])
742
743         clocks = 0
744         for i in ch[1]:
745             if i.clocks > clocks:
746                 clocks = i.clocks
747
748         last_t = t + clocks
749
750         (s, last_bar_t, bar_count) = dump_bar_line (last_bar_t,
751                                                     last_t, bar_count)
752         lines[-1] = lines[-1] + s
753
754     return '\n  '.join (lines) + '\n'
755
756 def number2ascii (i):
757     s = ''
758     i += 1
759     while i > 0:
760         m = (i - 1) % 26
761         s = '%c' % (m + ord ('A')) + s
762         i = (i - m)/26
763     return s
764
765 def get_track_name (i):
766     return 'track' + number2ascii (i)
767
768 def get_channel_name (i):
769     return 'channel' + number2ascii (i)
770
771 def get_voice_name (i, zero_too_p=False):
772     if i or zero_too_p:
773         return 'voice' + number2ascii (i)
774     return ''
775
776 def lst_append (lst, x):
777     lst.append (x)
778     return lst
779
780 def get_voice_layout (average_pitch):
781     d = {}
782     for i in range (len (average_pitch)):
783         d[average_pitch[i]] = lst_append (d.get (average_pitch[i], []), i)
784     s = list (reversed (sorted (average_pitch)))
785     non_empty = len (filter (lambda x: x, s))
786     names = ['One', 'Two']
787     if non_empty > 2:
788         names = ['One', 'Three', 'Four', 'Two']
789     layout = map (lambda x: '', range (len (average_pitch)))
790     for i, n in zip (s, names):
791         if i:
792             v = d[i]
793             if type (v) == list:
794                 d[i] = v[1:]
795                 v = v[0]
796             layout[v] = n
797     return layout
798
799 def dump_track (track, n):
800     s = '\n'
801     track_name = get_track_name (n)
802
803     average_pitch = track_average_pitch (track)
804     voices = len (filter (lambda x: x, average_pitch[1:]))
805     clef = get_best_clef (average_pitch[0])
806
807     c = 0
808     vv = 0
809     for channel in track:
810         v = 0
811         channel_name = get_channel_name (c)
812         c += 1
813         for voice in channel:
814             voice_name = get_voice_name (v)
815             voice_id = track_name + channel_name + voice_name
816             item = voice_first_item (voice)
817
818             if item and item.__class__ == Note:
819                 skip = 'r'
820                 if global_options.skip:
821                     skip = 's'
822                 s += '%(voice_id)s = ' % locals ()
823                 if not global_options.absolute_pitches:
824                     s += '\\relative c '
825             elif item and item.__class__ == Text:
826                 skip = '" "'
827                 s += '%(voice_id)s = \\lyricmode ' % locals ()
828             else:
829                 skip = '\\skip '
830                 s += '%(voice_id)s = ' % locals ()
831             s += '{\n'
832             if not n and not vv and global_options.key:
833                 s += global_options.key.dump ()
834             if average_pitch[vv+1] and voices > 1:
835                 vl = get_voice_layout (average_pitch[1:])[vv]
836                 if vl:
837                     s += '  \\voice' + vl + '\n'
838                 else:
839                     if not global_options.quiet:
840                         warning (_ ('found more than 5 voices on a staff, expect bad output'))
841             s += '  ' + dump_voice (voice, skip)
842             s += '}\n\n'
843             v += 1
844             vv += 1
845
846     s += '%(track_name)s = <<\n' % locals ()
847
848     if clef.type != 2:
849         s += clef.dump () + '\n'
850
851     c = 0
852     vv = 0
853     for channel in track:
854         v = 0
855         channel_name = get_channel_name (c)
856         c += 1
857         for voice in channel:
858             voice_context_name = get_voice_name (vv, zero_too_p=True)
859             voice_name = get_voice_name (v)
860             v += 1
861             vv += 1
862             voice_id = track_name + channel_name + voice_name
863             item = voice_first_item (voice)
864             context = 'Voice'
865             if item and item.__class__ == Text:
866                 context = 'Lyrics'
867             s += '  \\context %(context)s = %(voice_context_name)s \\%(voice_id)s\n' % locals ()
868     s += '>>\n\n'
869     return s
870
871 def voice_first_item (voice):
872     for event in voice:
873         if (event[1].__class__ == Note
874             or (event[1].__class__ == Text
875                 and event[1].type == midi.LYRIC)):
876             return event[1]
877     return None
878
879 def channel_first_item (channel):
880     for voice in channel:
881         first = voice_first_item (voice)
882         if first:
883             return first
884     return None
885
886 def track_first_item (track):
887     for channel in track:
888         first = channel_first_item (channel)
889         if first:
890             return first
891     return None
892
893 def track_average_pitch (track):
894     i = 0
895     p = [0]
896     v = 1
897     for channel in track:
898         for voice in channel:
899             c = 0
900             p.append (0)
901             for event in voice:
902                 if event[1].__class__ == Note:
903                     i += 1
904                     c += 1
905                     p[v] += event[1].pitch
906             if c:
907                 p[0] += p[v]
908                 p[v] = p[v] / c
909             v += 1
910     if i:
911         p[0] = p[0] / i
912     return p
913
914 def get_best_clef (average_pitch):
915     if average_pitch:
916         if average_pitch <= 3*12:
917             return Clef (0)
918         elif average_pitch <= 5*12:
919             return Clef (1)
920         elif average_pitch >= 7*12:
921             return Clef (3)
922     return Clef (2)
923
924 class Staff:
925     def __init__ (self, track):
926         self.voices = track.get_voices ()
927     def dump (self, i):
928         return dump_track (self.voices, i)
929
930 def convert_midi (in_file, out_file):
931     global midi
932     import midi
933
934     global clocks_per_1, clocks_per_4, key
935     global start_quant_clocks
936     global duration_quant_clocks
937     global allowed_tuplet_clocks
938     global time
939
940     str = open (in_file, 'rb').read ()
941     clocks_max = bar_max * clocks_per_1 * 2
942     midi_dump = midi.parse (str, clocks_max)
943
944     clocks_per_1 = midi_dump[0][1]
945     clocks_per_4 = clocks_per_1 / 4
946     time = Time (4, 4)
947
948     if global_options.start_quant:
949         start_quant_clocks = clocks_per_1 / global_options.start_quant
950
951     if global_options.duration_quant:
952         duration_quant_clocks = clocks_per_1 / global_options.duration_quant
953
954     allowed_tuplet_clocks = []
955     for (dur, num, den) in global_options.allowed_tuplets:
956         allowed_tuplet_clocks.append (clocks_per_1 / dur * num / den)
957
958     if global_options.verbose:
959         print 'allowed tuplet clocks:', allowed_tuplet_clocks
960
961     tracks = [create_track (t) for t in midi_dump[1]]
962     # urg, parse all global track events, such as Key first
963     # this fixes key in different voice/staff problem
964     for t in tracks:
965         t.music = t.parse ()
966     prev = None
967     staves = []
968     for t in tracks:
969         voices = t.get_voices ()
970         if ((t.name and prev and prev.name)
971             and t.name.split (':')[0] == prev.name.split (':')[0]):
972             # staves[-1].voices += voices
973             # all global track events first
974             staves[-1].voices = ([staves[-1].voices[0]]
975                                  + [voices[0]]
976                                  + staves[-1].voices[1:]
977                                  + voices[1:])
978         else:
979             staves.append (Staff (t))
980         prev = t
981
982     tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, in_file)
983
984
985     s = tag
986     s += r'''
987 \version "2.14.0"
988 '''
989
990     s += r'''
991 \layout {
992   \context {
993     \Voice
994     \remove "Note_heads_engraver"
995     \consists "Completion_heads_engraver"
996     \remove "Rest_engraver"
997     \consists "Completion_rest_engraver"
998   }
999 }
1000 '''
1001
1002     for i in global_options.include_header:
1003         s += '\n%% included from %(i)s\n' % locals ()
1004         s += open (i).read ()
1005         if s[-1] != '\n':
1006             s += '\n'
1007         s += '% end\n'
1008
1009     for i, t in enumerate (staves):
1010         s += t.dump (i)
1011
1012     s += '\n\\score {\n  <<\n'
1013
1014     control_track = False
1015     i = 0
1016     for i, staff in enumerate (staves):
1017         track_name = get_track_name (i)
1018         item = track_first_item (staff.voices)
1019         staff_name = track_name
1020         context = None
1021         if not i and not item and len (staves) > 1:
1022             control_track = track_name
1023             continue
1024         elif (item and item.__class__ == Note):
1025             context = 'Staff'
1026             if control_track:
1027                 s += '    \\context %(context)s=%(staff_name)s \\%(control_track)s\n' % locals ()
1028         elif item and item.__class__ == Text:
1029             context = 'Lyrics'
1030         if context:
1031             s += '    \\context %(context)s=%(staff_name)s \\%(track_name)s\n' % locals ()
1032
1033     s = s + '''  >>
1034   \layout {}
1035   \midi {}
1036 }
1037 '''
1038
1039     if not global_options.quiet:
1040         progress (_ ("%s output to `%s'...") % ('LY', out_file))
1041
1042     if out_file == '-':
1043         handle = sys.stdout
1044     else:
1045         handle = open (out_file, 'w')
1046
1047     handle.write (s)
1048     handle.close ()
1049
1050
1051 def get_option_parser ():
1052     p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'midi2ly',
1053                  description=_ ("Convert %s to LilyPond input.\n") % 'MIDI',
1054                  add_help_option=False)
1055
1056     p.add_option ('-a', '--absolute-pitches',
1057            action='store_true',
1058            help=_ ('print absolute pitches'))
1059     p.add_option ('-d', '--duration-quant',
1060            metavar=_ ('DUR'),
1061            help=_ ('quantise note durations on DUR'))
1062     p.add_option ('-D', '--debug',
1063            action='store_true',
1064            help=_ ('debug printing'))
1065     p.add_option ('-e', '--explicit-durations',
1066            action='store_true',
1067            help=_ ('print explicit durations'))
1068     p.add_option('-h', '--help',
1069            action='help',
1070            help=_ ('show this help and exit'))
1071     p.add_option('-i', '--include-header',
1072            help=_ ('prepend FILE to output'),
1073            action='append',
1074            default=[],
1075            metavar=_ ('FILE'))
1076     p.add_option('-k', '--key', help=_ ('set key: ALT=+sharps|-flats; MINOR=1'),
1077            metavar=_ ('ALT[:MINOR]'),
1078            default=None),
1079     p.add_option ('-o', '--output', help=_ ('write output to FILE'),
1080            metavar=_ ('FILE'),
1081            action='store')
1082     p.add_option ('-p', '--preview', help=_ ('preview of first 4 bars'),
1083            action='store_true')
1084     p.add_option ('-q', '--quiet',
1085            action="store_true",
1086            help=_ ("suppress progress messages and warnings about excess voices"))
1087     p.add_option ('-s', '--start-quant',help= _ ('quantise note starts on DUR'),
1088            metavar=_ ('DUR'))
1089     p.add_option ('-S', '--skip',
1090            action = "store_true",
1091            help =_ ("use s instead of r for rests"))
1092     p.add_option ('-t', '--allow-tuplet',
1093            metavar=_ ('DUR*NUM/DEN'),
1094            action = 'append',
1095            dest='allowed_tuplets',
1096            help=_ ('allow tuplet durations DUR*NUM/DEN'),
1097            default=[])
1098     p.add_option ('-V', '--verbose', help=_ ('be verbose'),
1099            action='store_true')
1100     p.version = 'midi2ly (LilyPond) @TOPLEVEL_VERSION@'
1101     p.add_option ('--version',
1102                  action='version',
1103                  help=_ ('show version number and exit'))
1104     p.add_option ('-w', '--warranty', help=_ ('show warranty and copyright'),
1105            action='store_true',)
1106     p.add_option ('-x', '--text-lyrics', help=_ ('treat every text as a lyric'),
1107            action='store_true')
1108
1109     p.add_option_group (ly.display_encode (_ ('Examples')),
1110               description = r'''
1111   $ midi2ly --key=-2:1 --duration-quant=32 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
1112 ''')
1113     p.add_option_group ('',
1114                         description=(
1115             _ ('Report bugs via %s')
1116             % 'http://post.gmane.org/post.php'
1117             '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
1118     return p
1119
1120
1121
1122 def do_options ():
1123     opt_parser = get_option_parser ()
1124     (options, args) = opt_parser.parse_args ()
1125
1126     if options.warranty:
1127         warranty ()
1128         sys.exit (0)
1129
1130     if not args or args[0] == '-':
1131         opt_parser.print_help ()
1132         ly.stderr_write ('\n%s: %s %s\n' % (program_name, _ ('error: '),
1133                          _ ('no files specified on command line.')))
1134         sys.exit (2)
1135
1136     if options.duration_quant:
1137         options.duration_quant = int (options.duration_quant)
1138
1139     if options.key:
1140         (alterations, minor) = map (int, (options.key + ':0').split (':'))[0:2]
1141         sharps = 0
1142         flats = 0
1143         if alterations >= 0:
1144             sharps = alterations
1145         else:
1146             flats = - alterations
1147         options.key = Key (sharps, flats, minor)
1148
1149     if options.start_quant:
1150         options.start_quant = int (options.start_quant)
1151
1152     global bar_max
1153     if options.preview:
1154         bar_max = 4
1155
1156     options.allowed_tuplets = [map (int, a.replace ('/','*').split ('*'))
1157                 for a in options.allowed_tuplets]
1158
1159     if options.verbose:
1160         sys.stderr.write ('Allowed tuplets: %s\n' % `options.allowed_tuplets`)
1161
1162     global global_options
1163     global_options = options
1164
1165     return args
1166
1167 def main ():
1168     files = do_options ()
1169
1170     exts = ['.midi', '.mid', '.MID']
1171     for f in files:
1172         g = f
1173         for e in exts:
1174             g = strip_extension (g, e)
1175         if not os.path.exists (f):
1176             for e in exts:
1177                 n = g + e
1178                 if os.path.exists (n):
1179                     f = n
1180                     break
1181
1182         if not global_options.output:
1183             outdir = '.'
1184             outbase = os.path.basename (g)
1185             o = outbase + '-midi.ly'
1186         elif (global_options.output[-1] == os.sep
1187               or os.path.isdir (global_options.output)):
1188             outdir = global_options.output
1189             outbase = os.path.basename (g)
1190             o = os.path.join (outdir, outbase + '-midi.ly')
1191         else:
1192             o = global_options.output
1193             (outdir, outbase) = os.path.split (o)
1194
1195         if outdir and outdir != '.' and not os.path.exists (outdir):
1196             os.mkdir (outdir, 0777)
1197
1198         convert_midi (f, o)
1199
1200 if __name__ == '__main__':
1201     main ()