]> git.donarmstrong.com Git - lilypond.git/blob - scripts/midi2ly.py
Bring dev/johngourlay/issue-4751 up to date with respect to staging.
[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         reference_note = self
276
277         # TODO: move space
278         return s + ' '
279
280
281 class Time:
282     def __init__ (self, num, den):
283         self.clocks = 0
284         self.num = num
285         self.den = den
286
287     def bar_clocks (self):
288         return clocks_per_1 * self.num / self.den
289
290     def __repr__ (self):
291         return 'Time(%d/%d)' % (self.num, self.den)
292
293     def dump (self):
294         global time
295         time = self
296         return '\n  ' + '\\time %d/%d ' % (self.num, self.den) + '\n  '
297
298 class Tempo:
299     def __init__ (self, seconds_per_1):
300         self.clocks = 0
301         self.seconds_per_1 = seconds_per_1
302
303     def __repr__ (self):
304         return 'Tempo(%d)' % self.bpm ()
305
306     def bpm (self):
307         return 4 * 60 / self.seconds_per_1
308
309     def dump (self):
310         return '\n  ' + '\\tempo 4 = %d ' % (self.bpm ()) + '\n  '
311
312 class Clef:
313     clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
314     def __init__ (self, type):
315         self.type = type
316
317     def __repr__ (self):
318         return 'Clef(%s)' % self.clefs[self.type]
319
320     def dump (self):
321         return '\n  \\clef %s\n  ' % self.clefs[self.type]
322
323 class Key:
324     key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
325     key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
326
327     def __init__ (self, sharps, flats, minor):
328         self.clocks = 0
329         self.flats = flats
330         self.sharps = sharps
331         self.minor = minor
332
333     def dump (self):
334         global_options.key = self
335
336         s = ''
337         if self.sharps and self.flats:
338             pass
339         else:
340             if self.flats:
341                 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
342             else:
343                 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
344
345             if not self.minor:
346                 name = chr ((k + 2) % 7 + ord ('a'))
347             else:
348                 name = chr ((k + 2) % 7 + ord ('a'))
349
350             # fis cis gis dis ais eis bis
351             sharps = (2, 4, 6, 1, 3, 5, 7)
352             # bes es as des ges ces fes
353             flats = (6, 4, 2, 7, 5, 3, 1)
354             a = 0
355             if self.flats:
356                 if flats[k] <= self.flats:
357                     a = -1
358             else:
359                 if sharps[k] <= self.sharps:
360                     a = 1
361
362             if a:
363                 name = name + Note.alteration_names[a + 2]
364
365             s = '\\key ' + name
366             if self.minor:
367                 s = s + ' \\minor'
368             else:
369                 s = s + ' \\major'
370
371         return '\n\n  ' + s + '\n  '
372
373
374 class Text:
375     text_types = (
376         'SEQUENCE_NUMBER',
377         'TEXT_EVENT',
378         'COPYRIGHT_NOTICE',
379         'SEQUENCE_TRACK_NAME',
380         'INSTRUMENT_NAME',
381         'LYRIC',
382         'MARKER',
383         'CUE_POINT',)
384
385     def __init__ (self, type, text):
386         self.clocks = 0
387         self.type = type
388         self.text = text
389
390     def dump (self):
391         # urg, we should be sure that we're in a lyrics staff
392         s = ''
393         if self.type == midi.LYRIC:
394             s = '"%s"' % self.text
395             d = Duration (self.clocks)
396             if (global_options.explicit_durations
397                 or d.compare (reference_note.duration)):
398                 s = s + Duration (self.clocks).dump ()
399             s = s + ' '
400         elif (self.text.strip ()
401               and self.type == midi.SEQUENCE_TRACK_NAME
402               and not self.text == 'control track'
403               and not self.track.lyrics_p_):
404             text = self.text.replace ('(MIDI)', '').strip ()
405             if text:
406                 s = '\n  \\set Staff.instrumentName = "%(text)s"\n  ' % locals ()
407         elif self.text.strip ():
408             s = '\n  % [' + self.text_types[self.type] + '] ' + self.text + '\n  '
409         return s
410
411     def __repr__ (self):
412         return 'Text(%d=%s)' % (self.type, self.text)
413
414 def get_voice (channel, music):
415     debug ('channel: ' + str (channel) + '\n')
416     return unthread_notes (music)
417
418 class Channel:
419     def __init__ (self, number):
420         self.number = number
421         self.events = []
422         self.music = None
423     def add (self, event):
424         self.events.append (event)
425     def get_voice (self):
426         if not self.music:
427             self.music = self.parse ()
428         return get_voice (self.number, self.music)
429     def parse (self):
430         pitches = {}
431         notes = []
432         music = []
433         last_lyric = 0
434         last_time = 0
435         for e in self.events:
436             t = e[0]
437
438             if start_quant_clocks:
439                 t = quantise_clocks (t, start_quant_clocks)
440
441             if (e[1][0] == midi.NOTE_OFF
442                 or (e[1][0] == midi.NOTE_ON and e[1][2] == 0)):
443                 debug ('%d: NOTE OFF: %s' % (t, e[1][1]))
444                 if not e[1][2]:
445                     debug ('   ...treated as OFF')
446                 end_note (pitches, notes, t, e[1][1])
447
448             elif e[1][0] == midi.NOTE_ON:
449                 if not pitches.has_key (e[1][1]):
450                     debug ('%d: NOTE ON: %s' % (t, e[1][1]))
451                     pitches[e[1][1]] = (t, e[1][2])
452                 else:
453                     debug ('...ignored')
454
455             # all include ALL_NOTES_OFF
456             elif (e[1][0] >= midi.ALL_SOUND_OFF
457               and e[1][0] <= midi.POLY_MODE_ON):
458                 for i in pitches:
459                     end_note (pitches, notes, t, i)
460
461             elif e[1][0] == midi.META_EVENT:
462                 if e[1][1] == midi.END_OF_TRACK:
463                     for i in pitches:
464                         end_note (pitches, notes, t, i)
465                     break
466
467                 elif e[1][1] == midi.SET_TEMPO:
468                     (u0, u1, u2) = map (ord, e[1][2])
469                     us_per_4 = u2 + 256 * (u1 + 256 * u0)
470                     seconds_per_1 = us_per_4 * 4 / 1e6
471                     music.append ((t, Tempo (seconds_per_1)))
472                 elif e[1][1] == midi.TIME_SIGNATURE:
473                     (num, dur, clocks4, count32) = map (ord, e[1][2])
474                     den = 2 ** dur
475                     music.append ((t, Time (num, den)))
476                 elif e[1][1] == midi.KEY_SIGNATURE:
477                     (alterations, minor) = map (ord, e[1][2])
478                     sharps = 0
479                     flats = 0
480                     if alterations < 127:
481                         sharps = alterations
482                     else:
483                         flats = 256 - alterations
484
485                     k = Key (sharps, flats, minor)
486                     if not t and global_options.key:
487                         # At t == 0, a set --key overrides us
488                         k = global_options.key
489                     music.append ((t, k))
490
491                     # ugh, must set key while parsing
492                     # because Note init uses key
493                     # Better do Note.calc () at dump time?
494                     global_options.key = k
495
496                 elif (e[1][1] == midi.LYRIC
497                       or (global_options.text_lyrics
498                           and e[1][1] == midi.TEXT_EVENT)):
499                     self.lyrics_p_ = True
500                     if last_lyric:
501                         last_lyric.clocks = t - last_time
502                         music.append ((last_time, last_lyric))
503                     last_time = t
504                     last_lyric = Text (midi.LYRIC, e[1][2])
505
506                 elif (e[1][1] >= midi.SEQUENCE_NUMBER
507                       and e[1][1] <= midi.CUE_POINT):
508                     text = Text (e[1][1], e[1][2])
509                     text.track = self
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         self.lyrics_p_ = False
542     def _add (self, event):
543         self.events.append (event)
544     def add (self, event, channel=None):
545         if channel == None:
546             self._add (event)
547         else:
548             self.channels[channel] = self.channels.get (channel, Channel (channel))
549             self.channels[channel].add (event)
550     def get_voices (self):
551         return ([self.get_voice ()]
552                 + [self.channels[k].get_voice ()
553                    for k in sorted (self.channels.keys ())])
554
555 def create_track (events):
556     track = Track ()
557     for e in events:
558         data = list (e[1])
559         if data[0] > 0x7f and data[0] < 0xf0:
560             channel = data[0] & 0x0f
561             e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
562             track.add (e, channel)
563         else:
564             track.add (e)
565     return track
566
567 def quantise_clocks (clocks, quant):
568     q = int (clocks / quant) * quant
569     if q != clocks:
570         for tquant in allowed_tuplet_clocks:
571             if int (clocks / tquant) * tquant == clocks:
572                 return clocks
573         if 2 * (clocks - q) > quant:
574             q = q + quant
575     return q
576
577 def end_note (pitches, notes, t, e):
578     try:
579         (lt, vel) = pitches[e]
580         del pitches[e]
581
582         i = len (notes) - 1
583         while i > 0:
584             if notes[i][0] > lt:
585                 i = i -1
586             else:
587                 break
588         d = t - lt
589         if duration_quant_clocks:
590             d = quantise_clocks (d, duration_quant_clocks)
591             if not d:
592                 d = duration_quant_clocks
593
594         notes.insert (i + 1,
595               (lt, Note (d, e, vel)))
596
597     except KeyError:
598         pass
599
600 def unthread_notes (channel):
601     threads = []
602     while channel:
603         thread = []
604         end_busy_t = 0
605         start_busy_t = 0
606         todo = []
607         for e in channel:
608             t = e[0]
609             if (e[1].__class__ == Note
610                 and ((t == start_busy_t
611                       and e[1].clocks + t == end_busy_t)
612                      or t >= end_busy_t)):
613                 thread.append (e)
614                 start_busy_t = t
615                 end_busy_t = t + e[1].clocks
616             elif (e[1].__class__ == Time
617                   or e[1].__class__ == Key
618                   or e[1].__class__ == Text
619                   or e[1].__class__ == Tempo):
620                 thread.append (e)
621             else:
622                 todo.append (e)
623         threads.append (thread)
624         channel = todo
625
626     return threads
627
628 def gcd (a,b):
629     if b == 0:
630         return a
631     c = a
632     while c:
633         c = a % b
634         a = b
635         b = c
636     return a
637
638 def dump_skip (skip, clocks):
639     return skip + Duration (clocks).dump () + ' '
640
641 def dump (d):
642     return d.dump ()
643
644 def dump_chord (ch):
645     s = ''
646     notes = []
647     for i in ch:
648         if i.__class__ == Note:
649             notes.append (i)
650         else:
651             s = s + i.dump ()
652     if len (notes) == 1:
653         s = s + dump (notes[0])
654     elif len (notes) > 1:
655         global reference_note
656         s = s + '<'
657         s = s + notes[0].dump (dump_dur=False)
658         r = reference_note
659         for i in notes[1:]:
660             s = s + i.dump (dump_dur=False)
661         s = s + '>'
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                 vl = get_voice_layout (average_pitch[1:])[vv]
830                 if vl:
831                     s += '  \\voice' + vl + '\n'
832                 else:
833                     if not global_options.quiet:
834                         warning (_ ('found more than 5 voices on a staff, expect bad output'))
835             s += '  ' + dump_voice (voice, skip)
836             s += '}\n\n'
837             v += 1
838             vv += 1
839
840     s += '%(track_name)s = <<\n' % locals ()
841
842     if clef.type != 2:
843         s += clef.dump () + '\n'
844
845     c = 0
846     vv = 0
847     for channel in track:
848         v = 0
849         channel_name = get_channel_name (c)
850         c += 1
851         for voice in channel:
852             voice_context_name = get_voice_name (vv, zero_too_p=True)
853             voice_name = get_voice_name (v)
854             v += 1
855             vv += 1
856             voice_id = track_name + channel_name + voice_name
857             item = voice_first_item (voice)
858             context = 'Voice'
859             if item and item.__class__ == Text:
860                 context = 'Lyrics'
861             s += '  \\context %(context)s = %(voice_context_name)s \\%(voice_id)s\n' % locals ()
862     s += '>>\n\n'
863     return s
864
865 def voice_first_item (voice):
866     for event in voice:
867         if (event[1].__class__ == Note
868             or (event[1].__class__ == Text
869                 and event[1].type == midi.LYRIC)):
870             return event[1]
871     return None
872
873 def channel_first_item (channel):
874     for voice in channel:
875         first = voice_first_item (voice)
876         if first:
877             return first
878     return None
879
880 def track_first_item (track):
881     for channel in track:
882         first = channel_first_item (channel)
883         if first:
884             return first
885     return None
886
887 def track_average_pitch (track):
888     i = 0
889     p = [0]
890     v = 1
891     for channel in track:
892         for voice in channel:
893             c = 0
894             p.append (0)
895             for event in voice:
896                 if event[1].__class__ == Note:
897                     i += 1
898                     c += 1
899                     p[v] += event[1].pitch
900             if c:
901                 p[0] += p[v]
902                 p[v] = p[v] / c
903             v += 1
904     if i:
905         p[0] = p[0] / i
906     return p
907
908 def get_best_clef (average_pitch):
909     if average_pitch:
910         if average_pitch <= 3*12:
911             return Clef (0)
912         elif average_pitch <= 5*12:
913             return Clef (1)
914         elif average_pitch >= 7*12:
915             return Clef (3)
916     return Clef (2)
917
918 class Staff:
919     def __init__ (self, track):
920         self.voices = track.get_voices ()
921     def dump (self, i):
922         return dump_track (self.voices, i)
923
924 def convert_midi (in_file, out_file):
925     global midi
926     import midi
927
928     global clocks_per_1, clocks_per_4, key
929     global start_quant_clocks
930     global duration_quant_clocks
931     global allowed_tuplet_clocks
932     global time
933
934     str = open (in_file, 'rb').read ()
935     clocks_max = bar_max * clocks_per_1 * 2
936     midi_dump = midi.parse (str, clocks_max)
937
938     clocks_per_1 = midi_dump[0][1]
939     clocks_per_4 = clocks_per_1 / 4
940     time = Time (4, 4)
941
942     if global_options.start_quant:
943         start_quant_clocks = clocks_per_1 / global_options.start_quant
944
945     if global_options.duration_quant:
946         duration_quant_clocks = clocks_per_1 / global_options.duration_quant
947
948     allowed_tuplet_clocks = []
949     for (dur, num, den) in global_options.allowed_tuplets:
950         allowed_tuplet_clocks.append (clocks_per_1 / dur * num / den)
951
952     if global_options.verbose:
953         print 'allowed tuplet clocks:', allowed_tuplet_clocks
954
955     tracks = [create_track (t) for t in midi_dump[1]]
956     # urg, parse all global track events, such as Key first
957     # this fixes key in different voice/staff problem
958     for t in tracks:
959         t.music = t.parse ()
960     prev = None
961     staves = []
962     for t in tracks:
963         voices = t.get_voices ()
964         if ((t.name and prev and prev.name)
965             and t.name.split (':')[0] == prev.name.split (':')[0]):
966             # staves[-1].voices += voices
967             # all global track events first
968             staves[-1].voices = ([staves[-1].voices[0]]
969                                  + [voices[0]]
970                                  + staves[-1].voices[1:]
971                                  + voices[1:])
972         else:
973             staves.append (Staff (t))
974         prev = t
975
976     tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, in_file)
977
978
979     s = tag
980     s += r'''
981 \version "2.14.0"
982 '''
983
984     s += r'''
985 \layout {
986   \context {
987     \Voice
988     \remove "Note_heads_engraver"
989     \consists "Completion_heads_engraver"
990     \remove "Rest_engraver"
991     \consists "Completion_rest_engraver"
992   }
993 }
994 '''
995
996     for i in global_options.include_header:
997         s += '\n%% included from %(i)s\n' % locals ()
998         s += open (i).read ()
999         if s[-1] != '\n':
1000             s += '\n'
1001         s += '% end\n'
1002
1003     for i, t in enumerate (staves):
1004         s += t.dump (i)
1005
1006     s += '\n\\score {\n  <<\n'
1007
1008     control_track = False
1009     i = 0
1010     for i, staff in enumerate (staves):
1011         track_name = get_track_name (i)
1012         item = track_first_item (staff.voices)
1013         staff_name = track_name
1014         context = None
1015         if not i and not item and len (staves) > 1:
1016             control_track = track_name
1017             continue
1018         elif (item and item.__class__ == Note):
1019             context = 'Staff'
1020             if control_track:
1021                 s += '    \\context %(context)s=%(staff_name)s \\%(control_track)s\n' % locals ()
1022         elif item and item.__class__ == Text:
1023             context = 'Lyrics'
1024         if context:
1025             s += '    \\context %(context)s=%(staff_name)s \\%(track_name)s\n' % locals ()
1026
1027     s = s + '''  >>
1028   \layout {}
1029   \midi {}
1030 }
1031 '''
1032
1033     if not global_options.quiet:
1034         progress (_ ("%s output to `%s'...") % ('LY', out_file))
1035
1036     if out_file == '-':
1037         handle = sys.stdout
1038     else:
1039         handle = open (out_file, 'w')
1040
1041     handle.write (s)
1042     handle.close ()
1043
1044
1045 def get_option_parser ():
1046     p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'midi2ly',
1047                  description=_ ("Convert %s to LilyPond input.\n") % 'MIDI',
1048                  add_help_option=False)
1049
1050     p.add_option ('-a', '--absolute-pitches',
1051            action='store_true',
1052            help=_ ('print absolute pitches'))
1053     p.add_option ('-d', '--duration-quant',
1054            metavar=_ ('DUR'),
1055            help=_ ('quantise note durations on DUR'))
1056     p.add_option ('-D', '--debug',
1057            action='store_true',
1058            help=_ ('debug printing'))
1059     p.add_option ('-e', '--explicit-durations',
1060            action='store_true',
1061            help=_ ('print explicit durations'))
1062     p.add_option('-h', '--help',
1063            action='help',
1064            help=_ ('show this help and exit'))
1065     p.add_option('-i', '--include-header',
1066            help=_ ('prepend FILE to output'),
1067            action='append',
1068            default=[],
1069            metavar=_ ('FILE'))
1070     p.add_option('-k', '--key', help=_ ('set key: ALT=+sharps|-flats; MINOR=1'),
1071            metavar=_ ('ALT[:MINOR]'),
1072            default=None),
1073     p.add_option ('-o', '--output', help=_ ('write output to FILE'),
1074            metavar=_ ('FILE'),
1075            action='store')
1076     p.add_option ('-p', '--preview', help=_ ('preview of first 4 bars'),
1077            action='store_true')
1078     p.add_option ('-q', '--quiet',
1079            action="store_true",
1080            help=_ ("suppress progress messages and warnings about excess voices"))
1081     p.add_option ('-s', '--start-quant',help= _ ('quantise note starts on DUR'),
1082            metavar=_ ('DUR'))
1083     p.add_option ('-S', '--skip',
1084            action = "store_true",
1085            help =_ ("use s instead of r for rests"))
1086     p.add_option ('-t', '--allow-tuplet',
1087            metavar=_ ('DUR*NUM/DEN'),
1088            action = 'append',
1089            dest='allowed_tuplets',
1090            help=_ ('allow tuplet durations DUR*NUM/DEN'),
1091            default=[])
1092     p.add_option ('-V', '--verbose', help=_ ('be verbose'),
1093            action='store_true')
1094     p.version = 'midi2ly (LilyPond) @TOPLEVEL_VERSION@'
1095     p.add_option ('--version',
1096                  action='version',
1097                  help=_ ('show version number and exit'))
1098     p.add_option ('-w', '--warranty', help=_ ('show warranty and copyright'),
1099            action='store_true',)
1100     p.add_option ('-x', '--text-lyrics', help=_ ('treat every text as a lyric'),
1101            action='store_true')
1102
1103     p.add_option_group (ly.display_encode (_ ('Examples')),
1104               description = r'''
1105   $ midi2ly --key=-2:1 --duration-quant=32 --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
1106 ''')
1107     p.add_option_group ('',
1108                         description=(
1109             _ ('Report bugs via %s')
1110             % 'http://post.gmane.org/post.php'
1111             '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
1112     return p
1113
1114
1115
1116 def do_options ():
1117     opt_parser = get_option_parser ()
1118     (options, args) = opt_parser.parse_args ()
1119
1120     if options.warranty:
1121         warranty ()
1122         sys.exit (0)
1123
1124     if not args or args[0] == '-':
1125         opt_parser.print_help ()
1126         ly.stderr_write ('\n%s: %s %s\n' % (program_name, _ ('error: '),
1127                          _ ('no files specified on command line.')))
1128         sys.exit (2)
1129
1130     if options.duration_quant:
1131         options.duration_quant = int (options.duration_quant)
1132
1133     if options.key:
1134         (alterations, minor) = map (int, (options.key + ':0').split (':'))[0:2]
1135         sharps = 0
1136         flats = 0
1137         if alterations >= 0:
1138             sharps = alterations
1139         else:
1140             flats = - alterations
1141         options.key = Key (sharps, flats, minor)
1142
1143     if options.start_quant:
1144         options.start_quant = int (options.start_quant)
1145
1146     global bar_max
1147     if options.preview:
1148         bar_max = 4
1149
1150     options.allowed_tuplets = [map (int, a.replace ('/','*').split ('*'))
1151                 for a in options.allowed_tuplets]
1152
1153     if options.verbose:
1154         sys.stderr.write ('Allowed tuplets: %s\n' % `options.allowed_tuplets`)
1155
1156     global global_options
1157     global_options = options
1158
1159     return args
1160
1161 def main ():
1162     files = do_options ()
1163
1164     exts = ['.midi', '.mid', '.MID']
1165     for f in files:
1166         g = f
1167         for e in exts:
1168             g = strip_extension (g, e)
1169         if not os.path.exists (f):
1170             for e in exts:
1171                 n = g + e
1172                 if os.path.exists (n):
1173                     f = n
1174                     break
1175
1176         if not global_options.output:
1177             outdir = '.'
1178             outbase = os.path.basename (g)
1179             o = outbase + '-midi.ly'
1180         elif (global_options.output[-1] == os.sep
1181               or os.path.isdir (global_options.output)):
1182             outdir = global_options.output
1183             outbase = os.path.basename (g)
1184             o = os.path.join (outdir, outbase + '-midi.ly')
1185         else:
1186             o = global_options.output
1187             (outdir, outbase) = os.path.split (o)
1188
1189         if outdir and outdir != '.' and not os.path.exists (outdir):
1190             os.mkdir (outdir, 0777)
1191
1192         convert_midi (f, o)
1193
1194 if __name__ == '__main__':
1195     main ()