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