]> git.donarmstrong.com Git - lilypond.git/blob - scripts/etf2ly.py
* scripts/musedata2ly.py (): idem
[lilypond.git] / scripts / etf2ly.py
1 #!@PYTHON@
2
3 # info mostly taken from looking at files. See also
4 # http://lilypond.org/wiki/?EnigmaTransportFormat
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_suffix = ce.note_suffix + '-)'
238                         
239                 except IndexError:
240                         sys.stderr.write ("""\nHuh? Slur no %d between (%d,%d), with %d notes""" % (self.number,  startnote, endnote, len (chords)))
241                                          
242                 
243 class Global_measure:
244         def __init__ (self, number):
245                 self.timesig = ''
246                 self.number = number
247                 self.keysignature = None
248                 self.scale = None
249                 self.force_break = 0
250                 
251                 self.repeats = []
252                 self.finale = []
253
254         def __str__ (self):
255                 return `self.finale `
256         
257         def set_timesig (self, finale):
258                 (beats, fdur) = finale
259                 (log, dots) = EDU_to_duration (fdur)
260                 if dots <> 0:
261                         sys.stderr.write ("\nHuh? Beat duration has a dot? (EDU Duration = %d)" % fdur) 
262                 self.timesig = (beats, log)
263
264         def length (self):
265                 return self.timesig
266         
267         def set_keysig (self, finale):
268                 k = interpret_finale_key_sig (finale)
269                 self.keysignature = k
270                 self.scale = find_scale (k)
271
272         def set_flags (self,flag1, flag2):
273                 
274                 # flag1 isn't all that interesting.
275                 if flag2 & 0x8000:
276                         self.force_break = 1
277                         
278                 if flag2 & 0x0008:
279                         self.repeats.append ('start')
280                 if flag2 & 0x0004:
281                         self.repeats.append ('stop')
282                         
283                 if flag2 & 0x0002:
284                         if flag2 & 0x0004:
285                                 self.repeats.append ('bracket')
286
287 articulation_dict ={
288         94: '^',
289         109: '\\prall',
290         84: '\\turn',
291         62: '\\mordent',
292         85: '\\fermata',
293         46: '.',
294 #       3: '>',
295 #       18: '\arpeggio' ,
296 }
297
298 class Articulation_def:
299         def __init__ (self, n, a, b):
300                 self.finale_glyph = a & 0xff
301                 self.number = n
302
303         def dump (self):
304                 try:
305                         return articulation_dict[self.finale_glyph]
306                 except KeyError:
307                         sys.stderr.write ("\nUnknown articulation no. %d" % self.finale_glyph)
308                         sys.stderr.write ("\nPlease add an entry to articulation_dict in the Python source")                    
309                         return None
310         
311 class Articulation:
312         def __init__ (self, a,b, finale):
313                 self.definition = finale[0]
314                 self.notenumber = b
315                 
316         def calculate (self, chords, defs):
317                 c = chords[self.notenumber]
318
319                 adef = defs[self.definition]
320                 lystr =adef.dump()
321                 if lystr == None:
322                         lystr = '"art"'
323                         sys.stderr.write ("\nThis happened on note %d" % self.notenumber)
324
325                 c.note_suffix = '-' + lystr
326
327 class Syllable:
328         def __init__ (self, a,b , finale):
329                 self.chordnum = b
330                 self.syllable = finale[1]
331                 self.verse = finale[0]
332         def calculate (self, chords, lyrics):
333                 self.chord = chords[self.chordnum]
334
335 class Verse:
336         def __init__ (self, number, body):
337                 self.body = body
338                 self.number = number
339                 self.split_syllables ()
340         def split_syllables (self):
341                 ss = re.split ('(-| +)', self.body)
342
343                 sep = 0
344                 syls = [None]
345                 for s in ss:
346                         if sep:
347                                 septor = re.sub (" +", "", s)
348                                 septor = re.sub ("-", " -- ", septor) 
349                                 syls[-1] = syls[-1] + septor
350                         else:
351                                 syls.append (s)
352                         
353                         sep = not sep 
354
355                 self.syllables = syls
356
357         def dump (self):
358                 str = ''
359                 line = ''
360                 for s in self.syllables[1:]:
361                         line = line + ' ' + s
362                         if len (line) > 72:
363                                 str = str + ' ' * 4 + line + '\n'
364                                 line = ''
365                         
366                 str = """\nverse%s = \\lyrics {\n %s}\n""" %  (encodeint (self.number - 1) ,str)
367                 return str
368
369         
370 class Measure:
371         def __init__(self, no):
372                 self.number = no
373                 self.frames = [0] * 4
374                 self.flags = 0
375                 self.clef = 0
376                 self.finale = []
377                 self.global_measure = None
378                 self.staff = None
379                 self.valid = 1
380                 
381
382         def valid (self):
383                 return self.valid
384         def calculate (self):
385                 fs = []
386
387                 if len (self.finale) < 2:
388                         fs = self.finale[0]
389
390                         self.clef = fs[1]
391                         self.frames = [fs[0]]
392                 else:
393                         fs = self.finale
394                         self.clef = fs[0]
395                         self.flags = fs[1]
396                         self.frames = fs[2:]
397
398
399 class Frame:
400         def __init__ (self, finale):
401                 self.measure = None
402                 self.finale = finale
403                 (number, start, end ) = finale
404                 self.number = number
405                 self.start = start
406                 self.end = end
407                 self.chords  = []
408
409         def set_measure (self, m):
410                 self.measure = m
411
412         def calculate (self):
413
414                 # do grace notes.
415                 lastch = None
416                 for c in self.chords:
417                         if c.grace and (lastch == None or (not lastch.grace)):
418                                 c.chord_prefix = r'\grace {' + c.chord_prefix
419                         elif not c.grace and lastch and lastch.grace:
420                                 lastch.chord_suffix = lastch.chord_suffix + ' } '
421
422                         lastch = c
423                         
424
425                 
426         def dump (self):
427                 str = '%% FR(%d)\n' % self.number
428                 left = self.measure.global_measure.length ()
429
430                 
431                 ln = ''
432                 for c in self.chords:
433                         add = c.ly_string () + ' '
434                         if len (ln) + len(add) > 72:
435                                 str = str + ln + '\n'
436                                 ln = ''
437                         ln = ln + add
438                         left = rat_subtract (left, c.length ())
439
440                 str = str + ln 
441                 
442                 if left[0] < 0:
443                         sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
444                         left = (0,1)
445                 if left[0]:
446                         str = str + rat_to_lily_duration (left)
447
448                 str = str + '  | \n'
449                 return str
450                 
451 def encodeint (i):
452         return chr ( i  + ord ('A'))
453
454 class Staff:
455         def __init__ (self, number):
456                 self.number = number
457                 self.measures = []
458
459         def get_measure (self, no):
460                 fill_list_to (self.measures, no)
461
462                 if self.measures[no] == None:
463                         m = Measure (no)
464                         self.measures [no] =m
465                         m.staff = self
466
467                 return self.measures[no]
468         def staffid (self):
469                 return 'staff' + encodeint (self.number - 1)
470         def layerid (self, l):
471                 return self.staffid() +  'layer%s' % chr (l -1 + ord ('A'))
472         
473         def dump_time_key_sigs (self):
474                 k  = ''
475                 last_key = None
476                 last_time = None
477                 last_clef = None
478                 gap = (0,1)
479                 for m in self.measures[1:]:
480                         if not m or not m.valid:
481                                 continue # ugh.
482                         
483                         g = m.global_measure
484                         e = ''
485                         
486                         if g:
487                                 if last_key <> g.keysignature:
488                                         e = e + "\\key %s \\major " % lily_notename (g.keysignature)
489                                         last_key = g.keysignature
490                                 if last_time <> g.timesig :
491                                         e = e + "\\time %d/%d " % g.timesig
492                                         last_time = g.timesig
493
494                                 if 'start' in g.repeats:
495                                         e = e + ' \\bar "|:" ' 
496
497
498                                 # we don't attempt voltas since they fail easily.
499                                 if 0 : # and g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket:
500                                         strs = []
501                                         if g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket == 'end':
502                                                 strs.append ('#f')
503
504                                         
505                                         if g.bracket == 'start':
506                                                 strs.append ('"0."')
507
508                                         str = string.join (map (lambda x: '(volta %s)' % x, strs))
509                                         
510                                         e = e + ' \\property Score.repeatCommands =  #\'(%s) ' % str
511
512                                 if g.force_break:
513                                         e = e + ' \\break '  
514                         
515                         if last_clef <> m.clef :
516                                 e = e + '\\clef "%s"' % lily_clef (m.clef)
517                                 last_clef = m.clef
518                         if e:
519                                 if gap <> (0,1):
520                                         k = k +' ' + rat_to_lily_duration (gap) + '\n'
521                                 gap = (0,1)
522                                 k = k + e
523                                 
524                         if g:
525                                 gap = rat_add (gap, g.length ())
526                                 if 'stop' in g.repeats:
527                                         k = k + ' \\bar ":|" '
528                                 
529                 k = '%sglobal = \\notes  { %s }\n\n ' % (self.staffid (), k)
530                 return k
531         
532         def dump (self):
533                 str = ''
534
535
536                 layerids = []
537                 for x in range (1,5): # 4 layers.
538                         laystr =  ''
539                         last_frame = None
540                         first_frame = None
541                         gap = (0,1)
542                         for m in self.measures[1:]:
543                                 if not m or not m.valid:
544                                         sys.stderr.write ("Skipping non-existant or invalid measure\n")
545                                         continue
546
547                                 fr = None
548                                 try:
549                                         fr = m.frames[x]
550                                 except IndexError:
551                                         sys.stderr.write ("Skipping nonexistent frame %d\n" % x)
552                                         laystr = laystr + "%% non existent frame %d (skipped) \n" % x
553                                 if fr:
554                                         first_frame = fr
555                                         if gap <> (0,1):
556                                                 laystr = laystr +'} %s {\n ' % rat_to_lily_duration (gap)
557                                                 gap = (0,1)
558                                         laystr = laystr + fr.dump ()
559                                 else:
560                                         if m.global_measure :
561                                                 gap = rat_add (gap, m.global_measure.length ())
562                                         else:
563                                                 sys.stderr.write ( \
564                                                         "No global measure for staff %d measure %d\n"
565                                                         % (self.number, m.number))
566                         if first_frame:
567                                 l = self.layerid (x)
568                                 laystr = '%s =  \\notes { { %s } }\n\n' % (l, laystr)
569                                 str = str  + laystr
570                                 layerids.append (l)
571
572                 str = str +  self.dump_time_key_sigs ()         
573                 stafdef = '\\%sglobal' % self.staffid ()
574                 for i in layerids:
575                         stafdef = stafdef + ' \\' + i
576                         
577
578                 str = str + '%s = \\context Staff = %s <\n %s\n >\n' % \
579                       (self.staffid (), self.staffid (), stafdef)
580                 return str
581
582                                 
583
584 def ziplist (l):
585         if len (l) < 2:
586                 return []
587         else:
588                 return [(l[0], l[1])] + ziplist (l[2:])
589
590
591 class Chord:
592         def __init__ (self, number, contents):
593                 self.pitches = []
594                 self.frame = None
595                 self.finale = contents[:7]
596
597                 self.notelist = ziplist (contents[7:])
598                 self.duration  = None
599                 self.next = None
600                 self.prev = None
601                 self.number = number
602                 self.note_prefix= ''
603                 self.note_suffix = ''
604                 self.chord_suffix = ''
605                 self.chord_prefix = ''
606                 self.tuplet = None
607                 self.grace = 0
608                 
609         def measure (self):
610                 if not self.frame:
611                         return None
612                 return self.frame.measure
613
614         def length (self):
615                 if self.grace:
616                         return (0,1)
617                 
618                 l = (1, self.duration[0])
619
620                 d = 1 << self.duration[1]
621
622                 dotfact = rat_subtract ((2,1), (1,d))
623                 mylen =  rat_multiply (dotfact, l)
624
625                 if self.tuplet:
626                         mylen = rat_multiply (mylen, self.tuplet.factor())
627                 return mylen
628                 
629
630         def EDU_duration (self):
631                 return self.finale[2]
632         def set_duration (self):
633                 self.duration = EDU_to_duration(self.EDU_duration ())
634                 
635         def calculate (self):
636                 self.find_realpitch ()
637                 self.set_duration ()
638
639                 flag = self.finale[4]
640                 if Chord.GRACE_MASK & flag:
641                         self.grace = 1
642                 
643         
644         def find_realpitch (self):
645
646                 meas = self.measure ()
647                 tiestart = 0
648                 if not meas or not meas.global_measure  :
649                         sys.stderr.write ('note %d not in measure\n' % self.number)
650                 elif not meas.global_measure.scale:
651                         sys.stderr.write ('note %d: no scale in this measure.' % self.number)
652                 else:
653                         
654                         for p in self.notelist:
655                                 (pitch, flag) = p
656
657
658                                 nib1 = pitch & 0x0f
659                                 
660                                 if nib1 > 8:
661                                         nib1 = -(nib1 - 8)
662                                 rest = pitch / 16
663
664                                 scale =  meas.global_measure.scale 
665                                 (sn, sa) =scale[rest % 7]
666                                 sn = sn + (rest - (rest%7)) + 7
667                                 acc = sa + nib1
668                                 self.pitches.append ((sn, acc))
669                                 tiestart =  tiestart or (flag & Chord.TIE_START_MASK)
670                 if tiestart :
671                         self.chord_suffix = self.chord_suffix + ' ~ '
672                 
673         REST_MASK = 0x40000000L
674         TIE_START_MASK = 0x40000000L
675         GRACE_MASK = 0x00800000L
676         
677         def ly_string (self):
678                 s = ''
679
680                 rest = ''
681
682
683                 if not (self.finale[4] & Chord.REST_MASK):
684                         rest = 'r'
685                 
686                 for p in self.pitches:
687                         (n,a) =  p
688                         o = n/ 7
689                         n = n % 7
690
691                         nn = lily_notename ((n,a))
692
693                         if o < 0:
694                                 nn = nn + (',' * -o)
695                         elif o > 0:
696                                 nn = nn + ('\'' * o)
697                                 
698                         if s:
699                                 s = s + ' '
700
701                         if rest:
702                                 nn = rest
703                                 
704                         s = s + nn 
705
706                 if not self.pitches:
707                         s  = 'r'
708                 if len (self.pitches) > 1:
709                         s = '<< %s >>' % s
710
711                 s = s + '%d%s' % (self.duration[0], '.'* self.duration[1])
712                 s = self.note_prefix + s + self.note_suffix
713                 
714                 s = self.chord_prefix + s + self.chord_suffix
715
716                 return s
717
718
719 def fill_list_to (list, no):
720         """
721 Add None to LIST until it contains entry number NO.
722         """
723         while len (list) <= no:
724                 list.extend ([None] * (no - len(list) + 1))
725         return list
726
727 def read_finale_value (str):
728         """
729 Pry off one value from STR. The value may be $hex, decimal, or "string".
730 Return: (value, rest-of-STR)
731         """
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                                         try:
1001                                                 fr = self.frames[frno]
1002                                                 frame_obj_list.append (fr)
1003                                         except IndexError:
1004                                                 sys.stderr.write ("\nNon-existent frame %d"  % frno)
1005
1006                                 m.frames = frame_obj_list
1007                                 for fr in frame_obj_list[1:]:
1008                                         if not fr:
1009                                                 continue
1010                                         
1011                                         fr.set_measure (m)
1012                                         
1013                                         fr.chords = self.get_thread (fr.start, fr.end)
1014                                         for c in fr.chords:
1015                                                 c.frame = fr
1016                                 mno = mno + 1
1017
1018                 for c in self.chords[1:]:
1019                         if c:
1020                                 c.calculate()
1021
1022                 for f in self.frames[1:]:
1023                         if f:
1024                                 f.calculate ()
1025                         
1026                 for t in self.tuplets[1:]:
1027                         t.calculate (self.chords)
1028                         
1029                 for s in self.slurs[1:]:
1030                         if s:
1031                                 s.calculate (self.chords)
1032                         
1033                 for s in self.articulations[1:]:
1034                         s.calculate (self.chords, self.articulation_defs)
1035                         
1036         def get_thread (self, startno, endno):
1037
1038                 thread = []
1039
1040                 c = None
1041                 try:
1042                         c = self.chords[startno]
1043                 except IndexError:
1044                         sys.stderr.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno, endno))
1045                         return []
1046
1047                 
1048                 while c and c.number <> endno:
1049                         thread.append (c)
1050                         c = c.next
1051
1052                 if c: 
1053                         thread.append (c)
1054                 
1055                 return thread
1056
1057         def dump (self):
1058                 str = ''
1059                 staffs = []
1060                 for s in self.staffs[1:]:
1061                         if s:
1062                                 str = str + '\n\n' + s.dump () 
1063                                 staffs.append ('\\' + s.staffid ())
1064
1065
1066                 # should use \addlyrics ?
1067
1068                 for v in self.verses[1:]:
1069                         str = str + v.dump()
1070
1071                 if len (self.verses) > 1:
1072                         sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
1073                         
1074                 if staffs:
1075                         str = str + '\\score { < %s > } ' % string.join (staffs)
1076                         
1077                 return str
1078
1079
1080         def __str__ (self):
1081                 return 'ETF FILE %s %s' % (self.measures,  self.entries)
1082         
1083         def unthread_entries (self):
1084                 for e in self.chords[1:]:
1085                         if not e:
1086                                 continue
1087
1088                         e.prev = self.chords[e.finale[0]]
1089                         e.next = self.chords[e.finale[1]]
1090
1091 def identify():
1092         sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1093
1094 def help ():
1095         sys.stdout.write("""Usage: etf2ly [OPTION]... ETF-FILE
1096
1097 Convert ETF to LilyPond.
1098
1099 Options:
1100   -h,--help          this help
1101   -o,--output=FILE   set output filename to FILE
1102   -v,--version       version information
1103
1104 Enigma Transport Format is a format used by Coda Music Technology's
1105 Finale product. This program will convert a subset of ETF to a
1106 ready-to-use lilypond file.
1107
1108 Report bugs to bug-lilypond@gnu.org
1109
1110 Written by  Han-Wen Nienhuys <hanwen@cs.uu.nl>
1111 """)
1112
1113 def print_version ():
1114         sys.stdout.write (r"""etf2ly (GNU lilypond) %s
1115
1116 This is free software.  It is covered by the GNU General Public License,
1117 and you are welcome to change it and/or distribute copies of it under
1118 certain conditions.  Invoke as `midi2ly --warranty' for more information.
1119
1120 Copyright (c) 2000 by Han-Wen Nienhuys <hanwen@cs.uu.nl>
1121 """ % version)
1122
1123
1124
1125 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
1126 out_filename = None
1127
1128 for opt in options:
1129         o = opt[0]
1130         a = opt[1]
1131         if o== '--help' or o == '-h':
1132                 help ()
1133                 sys.exit (0)
1134         if o == '--version' or o == '-v':
1135                 print_version ()
1136                 sys.exit(0)
1137                 
1138         if o == '--output' or o == '-o':
1139                 out_filename = a
1140         else:
1141                 print o
1142                 raise getopt.error
1143
1144 identify()
1145
1146 e = None
1147 for f in files:
1148         if f == '-':
1149                 f = ''
1150
1151         sys.stderr.write ('Processing `%s\'\n' % f)
1152
1153         dict = parse_etf_file (f, Etf_file.routine_dict)
1154         e = Etf_file(dict)
1155         if not out_filename:
1156                 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1157                 
1158         if out_filename == f:
1159                 out_filename = os.path.basename (f + '.ly')
1160                 
1161         sys.stderr.write ('Writing `%s\'' % out_filename)
1162         ly = e.dump()
1163
1164         
1165         
1166         fo = open (out_filename, 'w')
1167         fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)
1168         fo.write(ly)
1169         fo.close ()
1170