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