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