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