]> git.donarmstrong.com Git - lilypond.git/blob - scripts/etf2ly.py
release: 1.3.92
[lilypond.git] / scripts / etf2ly.py
1 #!@PYTHON@
2
3 # info mostly taken from looking at files. See also
4 # http://www.cs.uu.nl/~hanwen/lily-devel/etf.html
5
6 # This supports
7 #
8 #  * notes
9 #  * rests
10 #  * ties
11 #  * slurs
12 #  * lyrics
13 #  * articulation
14 #  * grace notes
15 #  * tuplets
16
17
18 # todo:
19 #  * slur/stem directions
20 #  * voices (2nd half of frame?)
21 #  * more intelligent lyrics
22 #  * beams (better use autobeam?)
23 #  * more robust: try entertainer.etf (freenote)
24 #  * dynamics
25 #  * automatic `deletion' of invalid items
26 #
27
28
29 program_name = 'etf2ly'
30 version = '@TOPLEVEL_VERSION@'
31 if version == '@' + 'TOPLEVEL_VERSION' + '@':
32         version = '(unknown version)'      # uGUHGUHGHGUGH
33   
34 import __main__
35 import getopt
36 import sys
37 import re
38 import string
39 import os
40
41 finale_clefs= ['treble', 'alto', 'tenor', 'bass', 'percussion', 'treble8vb', 'bass8vb', 'baritone']
42
43 def lily_clef (fin):
44         return finale_clefs[fin]
45
46 def gulp_file(f):
47         return open (f).read ()
48
49 # notename 0 == central C
50 distances = [0, 2, 4, 5, 7, 9, 11, 12]
51 def semitones (name, acc):
52         return (name / 7 ) * 12 + distances[name % 7] + acc
53
54 # represent pitches as (notename, alteration), relative to C-major scale
55 def transpose(orig, delta):
56         (oname, oacc) = orig
57         (dname, dacc) = delta
58         
59         old_pitch =semitones (oname, oacc)
60         delta_pitch = semitones (dname, dacc)
61         nname = (oname + dname) 
62         nacc = oacc
63         new_pitch = semitones (nname, nacc) 
64
65         nacc = nacc - (new_pitch - old_pitch - delta_pitch)
66
67         return (nname, nacc)
68
69
70
71 # find transposition of C-major scale that belongs here. 
72 def interpret_finale_key_sig (finale_id):
73         p = (0,0)
74         if 0 <= finale_id < 7:
75                 while finale_id > 0:
76                         p = transpose (p, (4,0)) # a fifth up
77                         finale_id = finale_id - 1
78         elif 248 < finale_id <= 255:
79                 while finale_id < 256:
80                         p = transpose (p, (3,0))
81                         finale_id = finale_id + 1
82
83         p  = (p[0] % 7, p[1])
84         return p
85
86 # should cache this.
87 def find_scale (transposition):
88         cscale = map (lambda x: (x,0), range (0,7))
89         trscale = map(lambda x, k=transposition: transpose(x, k), cscale)
90
91         return trscale
92 def EDU_to_duration (edu):
93         log = 1
94         d = 4096
95         while d > edu:
96                 d = d >> 1
97                 log = log << 1
98
99         edu = edu - d
100         dots = 0
101         if edu == d /2:
102                 dots = 1
103         elif edu == d*3/4:
104                 dots = 2
105         return (log, dots)      
106
107 def rat_to_lily_duration (rat):
108         (n,d) = rat
109
110         basedur = 1
111         while d and  d % 2 == 0:
112                 basedur = basedur << 1
113                 d = d >> 1
114
115         str = 's%d' % basedur
116         if n <> 1:
117                 str = str + '*%d' % n
118         if d <> 1:
119                 str = str + '/%d' % d
120
121         return str
122
123 def gcd (a,b):
124         if b == 0:
125                 return a
126         c = a
127         while c: 
128                 c = a % b
129                 a = b
130                 b = c
131         return a
132         
133
134 def rat_simplify (r):
135         (n,d) = r
136         if d < 0:
137                 d = -d
138                 n = -n
139         if n == 0:
140                 return (0,1)
141         else:
142                 g = gcd (n, d)
143                 return (n/g, d/g)
144         
145 def rat_multiply (a,b):
146         (x,y) = a
147         (p,q) = b
148
149         return rat_simplify ((x*p, y*q))
150
151 def rat_add (a,b):
152         (x,y) = a
153         (p,q) = b
154
155         return rat_simplify ((x*q + p*y, y*q))
156
157 def rat_neg (a):
158         (p,q) = a
159         return (-p,q)
160
161
162
163 def rat_subtract (a,b ):
164         return rat_add (a, rat_neg (b))
165
166 def lily_notename (tuple2):
167         (n, a) = tuple2
168         nn = chr ((n+ 2)%7 + ord ('a'))
169
170         if a == -1:
171                 nn = nn + 'es'
172         elif a == -2:
173                 nn = nn + 'eses'
174         elif a == 1:
175                 nn = nn + 'is'
176         elif a == 2:
177                 nn = nn + 'isis'
178
179         return nn
180
181
182 class Tuplet:
183         def __init__ (self, number):
184                 self.start_note = number
185                 self.finale = []
186
187         def append_finale (self, fin):
188                 self.finale.append (fin)
189
190         def factor (self):
191                 n = self.finale[0][2]*self.finale[0][3]
192                 d = self.finale[0][0]*self.finale[0][1]
193                 return rat_simplify( (n, d))
194         
195         def dump_start (self):
196                 return '\\times %d/%d { ' % self.factor ()
197         
198         def dump_end (self):
199                 return ' }'
200
201         def calculate (self, chords):
202                 edu_left = self.finale[0][0] * self.finale[0][1]
203
204                 startch = chords[self.start_note]
205                 c = startch
206                 while c and edu_left:
207                         c.tuplet = self
208                         if c == startch:
209                                 c.chord_prefix = self.dump_start () + c.chord_prefix 
210
211                         if not c.grace:
212                                 edu_left = edu_left - c.EDU_duration ()
213                         if edu_left == 0:
214                                 c.chord_suffix = c.chord_suffix+ self.dump_end ()
215                         c = c.next
216
217                 if edu_left:
218                         sys.stderr.write ("\nHuh? Tuplet starting at entry %d was too short." % self.start_note)
219                 
220 class Slur:
221         def __init__ (self, number):
222                 self.number = number
223                 self.finale = []
224
225         def append_entry (self, finale_e):
226                 self.finale.append (finale_e)
227
228         def calculate (self, chords):
229                 startnote = self.finale[0][5]
230                 endnote = self.finale[3][2]
231                 try:
232                         cs = chords[startnote]
233                         ce = chords[endnote]
234
235                         if not cs or not ce:
236                                 raise IndexError
237                         
238                         cs.note_suffix = '(' + cs.note_suffix 
239                         ce.note_prefix = ce.note_prefix + ')'
240                 except IndexError:
241                         sys.stderr.write ("""\nHuh? Slur no %d between (%d,%d), with %d notes""" % (self.number,  startnote, endnote, len (chords)))
242                                          
243                 
244 class Global_measure:
245         def __init__ (self, number):
246                 self.timesig = ''
247                 self.number = number
248                 self.keysignature = None
249                 self.scale = None
250
251                 self.finale = []
252
253         def __str__ (self):
254                 return `self.finale `
255         
256         def set_timesig (self, finale):
257                 (beats, fdur) = finale
258                 (log, dots) = EDU_to_duration (fdur)
259                 assert dots == 0
260                 self.timesig = (beats, log)
261
262         def length (self):
263                 return self.timesig
264         
265         def set_keysig (self, finale):
266                 k = interpret_finale_key_sig (finale)
267                 self.keysignature = k
268                 self.scale = find_scale (k)
269
270
271 articulation_dict ={
272         11: '\\prall',
273         12: '\\mordent',
274         8: '\\fermata',
275         4: '^',
276         1: '.',
277         3: '>',
278         18: '"arp"' , # arpeggio
279 };
280
281 class Articulation:
282         def __init__ (self, a,b, finale):
283                 self.type = finale[0]
284                 self.notenumber = b
285         def calculate (self, chords):
286                 c = chords[self.notenumber]
287
288                 try:
289                         a = articulation_dict[self.type]
290                 except KeyError:
291                         sys.stderr.write ("\nUnknown articulation no. %d on note no. %d" % (self.type, self.notenumber))
292                         a = '"art"'
293                         
294                 c.note_suffix = '-' + a + c.note_suffix
295
296 class Syllable:
297         def __init__ (self, a,b , finale):
298                 self.chordnum = b
299                 self.syllable = finale[1]
300                 self.verse = finale[0]
301         def calculate (self, chords, lyrics):
302                 self.chord = chords[self.chordnum]
303
304 class Verse:
305         def __init__ (self, number, body):
306                 self.body = body
307                 self.number = number
308                 self.split_syllables ()
309         def split_syllables (self):
310                 ss = re.split ('(-| +)', self.body)
311
312                 sep = 0
313                 syls = [None]
314                 for s in ss:
315                         if sep:
316                                 septor = re.sub (" +", "", s)
317                                 septor = re.sub ("-", " -- ", septor) 
318                                 syls[-1] = syls[-1] + septor
319                         else:
320                                 syls.append (s)
321                         
322                         sep = not sep 
323
324                 self.syllables = syls
325
326         def dump (self):
327                 str = ''
328                 line = ''
329                 for s in self.syllables[1:]:
330                         line = line + ' ' + s
331                         if len (line) > 72:
332                                 str = str + ' ' * 4 + line + '\n'
333                                 line = ''
334                         
335                 str = """\nverse%s = \\lyrics {\n %s}\n""" %  (encodeint (self.number - 1) ,str)
336                 return str
337
338         
339 class Measure:
340         def __init__(self, no):
341                 self.number = no
342                 self.frames = [0] * 4
343                 self.flags = 0
344                 self.clef = 0
345                 self.finale = []
346                 self.global_measure = None
347                 self.staff = None
348                 self.valid = 1
349                 
350         def add_finale_entry (self, entry):
351                 self.finale.append (entry)
352
353         def valid (self):
354                 return self.valid
355         def calculate (self):
356                 fs = []
357
358                 if len (self.finale) < 2:
359                         fs = self.finale[0]
360                         fs = map (string.atoi, list (fs))
361                         self.clef = fs[1]
362                         self.frames = [fs[0]]
363                 else:
364                         fs = self.finale[0] + self.finale[1]
365                         
366                         fs = map (string.atoi, list (fs))
367                         self.clef = fs[0]
368                         self.flags = fs[1]
369                         self.frames = fs[2:]
370
371
372 class Frame:
373         def __init__ (self, finale):
374                 self.measure = None
375                 self.finale = finale
376                 (number, start, end ) = finale
377                 self.number = number
378                 self.start = start
379                 self.end = end
380                 self.chords  = []
381
382         def set_measure (self, m):
383                 self.measure = m
384
385         def calculate (self):
386
387                 # do grace notes.
388                 lastch = None
389                 for c in self.chords:
390                         if c.grace and (lastch == None or (not lastch.grace)):
391                                 c.chord_prefix = r'\grace {' + c.chord_prefix
392                         elif not c.grace and lastch and lastch.grace:
393                                 lastch.chord_suffix = lastch.chord_suffix + ' } '
394
395                         lastch = c
396                         
397
398                 
399         def dump (self):
400                 str = '%% FR(%d)\n' % self.number
401                 left = self.measure.global_measure.length ()
402
403                 
404                 ln = ''
405                 for c in self.chords:
406                         add = c.ly_string () + ' '
407                         if len (ln) + len(add) > 72:
408                                 str = str + ln + '\n'
409                                 ln = ''
410                         ln = ln + add
411                         left = rat_subtract (left, c.length ())
412
413                 str = str + ln 
414                 
415                 if left[0] < 0:
416                         sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
417                         left = (0,1)
418                 if left[0]:
419                         str = str + rat_to_lily_duration (left)
420
421                 str = str + '  | \n'
422                 return str
423                 
424 def encodeint (i):
425         return chr ( i  + ord ('A'))
426
427 class Staff:
428         def __init__ (self, number):
429                 self.number = number
430                 self.measures = []
431
432         def get_measure (self, no):
433                 if len (self.measures) <= no:
434                         self.measures = self.measures + [None]* (1 + no - len (self.measures))
435
436                 if self.measures[no] == None:
437                         m = Measure (no)
438                         self.measures [no] =m
439                         m.staff = self
440
441
442                 return self.measures[no]
443         def staffid (self):
444                 return 'staff' + encodeint (self.number - 1)
445         def layerid (self, l):
446                 return self.staffid() +  'layer%s' % chr (l -1 + ord ('A'))
447         
448         def dump_time_key_sigs (self):
449                 k  = ''
450                 last_key = None
451                 last_time = None
452                 last_clef = None
453                 gap = (0,1)
454                 for m in self.measures[1:]:
455                         if not m or not m.valid:
456                                 continue # ugh.
457                         
458                         g = m.global_measure
459                         e = ''
460                         if last_key <> g.keysignature:
461                                 e = e + "\\key %s \\major; " % lily_notename (g.keysignature)
462                                 last_key = g.keysignature
463                         if last_time <> g.timesig :
464                                 e = e + "\\time %d/%d; " % g.timesig
465                                 last_time = g.timesig
466                         if last_clef <> m.clef :
467                                 e = e + '\\clef %s;' % lily_clef (m.clef)
468                                 last_clef = m.clef
469                         if e:
470                                 if gap <> (0,1):
471                                         k = k +' ' + rat_to_lily_duration (gap) + '\n'
472                                 gap = (0,1)
473                                 k = k + e
474                         
475                         gap = rat_add (gap, g.length ())
476
477                                 
478                 k = '%sglobal = \\notes  { %s }\n\n ' % (self.staffid (), k)
479                 return k
480         
481         def dump (self):
482                 str = ''
483
484
485                 layerids = []
486                 for x in range (1,5): # 4 layers.
487                         laystr =  ''
488                         last_frame = None
489                         first_frame = None
490                         gap = (0,1)
491                         for m in self.measures[1:]:
492                                 if not m or not m.valid:
493                                         continue
494
495                                 fr = None
496                                 try:
497                                         fr = m.frames[x]
498                                 except IndexError:
499                                         pass
500                                 
501                                 if fr:
502                                         first_frame = fr
503                                         if gap <> (0,1):
504                                                 laystr = laystr +'} %s {\n ' % rat_to_lily_duration (gap)
505                                                 gap = (0,1)
506                                         laystr = laystr + fr.dump ()
507                                 else:
508                                         gap = rat_add (gap, m.global_measure.length ())
509
510                         if first_frame:
511                                 l = self.layerid (x)
512                                 laystr = '%s =  \\notes { { %s } }\n\n' % (l, laystr)
513                                 str = str  + laystr
514                                 layerids.append (l)
515
516                 str = str +  self.dump_time_key_sigs ()         
517                 stafdef = '\\%sglobal' % self.staffid ()
518                 for i in layerids:
519                         stafdef = stafdef + ' \\' + i
520                         
521
522                 str = str + '%s = \\context Staff = %s <\n %s\n >\n' % \
523                       (self.staffid (), self.staffid (), stafdef)
524                 return str
525
526                                 
527
528
529 class Chord:
530         def __init__ (self, finale_entry):
531                 self.pitches = []
532                 self.frame = None
533                 self.finale = finale_entry
534                 self.duration  = None
535                 self.next = None
536                 self.prev = None
537                 self.note_prefix= ''
538                 self.note_suffix = ''
539                 self.chord_suffix = ''
540                 self.chord_prefix = ''
541                 self.tuplet = None
542                 self.grace = 0
543                 
544         def measure (self):
545                 if not self.frame:
546                         return None
547                 return self.frame.measure
548
549         def length (self):
550                 if self.grace:
551                         return (0,1)
552                 
553                 l = (1, self.duration[0])
554
555                 d = 1 << self.duration[1]
556
557                 dotfact = rat_subtract ((2,1), (1,d))
558                 mylen =  rat_multiply (dotfact, l)
559
560                 if self.tuplet:
561                         mylen = rat_multiply (mylen, self.tuplet.factor())
562                 return mylen
563                 
564         def number (self):
565                 return self.finale[0][0]
566
567         def EDU_duration (self):
568                 return self.finale[0][3]
569         def set_duration (self):
570                 self.duration = EDU_to_duration(self.EDU_duration ())
571         def calculate (self):
572                 self.find_realpitch ()
573                 self.set_duration ()
574
575                 flag = self.finale[0][5]
576                 if Chord.GRACE_MASK & flag:
577                         self.grace = 1
578                 
579                 
580         def find_realpitch (self):
581                 
582                 ((no, prev, next, dur, pos, entryflag, extended, follow), notelist) = self.finale
583
584                 meas = self.measure ()
585                 tiestart = 0
586                 if not meas or not meas.global_measure  :
587                         print 'note %d not in measure' % self.number ()
588                 elif not meas.global_measure.scale:
589                         print  'note %d: no scale in this measure.' % self.number ()
590                 else:
591                         for p in notelist:
592                                 (pitch, flag) = p
593                                 
594                                 nib1 = pitch & 0x0f
595                                 if nib1 > 8:
596                                         nib1 = -(nib1 - 8)
597                                 rest = pitch / 16
598
599                                 scale =  meas.global_measure.scale 
600                                 (sn, sa) =scale[rest % 7]
601                                 sn = sn + (rest - (rest%7)) + 7
602                                 acc = sa + nib1
603                                 self.pitches.append ((sn, acc))
604                                 tiestart =  tiestart or (flag & Chord.TIE_START_MASK)
605                 if tiestart :
606                         self.chord_suffix = self.chord_suffix + ' ~ '
607                 
608         REST_MASK = 0x40000000L
609         TIE_START_MASK = 0x40000000L
610         GRACE_MASK = 0x00800000L
611         
612         def ly_string (self):
613                 s = ''
614
615                 rest = ''
616
617                 if not (self.finale[0][5] & Chord.REST_MASK):
618                         rest = 'r'
619                 
620                 for p in self.pitches:
621                         (n,a) =  p
622                         o = n/ 7
623                         n = n % 7
624
625                         nn = lily_notename ((n,a))
626
627                         if o < 0:
628                                 nn = nn + (',' * -o)
629                         elif o > 0:
630                                 nn = nn + ('\'' * o)
631                                 
632                         if s:
633                                 s = s + ' '
634
635                         if rest:
636                                 nn = rest
637                                 
638                         s = s + '%s%d%s' % (nn, self.duration[0], '.'* self.duration[1])
639
640                 if not self.pitches:
641                         s  = 'r%d%s' % (self.duration[0] , '.'* self.duration[1])
642                 s = self.note_prefix + s + self.note_suffix
643                 if len (self.pitches) > 1:
644                         s = '<%s>' % s
645                 
646                 s = self.chord_prefix + s + self.chord_suffix
647                 return s
648
649 GFre = re.compile(r"""^\^GF\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
650 BCre = re.compile (r"""^\^BC\(([0-9-]+)\) ([0-9-]+) .*$""")
651 eEre = re.compile(r"""^\^eE\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) \$([0-9A-Fa-f]+) ([0-9-]+) ([0-9-]+)""")
652 FRre = re.compile (r"""^\^FR\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
653 MSre = re.compile (r"""^\^MS\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
654 note_re = re.compile (r"""^ +([0-9-]+) \$([A-Fa-f0-9]+)""")
655 Sxre  = re.compile (r"""^\^Sx\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
656 IMre = re.compile (r"""^\^IM\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
657 vere = re.compile(r"""^\^(ve|ch|se)\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
658 versere = re.compile(r"""^\^verse\(([0-9]+)\)(.*)\^end""")
659
660 TPre = re.compile(r"""^\^TP\(([0-9]+),([0-9]+)\) *([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
661
662
663 class Etf_file:
664         def __init__ (self, name):
665                 self.measures = [None]
666                 self.entries = [None]
667                 self.chords = [None]
668                 self.frames = [None]
669                 self.tuplets = [None]
670                 self.staffs = [None]
671                 self.slur_dict = {}
672                 self.articulations = [None]
673                 self.syllables = [None]
674                 self.verses = [None]
675                 
676                 ## do it
677                 self.parse (name)
678
679         def get_global_measure (self, no):
680                 if len (self.measures) <= no:
681                         self.measures = self.measures + [None]* (1 + no - len (self.measures))
682
683                 if self.measures[no] == None:
684                         self.measures [no] = Global_measure (no)
685
686                 return self.measures[no]
687
688                 
689         def get_staff(self,staffno):
690                 if len (self.staffs) <= staffno:
691                         self.staffs = self.staffs + [None] * (1 + staffno - len (self.staffs))
692
693                 if self.staffs[staffno] == None:
694                         self.staffs[staffno] = Staff (staffno)
695
696                 return self.staffs[staffno]
697
698         # staff-spec
699         def try_IS (self, l):
700                 pass
701
702         def try_BC (self, l):
703                 m =  BCre.match  (l)
704                 if m:
705                         bn = string.atoi (m.group (1))
706                         where = string.atoi (m.group (2)) / 1024.0
707                 return m
708         def try_TP(self, l):
709                 m = TPre.match (l)
710                 if m:
711                         (nil, num) = map (string.atoi, (m.groups ()[0:2]))
712                         entries = map (string.atoi, (m.groups ()[2:]))
713
714                         if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
715                                 self.tuplets.append (Tuplet (num))
716
717                         self.tuplets[-1].append_finale (entries)
718                         
719         def try_IM (self, l):
720                 m = IMre.match (l)
721                 if m:
722                         a = string.atoi (m.group (1))
723                         b = string.atoi (m.group (2))
724
725                         fin = map (string.atoi, m.groups ()[2:])
726
727                         self.articulations.append (Articulation (a,b,fin))
728                 return m
729         def try_verse (self,l):
730                 m =  versere .match (l)
731                 if m:
732                         a = string.atoi (m.group (1))
733                         body =m.group (2)
734
735                         body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
736                         body = re.sub ("\^[a-z]+", "", body)
737                         self.verses.append (Verse (a, body))
738                         
739                 return m
740         def try_ve (self,l):
741                 m = vere .match (l)
742                 if m:
743                         a = string.atoi (m.group (1))
744                         b = string.atoi (m.group (2))
745
746                         fin = map (string.atoi, m.groups ()[2:])
747
748                         self.syllables.append (Syllable (a,b,fin))
749                 return m
750         def try_eE (self, l):
751                 m = eEre.match (l)
752                 if m:
753                         tup = m.groups()
754                         (no, prev, next, dur, pos, entryflag, extended, follow) = tup
755                         (no, prev, next, dur, pos,extended, follow) \
756                           = tuple (map (string.atoi, [no,prev,next,dur,pos,extended,follow]))
757
758                         entryflag = string.atol (entryflag,16)
759                         if no > len (self.entries):
760                                 sys.stderr.write ("\nHuh? Entry number to large,\nexpected %d got %d. Filling with void entries.\n" % (len(self.entries), no  ))
761                                 while len (self.entries) <> no:
762                                         c = ((len (self.entries), 0, 0, 0, 0, 0L, 0, 0), [])
763                                         self.entries.append (c)
764                                         
765                         current_entry = ((no, prev, next, dur, pos, entryflag, extended, follow), [])
766                         self.entries.append (current_entry)
767                 return m
768
769         def try_Sx(self,l):
770                 m = Sxre.match (l)
771                 if m:
772                         slurno = string.atoi (m.group (1))
773
774                         sl = None
775                         try:
776                                 sl = self.slur_dict[slurno]
777                         except KeyError:
778                                 sl = Slur (slurno)
779                                 self.slur_dict[slurno] = sl
780
781                         params = list (m.groups ()[1:])
782                         params = map (string.atoi, params)
783                         sl.append_entry (params)
784
785                 return m        
786         def try_GF(self, l):
787                 m = GFre.match (l)
788                 if m:
789                         (staffno,measno) = m.groups ()[0:2]
790                         s = string.atoi (staffno)
791                         me = string.atoi (measno)
792                         
793                         entry = m.groups () [2:]
794                         st = self.get_staff (s)
795                         meas = st.get_measure (me)
796                         meas.add_finale_entry (entry)
797                 
798         # frame  ?
799         def try_FR(self, l):
800                 m = FRre.match (l)
801                 if m:
802                         (frameno, startnote, endnote, foo, bar) = m.groups ()
803                         (frameno, startnote, endnote)  = tuple (map (string.atoi, [frameno, startnote, endnote]))
804                         if frameno > len (self.frames):
805                                 sys.stderr.write ("Frame no %d missing, filling up to %d\n" % (len(self.frames), frameno))
806                                 while frameno <> len (self.frames):
807                                         self.frames.append (Frame ((len (self.frames), 0,0) ))
808                         
809                         self.frames.append (Frame ((frameno, startnote, endnote)))
810                         
811                 return m
812         def try_MS (self, l):
813                 m = MSre.match (l)
814                 if m:
815                         measno = string.atoi (m.group (1))
816                         keynum = string.atoi (m.group (3))
817                         meas =self. get_global_measure (measno)
818                         meas.set_keysig (keynum)
819
820                         beats = string.atoi (m.group (4))
821                         beatlen = string.atoi (m.group (5))
822                         meas.set_timesig ((beats, beatlen))
823                                                 
824                 return m
825
826         def try_note (self, l):
827                 m = note_re.match (l)
828                 if m:
829                         (pitch, flag) = m.groups ()
830                         pitch = string.atoi (pitch)
831                         flag = string.atol (flag,16)
832                         self.entries[-1][1].append ((pitch,flag))
833
834         def parse (self, name):
835                 sys.stderr.write ('parsing ...')
836                 sys.stderr.flush ()
837
838                 gulp = open (name).read ()
839
840                 gulp = re.sub ('[\n\r]+', '\n',  gulp)
841                 ls = string.split (gulp, '\n')
842                 
843                 for l in ls:
844                         m = None
845                         if not m: 
846                                 m = self.try_MS (l)
847                         if not m: 
848                                 m = self.try_FR (l)
849                         if not m: 
850                                 m = self.try_GF (l)
851                         if not m: 
852                                 m = self.try_note (l)
853                         if not m: 
854                                 m = self.try_eE (l)
855                         if not m:
856                                 m = self.try_IM (l)
857                         if not m:
858                                 m = self.try_Sx (l)
859                         if not m:
860                                 m = self.try_TP (l)
861                         if not m:
862                                 m = self.try_verse (l)
863
864                 sys.stderr.write ('processing ...')
865                 sys.stderr.flush ()
866
867                 self.unthread_entries ()
868
869                 for st in self.staffs[1:]:
870                         if not st:
871                                 continue
872                         mno = 1
873                         for m in st.measures[1:]:
874                                 if not m:
875                                         continue
876                                 
877                                 m.calculate()
878                                 try:
879                                         m.global_measure = self.measures[mno]
880                                 except IndexError:
881                                         sys.stderr.write ("non-existent global measure %d" % mno)
882                                         continue
883                                 
884                                 frame_obj_list = [None]
885                                 for frno in m.frames:
886                                         fr = self.frames[frno]
887                                         frame_obj_list.append (fr)
888
889                                 m.frames = frame_obj_list
890                                 for fr in frame_obj_list[1:]:
891                                         if not fr:
892                                                 continue
893                                         
894                                         fr.set_measure (m)
895                                         
896                                         fr.chords = self.get_thread (fr.start, fr.end)
897                                         for c in fr.chords:
898                                                 c.frame = fr
899                                 mno = mno + 1
900
901                 for c in self.chords[1:]:
902                         c.calculate()
903
904                 for f in self.frames[1:]:
905                         f.calculate ()
906                         
907                 for t in self.tuplets[1:]:
908                         t.calculate (self.chords)
909                         
910                 for s in self.slur_dict.values():
911                         s.calculate (self.chords)
912                 for s in self.articulations[1:]:
913                         s.calculate (self.chords)
914                         
915         def get_thread (self, startno, endno):
916
917                 thread = []
918
919                 c = None
920                 try:
921                         c = self.chords[startno]
922                 except IndexError:
923                         sys.stderr.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno, endno))
924                         return []
925
926                 
927                 while c and c.number () <> endno:
928                         thread.append (c)
929                         c = c.next
930
931                 if c: 
932                         thread.append (c)
933                 
934                 return thread
935
936         def dump (self):
937                 str = ''
938                 staffs = []
939                 for s in self.staffs[1:]:
940                         if s:
941                                 str = str + '\n\n' + s.dump () 
942                                 staffs.append ('\\' + s.staffid ())
943
944
945                 # should use \addlyrics ?
946
947                 for v in self.verses[1:]:
948                         str = str + v.dump()
949
950                 if len (self.verses) > 1:
951                         sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
952                         
953                 if staffs:
954                         str = str + '\\score { < %s > } ' % string.join (staffs)
955                         
956                 return str
957
958
959         def __str__ (self):
960                 return 'ETF FILE %s %s' % (self.measures,  self.entries)
961         
962         def unthread_entries (self):
963                 self.chords = [None]
964                 for e in self.entries[1:]:
965                         self.chords.append (Chord (e))
966
967                 for e in self.chords[1:]:
968                         e.prev = self.chords[e.finale[0][1]]
969                         e.next = self.chords[e.finale[0][2]]
970
971 def identify():
972         sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
973
974 def help ():
975         print """Usage: etf2ly [OPTION]... ETF-FILE
976
977 Convert ETF to LilyPond.
978
979 Options:
980   -h,--help          this help
981   -o,--output=FILE   set output filename to FILE
982   -v,--version       version information
983
984 Enigma Transport Format is a format used by Coda Music Technology's
985 Finale product. This program will convert a subset of ETF to a
986 ready-to-use lilypond file.
987
988 Report bugs to bug-gnu-music@gnu.org
989
990 Written by  Han-Wen Nienhuys <hanwen@cs.uu.nl>
991 """
992
993 def print_version ():
994         print r"""etf2ly (GNU lilypond) %s
995
996 This is free software.  It is covered by the GNU General Public License,
997 and you are welcome to change it and/or distribute copies of it under
998 certain conditions.  Invoke as `midi2ly --warranty' for more information.
999
1000 Copyright (c) 2000 by Han-Wen Nienhuys <hanwen@cs.uu.nl>
1001 """ % version
1002
1003
1004
1005 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
1006 out_filename = None
1007
1008 for opt in options:
1009         o = opt[0]
1010         a = opt[1]
1011         if o== '--help' or o == '-h':
1012                 help ()
1013                 sys.exit (0)
1014         if o == '--version' or o == '-v':
1015                 print_version ()
1016                 sys.exit(0)
1017                 
1018         if o == '--output' or o == '-o':
1019                 out_filename = a
1020         else:
1021                 print o
1022                 raise getopt.error
1023
1024 identify()
1025
1026 for f in files:
1027         if f == '-':
1028                 f = ''
1029
1030         sys.stderr.write ('Processing `%s\'\n' % f)
1031         e = Etf_file(f)
1032         if not out_filename:
1033                 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1034                 
1035         if out_filename == f:
1036                 out_filename = os.path.basename (f + '.ly')
1037                 
1038         sys.stderr.write ('Writing `%s\'' % out_filename)
1039         ly = e.dump()
1040
1041         
1042         
1043         fo = open (out_filename, 'w')
1044         fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)
1045         fo.write(ly)
1046         fo.close ()
1047