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