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