]> git.donarmstrong.com Git - lilypond.git/blob - scripts/midi2ly.py
2709adacc4e0353014cf4884e42ead6dbb202899
[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, 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 and g > clocks / 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                                 commas = commas + sign (delta)
223                         
224                 if commas > 0:
225                         s = s + "'" * commas
226                 elif commas < 0:
227                         s = s + "," * -commas
228
229                 if explicit_durations_p \
230                    or Duration.compare (self.duration, reference_note.duration):
231                         s = s + self.duration.dump ()
232
233                 global reference_note
234                 reference_note = self
235                 # TODO: move space
236                 return s + ' '
237
238
239 class Time:
240         def __init__ (self, num, den):
241                 self.clocks = 0
242                 self.num = num
243                 self.den = den
244
245         def dump (self):
246                 return '\n  ' + '\\time %d/%d ' % (self.num, self.den) + '\n  '
247
248 class Tempo:
249         def __init__ (self, seconds_per_1):
250                 self.clocks = 0
251                 self.seconds_per_1 = seconds_per_1
252
253         def dump (self):
254                 return '\n  ' + '\\tempo 4 = %d ' % (4 * 60 / self.seconds_per_1) + '\n  '
255
256 class Clef:
257         clefs = ('"bass_8"', 'bass', 'violin', '"violin^8"')
258         def __init__ (self, type):
259                 self.type = type
260                 
261         def dump (self):
262                 return '\n  \\clef %s\n  ' % self.clefs[self.type]
263
264 class Key:
265         key_sharps = ('c', 'g', 'd', 'a', 'e', 'b', 'fis')
266         key_flats = ('BUG', 'f', 'bes', 'es', 'as', 'des', 'ges')
267
268         def __init__ (self, sharps, flats, minor):
269                 self.clocks = 0
270                 self.flats = flats
271                 self.sharps = sharps
272                 self.minor = minor
273
274         def dump (self):
275                 global key
276                 key = self
277
278                 s = ''
279                 if self.sharps and self.flats:
280                         s = '\\keysignature %s ' % 'TODO'
281                 else:
282                         
283                         if self.flats:
284                                 k = (ord ('cfbeadg'[self.flats % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
285                         else:
286                                 k = (ord ('cgdaebf'[self.sharps % 7]) - ord ('a') - 2 -2 * self.minor + 7) % 7
287   
288                         if not self.minor:
289                                 name = chr ((k + 2) % 7 + ord ('a'))
290                         else:
291                                 name = chr ((k + 2) % 7 + ord ('a'))
292
293                         # fis cis gis dis ais eis bis
294                         sharps = (2, 4, 6, 1, 3, 5, 7)
295                         # bes es as des ges ces fes
296                         flats = (6, 4, 2, 7, 5, 3, 1)
297                         a = 0
298                         if self.flats:
299                                 if flats[k] <= self.flats:
300                                         a = -1
301                         else:
302                                 if sharps[k] <= self.sharps:
303                                         a = 1
304
305                         if a:
306                                 name = name + Note.alteration_names[a + 2]
307
308                         s = '\\key ' + name
309                         if self.minor:
310                                 s = s + ' \\minor'
311                         else:
312                                 s = s + ' \\major'
313
314                 return '\n\n  ' + s + '\n  '
315
316
317 class Text:
318         text_types = (
319                 'SEQUENCE_NUMBER',
320                 'TEXT_EVENT',
321                 'COPYRIGHT_NOTICE',
322                 'SEQUENCE_TRACK_NAME',
323                 'INSTRUMENT_NAME',
324                 'LYRIC',
325                 'MARKER',
326                 'CUE_POINT',)
327         
328         def __init__ (self, type, text):
329                 self.clocks = 0
330                 self.type = type
331                 self.text = text
332
333         def dump (self):
334                 # urg, we should be sure that we're in a lyrics staff
335                 if self.type == midi.LYRIC:
336                         s = '"%s"' % self.text
337                         d = Duration (self.clocks)
338                         if explicit_durations_p \
339                            or Duration.compare (d,
340                                                 reference_note.duration):
341                                 s = s + Duration (self.clocks).dump ()
342                         s = s + ' '
343                 else:
344                         s = '\n  % [' + self.text_types[self.type] + '] ' + self.text + '\n  '
345                 return s
346
347
348 output_name = ''
349 LINE_BELL = 60
350 scale_steps = [0,2,4,5,7,9,11]
351
352 clocks_per_1 = 1536
353 clocks_per_4 = 0
354 key = 0
355 reference_note = 0
356 start_quant = 0
357 start_quant_clocks = 0
358 duration_quant = 0
359 duration_quant_clocks = 0
360 allowed_tuplets = []
361 allowed_tuplet_clocks = []
362 absolute_p = 0
363 explicit_durations_p = 0
364 text_lyrics_p = 0
365
366 def split_track (track):
367         chs = {}
368         for i in range(16):
369                 chs[i] = []
370                 
371         for e in track:
372                 data = list (e[1])
373                 if data[0] > 0x7f and data[0] < 0xf0:
374                         c = data[0] & 0x0f
375                         e = (e[0], tuple ([data[0] & 0xf0] + data[1:]))
376                         chs[c].append (e)
377                 else:
378                         chs[0].append (e)
379
380         for i in range (16):
381                 if chs[i] == []:
382                         del chs[i]
383
384         threads = []
385         for v in chs.values ():
386                 events = events_on_channel (v)
387                 thread = unthread_notes (events)
388                 if len (thread):
389                         threads.append (thread)
390         return threads
391
392
393 def quantise_clocks (clocks, quant):
394         q = int (clocks / quant) * quant
395         if q != clocks:
396                 for tquant in allowed_tuplet_clocks:
397                         if int (clocks / tquant) * tquant == clocks:
398                                 return clocks
399                 if 2 * (clocks - q) > quant:
400                         q = q + quant
401         return q
402
403 def end_note (pitches, notes, t, e):
404         try:
405                 (lt, vel) = pitches[e]
406                 del pitches[e]
407
408                 i = len (notes) - 1 
409                 while i > 0:
410                         if notes[i][0] > lt:
411                                 i = i -1
412                         else:
413                                 break
414                 d = t - lt
415                 if duration_quant_clocks:
416                         d = quantise_clocks (d, duration_quant_clocks)
417                         if not d:
418                                 d = duration_quant_clocks
419
420                 notes.insert (i + 1,
421                             (lt, Note (d, e, vel)))
422
423         except KeyError:
424                 pass
425
426 def events_on_channel (channel):
427         pitches = {}
428
429         notes = []
430         events = []
431         last_lyric = 0
432         last_time = 0
433         for e in channel:
434                 t = e[0]
435
436                 if start_quant_clocks:
437                         t = quantise_clocks (t, start_quant_clocks)
438
439
440                 if e[1][0] == midi.NOTE_OFF \
441                    or (e[1][0] == midi.NOTE_ON and e[1][2] == 0):
442                         end_note (pitches, notes, t, e[1][1])
443                         
444                 elif e[1][0] == midi.NOTE_ON:
445                         if not pitches.has_key (e[1][1]):
446                                 pitches[e[1][1]] = (t, e[1][2])
447                                 
448                 # all include ALL_NOTES_OFF
449                 elif e[1][0] >= midi.ALL_SOUND_OFF \
450                      and e[1][0] <= midi.POLY_MODE_ON:
451                         for i in pitches.keys ():
452                                 end_note (pitches, notes, t, i)
453                                 
454                 elif e[1][0] == midi.META_EVENT:
455                         if e[1][1] == midi.END_OF_TRACK:
456                                 for i in pitches.keys ():
457                                         end_note (pitches, notes, t, i)
458                                 break
459
460                         elif e[1][1] == midi.SET_TEMPO:
461                                 (u0, u1, u2) = map (ord, e[1][2])
462                                 us_per_4 = u2 + 256 * (u1 + 256 * u0)
463                                 seconds_per_1 = us_per_4 * 4 / 1e6
464                                 events.append ((t, Tempo (seconds_per_1)))
465                         elif e[1][1] == midi.TIME_SIGNATURE:
466                                 (num, dur, clocks4, count32) = map (ord, e[1][2])
467                                 den = 2 ** dur 
468                                 events.append ((t, Time (num, den)))
469                         elif e[1][1] == midi.KEY_SIGNATURE:
470                                 (alterations, minor) = map (ord, e[1][2])
471                                 sharps = 0
472                                 flats = 0
473                                 if alterations < 127:
474                                         sharps = alterations
475                                 else:
476                                         flats = 256 - alterations
477
478                                 k = Key (sharps, flats, minor)
479                                 events.append ((t, k))
480
481                                 # ugh, must set key while parsing
482                                 # because Note init uses key
483                                 # Better do Note.calc () at dump time?
484                                 global key
485                                 key = k
486
487                         elif e[1][1] == midi.LYRIC \
488                              or (text_lyrics_p and e[1][1] == midi.TEXT_EVENT):
489                                 if last_lyric:
490                                         last_lyric.clocks = t - last_time
491                                         events.append ((last_time, last_lyric))
492                                 last_time = t
493                                 last_lyric = Text (midi.LYRIC, e[1][2])
494
495                         elif e[1][1] >= midi.SEQUENCE_NUMBER \
496                              and e[1][1] <= midi.CUE_POINT:
497                                 events.append ((t, Text (e[1][1], e[1][2])))
498                         else:
499                                 if verbose_p:
500                                         sys.stderr.write ("SKIP: %s\n" % `e`)
501                                 pass
502                 else:
503                         if verbose_p:
504                                 sys.stderr.write ("SKIP: %s\n" % `e`)
505                         pass
506
507         if last_lyric:
508                 # last_lyric.clocks = t - last_time
509                 # hmm
510                 last_lyric.clocks = clocks_per_4
511                 events.append ((last_time, last_lyric))
512                 last_lyric = 0
513                 
514         i = 0
515         while len (notes):
516                 if i < len (events) and notes[0][0] >= events[i][0]:
517                         i = i + 1
518                 else:
519                         events.insert (i, notes[0])
520                         del notes[0]
521         return events
522
523 def unthread_notes (channel):
524         threads = []
525         while channel:
526                 thread = []
527                 end_busy_t = 0
528                 start_busy_t = 0
529                 todo = []
530                 for e in channel:
531                         t = e[0]
532                         if e[1].__class__ == Note \
533                            and ((t == start_busy_t \
534                                  and e[1].clocks + t == end_busy_t) \
535                             or t >= end_busy_t):
536                                 thread.append (e)
537                                 start_busy_t = t
538                                 end_busy_t = t + e[1].clocks
539                         elif e[1].__class__ == Time \
540                              or e[1].__class__ == Key \
541                              or e[1].__class__ == Text \
542                              or e[1].__class__ == Tempo:
543                                 thread.append (e)
544                         else:
545                                 todo.append (e)
546                 threads.append (thread)
547                 channel = todo
548
549         return threads
550
551 def gcd (a,b):
552         if b == 0:
553                 return a
554         c = a
555         while c: 
556                 c = a % b
557                 a = b
558                 b = c
559         return a
560         
561 def dump_skip (skip, clocks):
562         return skip + Duration (clocks).dump () + ' '
563
564 def dump (self):
565         return self.dump ()
566
567 def dump_chord (ch):
568         s = ''
569         notes = []
570         for i in ch:
571                 if i.__class__ == Note:
572                         notes.append (i)
573                 else:
574                         s = s + i.dump ()
575         if len (notes) == 1:
576                 s = s + dump (notes[0])
577         elif len (notes) > 1:
578                 global reference_note
579                 s = s + '<'
580                 s = s + notes[0].dump ()
581                 r = reference_note
582                 for i in notes[1:]:
583                         s = s + i.dump ()
584                 s = s + '>'
585                 reference_note = r
586         return s
587
588 def dump_channel (thread, skip):
589         global key, reference_note
590
591         key = Key (0, 0, 0)
592         # urg LilyPond doesn't start at c4, but
593         # remembers from previous tracks!
594         # reference_note = Note (clocks_per_4, 4*12, 0)
595         reference_note = Note (0, 4*12, 0)
596         last_e = None
597         chs = []
598         ch = []
599
600         for e in thread:
601                 if last_e and last_e[0] == e[0]:
602                         ch.append (e[1])
603                 else:
604                         if ch:
605                                 chs.append ((last_e[0], ch))
606                                 
607                         ch = [e[1]]
608                         
609                 last_e = e
610
611         if ch:
612                 chs.append ((last_e[0], ch))
613         t = 0
614         last_t = 0
615
616         lines = ['']
617         for ch in chs: 
618                 i = string.rfind (lines[-1], '\n') + 1
619                 if len (lines[-1][i:]) > LINE_BELL:
620                         lines.append ('')
621                         
622                 t = ch[0]
623                 if t - last_t > 0:
624                         lines[-1] = lines[-1] + dump_skip (skip, t-last_t)
625                 elif t - last_t < 0:
626                         errorport.write ('BUG: time skew')
627                         
628                 lines[-1] = lines[-1] + dump_chord (ch[1])
629
630                 clocks = 0
631                 for i in ch[1]:
632                         if i.clocks > clocks:
633                                 clocks = i.clocks
634                                 
635                 last_t = t + clocks
636
637         return string.join (lines, '\n  ') + '\n'
638
639 def track_name (i):
640         return 'track%c' % (i + ord ('A'))
641
642 def channel_name (i):
643         return 'channel%c' % (i + ord ('A'))
644
645 def dump_track (channels, n):
646         s = '\n'
647         track = track_name (n)
648         clef = guess_clef (channels)
649
650         for i in range (len (channels)):
651                 channel = channel_name (i)
652                 item = thread_first_item (channels[i])
653
654                 if item and item.__class__ == Note:
655                         skip = 's'
656                         s = s + '%s = \\notes' % (track + channel)
657                         if not absolute_p:
658                                 s = s + '\\relative c '
659                 elif item and item.__class__ == Text:
660                         skip = '" "'
661                         s = s + '%s = \\lyrics ' % (track + channel)
662                 else:
663                         skip = '\\skip '
664                         # must be in \notes mode for parsing \skip
665                         s = s + '%s = \\notes ' % (track + channel)
666                 s = s + '{\n'
667                 s = s + '  ' + dump_channel (channels[i][0], skip)
668                 s = s + '}\n\n'
669
670         s = s + '%s = <\n' % track
671
672         if clef.type != 2:
673                 s = s + clef.dump () + '\n'
674
675         for i in range (len (channels)):
676                 channel = channel_name (i)
677                 item = thread_first_item (channels[i])
678                 if item and item.__class__ == Text:
679                         s = s + '  \\context Lyrics = %s \\%s\n' % (channel,
680                                                                     track + channel)
681                 else:
682                         s = s + '  \\context Voice = %s \\%s\n' % (channel,
683                                                                    track + channel)
684         s = s + '>\n\n'
685         return s
686
687 def thread_first_item (thread):
688         for chord in thread:
689                 for event in chord:
690                         if event[1].__class__ == Note \
691                            or (event[1].__class__ == Text \
692                                and event[1].type == midi.LYRIC):
693                                 return event[1]
694         return 0
695
696 def track_first_item (track):
697         for thread in track:
698                 return thread_first_item (thread)
699
700 def guess_clef (track):
701         i = 0
702         p = 0
703         for thread in track:
704                 for chord in thread:
705                         for event in chord:
706                                 if event[1].__class__ == Note:
707                                         i = i + 1
708                                         p = p + event[1].pitch
709         if i and p / i <= 3*12:
710                 return Clef (0)
711         elif i and p / i <= 5*12:
712                 return Clef (1)
713         elif i and p / i >= 7*12:
714                 return Clef (3)
715         else:
716                 return Clef (2)
717         
718
719 def convert_midi (f, o):
720         global clocks_per_1, clocks_per_4, key
721
722         str = open (f).read ()
723         midi_dump = midi.parse (str)
724
725         clocks_per_1 = midi_dump[0][1]
726         clocks_per_4 = clocks_per_1 / 4
727         
728         global start_quant, start_quant_clocks
729         if start_quant:
730                 start_quant_clocks = clocks_per_1 / start_quant
731
732         global duration_quant, duration_quant_clocks
733         if duration_quant:
734                 duration_quant_clocks = clocks_per_1 / duration_quant
735
736         global allowed_tuplet_clocks
737         allowed_tuplet_clocks = []
738         for (dur, num, den) in allowed_tuplets:
739                 allowed_tuplet_clocks.append (clocks_per_1 * num / (dur * den))
740
741         tracks = []
742         for t in midi_dump[1]:
743                 key = Key (0, 0, 0)
744                 tracks.append (split_track (t))
745
746         tag = '%% Lily was here -- automatically converted by %s from %s' % ( program_name, f)
747
748         s = ''
749         s = tag + '\n\n'
750         for i in range (len (tracks)):
751                 s = s + dump_track (tracks[i], i)
752
753         s = s + '\n\\score {\n  <\n'
754         for i in range (len (tracks)):
755                 track = track_name (i)
756                 item = track_first_item (tracks[i])
757                 if item and item.__class__ == Note:
758                         s = s + '    \\context Staff=%s \\%s\n' % (track, track)
759                 elif item and item.__class__ == Text:
760                         s = s + '    \\context Lyrics=%s \\%s\n' % (track, track)
761         s = s + '  >\n}\n'
762
763         progress (_ ("%s output to `%s'...") % ('LY', o))
764
765         if o == '-':
766                 h = sys.stdout
767         else:
768                 h = open (o, 'w')
769
770         h.write (s)
771         h.close ()
772
773
774 (sh, long) = getopt_args (__main__.option_definitions)
775 try:
776         (options, files) = getopt.getopt(sys.argv[1:], sh, long)
777 except getopt.error, s:
778         errorport.write ('\n')
779         errorport.write (_ ("error: ") + _ ("getopt says: `%s\'" % s))
780         errorport.write ('\n')
781         errorport.write ('\n')
782         help ()
783         sys.exit (2)
784         
785 for opt in options:     
786         o = opt[0]
787         a = opt[1]
788
789         if 0:
790                 pass
791         elif o == '--help' or o == '-h':
792                 help ()
793                 errorport.write ('\n')
794                 errorport.write (_ ("Example:"))
795                 errorport.write  (r'''
796     midi2ly --key=-2:1 --duration-quant=32 \
797         --allow-tuplet=4*2/3 --allow-tuplet=2*4/3 foo.midi
798 ''')
799                 sys.exit (0)
800         elif o == '--output' or o == '-o':
801                 output_name = a
802         elif o == '--verbose' or o == '-V':
803                 verbose_p = 1
804         elif o == '--version' or o == '-v':
805                 identify ()
806                 sys.exit (0)
807         elif o == '--warranty' or o == '-w':
808                 status = system ('lilypond -w', ignore_error = 1)
809                 if status:
810                         warranty ()
811                 sys.exit (0)
812
813
814         elif o == '--absolute-pitches' or o == '-a':
815                 global absolute_p
816                 absolute_p = 1
817         elif o == '--duration-quant' or o == '-d':
818                 global duration_quant
819                 duration_quant = string.atoi (a)
820         elif o == '--explicit-durations' or o == '-e':
821                 global explicit_durations_p
822                 explicit_durations_p = 1
823         elif o == '--key' or o == '-k':
824                 (alterations, minor) = map (string.atoi, string.split (a + ':0', ':'))[0:2]
825                 sharps = 0
826                 flats = 0
827                 if alterations >= 0:
828                         sharps = alterations
829                 else:
830                         flats = - alterations
831                 global key
832                 key = Key (sharps, flats, minor)
833         elif o == '--start-quant' or o == '-s':
834                 global start_quant, start_quant_clocks
835                 start_quant = string.atoi (a)
836         elif o == '--allow-tuplet' or o == '-t':
837                 global allowed_tuplets
838                 a = string.replace (a, '/', '*')
839                 tuplet = map (string.atoi, string.split (a, '*'))
840                 allowed_tuplets.append (tuplet)
841         # lots of midi files use plain text for lyric events
842         elif o == '--text-lyrics' or o == '-x':
843                 text_lyrics_p = 1
844
845
846 if not files or files[0] == '-':
847
848         # FIXME: read from stdin when files[0] = '-'
849         help ()
850         errorport.write (program_name + ":" + _ ("error: ") + _ ("no files specified on command line.") + '\n')
851         sys.exit (2)
852
853
854 for f in files:
855
856         g = f
857         g = strip_extension (g, '.midi')
858         g = strip_extension (g, '.mid')
859         g = strip_extension (g, '.MID')
860         (outdir, outbase) = ('','')
861
862         if not output_name:
863                 outdir = '.'
864                 outbase = os.path.basename (g)
865                 o = os.path.join (outdir, outbase + '-midi.ly')
866         elif output_name[-1] == os.sep:
867                 outdir = output_name
868                 outbase = os.path.basename (g)
869                 os.path.join (outdir, outbase + '-gen.ly')
870         else:
871                 o = output_name
872                 (outdir, outbase) = os.path.split (o)
873
874         if outdir != '.':
875                 mkdir_p (outdir, 0777)
876
877         convert_midi (f, o)
878