Compile fix.
[lilypond/mpolesky.git] / scm / song.scm
blob410b3c89df99361cd1b9d75f4fdd11b6ab9bab8a
1 ;;;; song.scm --- Festival singing mode output
2 ;;;;
3 ;;;; This file is part of LilyPond, the GNU music typesetter.
4 ;;;;
5 ;;;; Copyright (C) 2006, 2007 Brailcom, o.p.s.
6 ;;;; Author: Milan Zamazal <pdm@brailcom.org>
7 ;;;;
8 ;;;; LilyPond is free software: you can redistribute it and/or modify
9 ;;;; it under the terms of the GNU General Public License as published by
10 ;;;; the Free Software Foundation, either version 3 of the License, or
11 ;;;; (at your option) any later version.
12 ;;;;
13 ;;;; LilyPond is distributed in the hope that it will be useful,
14 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 ;;;; GNU General Public License for more details.
17 ;;;;
18 ;;;; You should have received a copy of the GNU General Public License
19 ;;;; along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
22 (define-module (scm song))
24 (use-modules (srfi srfi-1))
25 (use-modules (ice-9 optargs))
26 (use-modules (ice-9 receive))
28 (use-modules (lily))
29 (use-modules (scm song-util))
32 ;;; Configuration
35 ;; The word to be sung in places where notes are played without lyrics.
36 ;; If it is #f, the places without lyrics are omitted on the output.
37 (define-public *skip-word* "-skip-")
39 ;; If true, use syllables in the Festival XML file.
40 ;; If false, use whole words instead; this is necessary in languages like
41 ;; English, were the phonetic form cannot be deduced from syllables well enough.
42 (define-public *syllabify* #f)
44 ;; Base Festival octave to which LilyPond notes are mapped.
45 (define-public *base-octave* 5)
46 ;; The resulting base octave is sum of *base-octave* and
47 ;; *base-octave-shift*.  This is done to work around a Festival bug
48 ;; causing Festival to segfault or produce invalid pitch on higher pitches.
49 ;(define *base-octave-shift* -2)
50 (define *base-octave-shift* 0)
52 ;; The coeficient by which the notes just before \breath are shortened.
53 (define-public *breathe-shortage* 0.8)
56 ;;; LilyPond interface
59 (define-public (output-file music tempo filename)
60   (if *debug*
61       (debug-enable 'backtrace))
62   (ly:message "Writing Festival XML file ~a..." filename)
63   (let ((port (open-output-file filename)))
64     (write-header port tempo)
65     (write-lyrics port music)
66     (write-footer port)
67     (close-port port))
68   #f)
71 ;;; Utility functions
74 (define pp-pitch-names '((0 . "c") (1 . "des") (2 . "d") (3 . "es") (4 . "e") (5 . "f")
75                          (6 . "ges") (7 . "g") (8 . "as") (9 . "a") (10 . "bes") (11 . "b")))
76 (define (pp object)
77   (cond
78    ((list? object)
79     (format #f "[~{~a ~}]" (map pp object)))
80    ((skip? object)
81     (format #f "skip(~a)" (skip-duration object)))
82    ((lyrics? object)
83     (format #f "~a(~a)~a" (lyrics-text object) (lyrics-duration object)
84             (if (lyrics-unfinished object) "-" "")))
85    ((note? object)
86     (let ((pitch (ly:pitch-semitones (note-pitch object))))
87       (format #f "~a~a~a~a"
88               (assoc-get (modulo pitch 12) pp-pitch-names)
89               (let ((octave (+ (inexact->exact (floor (/ pitch 12))) 1)))
90                 (cond
91                  ((= octave 0)
92                   "")
93                  ((> octave 0)
94                   (make-uniform-array #\' octave))
95                  ((< octave 0)
96                   (make-uniform-array #\, (- 0 octave)))))
97               (pp-duration (note-duration object))
98               (if (> (note-joined object) 0) "-" ""))))
99    ((rest? object)
100     (format #f "r~a" (pp-duration (rest-duration object))))
101    (else
102     object)))
104 (define (pp-duration duration)
105   (set! duration (/ 4 duration))
106   (if (< (abs (- duration (inexact->exact duration))) 0.0001)
107       (inexact->exact duration)
108       (/ (round (* duration 100)) 100)))
110 (define-public (warning object-with-origin message . args)
111   (let ((origin (cond
112                  ((not object-with-origin)
113                   #f)
114                  ((note? object-with-origin)
115                   (note-origin object-with-origin))
116                  ((rest? object-with-origin)
117                   (rest-origin object-with-origin))
118                  ((ly:input-location? object-with-origin)
119                   object-with-origin)
120                  ((ly:music? object-with-origin)
121                   (ly:music-property object-with-origin 'origin))
122                  (else
123                   (format #t "Minor programming error: ~a~%" object-with-origin)
124                   #f))))
125     (if origin
126         (ly:input-message origin "***Song Warning***")
127         (format #t "~%***Song Warning***"))
128     (apply ly:message message (map pp args))))
131 ;;; Analysis functions
134 (define *default-tempo* #f)
135 (define *tempo-compression* #f)
137 (define (duration->number duration)
138   (let* ((log (ly:duration-log duration))
139          (dots (ly:duration-dot-count duration))
140          (factor (ly:duration-factor duration)))
141     (exact->inexact (* (expt 2 (- log)) (+ 1 (/ dots 2)) (/ (car factor) (cdr factor))))))
143 (define (tempo->beats music)
144   (let* ((tempo-spec (or (find-child-named music 'MetronomeChangeEvent)
145                          (find-child-named music 'SequentialMusic)))
146          (tempo (cond
147                  ((not tempo-spec)
148                   #f)
149                  ((music-name? tempo-spec 'MetronomeChangeEvent)
150                   (* (ly:music-property tempo-spec 'metronome-count)
151                      (duration->number (ly:music-property tempo-spec 'tempo-unit))))
152                  ((music-name? tempo-spec 'SequentialMusic)
153                   (* (property-value
154                       (find-child tempo-spec (lambda (elt) (music-property? elt 'tempoUnitCount))))
155                      (duration->number
156                       (property-value
157                        (find-child tempo-spec (lambda (elt) (music-property? elt 'tempoUnitDuration)))))))
158                  (else
159                   (format #t "Programming error (tempo->beats): ~a~%" tempo-spec)))))
160     (debug-enable 'backtrace)
161     (if (and tempo (music-name? tempo-spec 'SequentialMusic))
162         (set! *default-tempo* (property-value
163                                (find-child tempo-spec (lambda (elt) (music-property? elt 'tempoWholesPerMinute))))))
164     (if tempo
165         (round (* tempo (expt 2 (+ 2 *base-octave-shift*))))
166         #f)))
168 (defstruct music-context
169   music
170   context)
172 (define (collect-lyrics-music music)
173   ;; Returns list of music-context instances.
174   (let ((music-context-list '()))
175     (process-music
176      music
177      (lambda (music*)
178        (cond
179         ((music-name? music* 'LyricCombineMusic)
180          (push! (make-music-context #:music music*
181                                               #:context (ly:music-property music* 'associated-context))
182                      music-context-list)
183          #t)
184         ((and (music-name? music* 'ContextSpeccedMusic)
185               (music-property-value? music* 'context-type 'Lyrics)
186               (not (find-child-named music* 'LyricCombineMusic)))
187          (let ((name-node (find-child music* (lambda (node) (music-property? node 'associatedVoice)))))
188            (if name-node
189                (push! (make-music-context #:music music* #:context (property-value name-node))
190                            music-context-list)))
191          #t)
192         (else
193          #f))))
194     (debug "Lyrics contexts" (reverse music-context-list))))
196 (defstruct lyrics
197   text
198   duration
199   unfinished
200   ignore-melismata
201   context)
203 (defstruct skip
204   duration
205   context)
207 (define (get-lyrics music context)
208   ;; Returns list of lyrics and skip instances.
209   (let ((lyrics-list '())
210         (next-ignore-melismata #f)
211         (ignore-melismata #f)
212         (next-current-voice context)
213         (current-voice context))
214     (process-music
215      music
216      (lambda (music)
217        (cond
218         ;; true lyrics
219         ((music-name? music 'EventChord)
220          (let ((lyric-event (find-child-named music 'LyricEvent)))
221            (push! (make-lyrics
222                         #:text (ly:music-property lyric-event 'text)
223                         #:duration (* (duration->number (ly:music-property lyric-event 'duration)) 4)
224                         #:unfinished (and (not *syllabify*) (find-child-named music 'HyphenEvent))
225                         #:ignore-melismata ignore-melismata
226                         #:context current-voice)
227                        lyrics-list))
228          ;; LilyPond delays applying settings
229          (set! ignore-melismata next-ignore-melismata)
230          (set! current-voice next-current-voice)
231          #t)
232         ;; skipping
233         ((music-name? music 'SkipMusic)
234          (push! (make-skip
235                       #:duration (* (duration->number (ly:music-property music 'duration)) 4)
236                       #:context current-voice)
237                      lyrics-list)
238          #t)
239         ;; parameter change
240         ((music-property? music 'ignoreMelismata)
241          (set! next-ignore-melismata (property-value music))
242          #t)
243         ((music-property? music 'associatedVoice)
244          (set! next-current-voice (property-value music))
245          #t)
246         ;; anything else
247         (else
248          #f))))
249     (debug "Raw lyrics" (reverse lyrics-list))))
251 (defstruct score-voice
252   context
253   elements ; list of score-* instances
254   )
256 (defstruct score-choice
257   lists ; of lists of score-* instances
258   (n-assigned 0) ; number of lists having a verse-block
259   )
261 (defstruct score-repetice
262   count ; number of repetitions
263   elements ; list of score-* instances
264   )
266 (defstruct score-notes
267   note/rest-list ; list of note and rest instances
268   (verse-block-list '()) ; lyrics attached to notes -- multiple elements are
269                          ; possible for multiple stanzas
270   )
272 (defstruct note
273   pitch
274   duration
275   joined ; to the next note
276   origin
277   )
279 (defstruct rest
280   duration
281   origin
282   )
284 (define (get-notes music)
285   ;; Returns list of score-* instances.
286   (get-notes* music #t))
288 (define (get-notes* music autobeaming*)
289   ;; Returns list of score-* instances.
290   (let* ((result-list '())
291          (in-slur 0)
292          (autobeaming autobeaming*)
293          (last-note-spec #f))
294     (process-music
295      music
296      (lambda (music)
297        (cond
298         ;; context change
299         ((music-has-property? music 'context-id)
300          (let ((context (ly:music-property music 'context-id))
301                (children (music-elements music)))
302            (add! (make-score-voice #:context (debug "Changing context" context)
303                                              #:elements (append-map (lambda (elt)
304                                                                       (get-notes* elt autobeaming))
305                                                                     children))
306                       result-list))
307          #t)
308         ;; timing change
309         ((music-property? music 'timeSignatureFraction)
310          (let ((value (property-value music)))
311            (debug "Timing change" value)))
312         ;; simultaneous notes
313         ((music-name? music 'SimultaneousMusic)
314          (let ((simultaneous-lists (map (lambda (child)
315                                           (get-notes* child autobeaming))
316                                         (ly:music-property music 'elements))))
317            (debug "Simultaneous lists" simultaneous-lists)
318            (add! (make-score-choice #:lists simultaneous-lists) result-list))
319          #t)
320         ;; repetice
321         ((music-name? music 'VoltaRepeatedMusic)
322          (let ((repeat-count (ly:music-property music 'repeat-count))
323                (children (music-elements music)))
324            (add! (make-score-repetice #:count repeat-count
325                                                 #:elements (append-map
326                                                             (lambda (elt) (get-notes* elt autobeaming))
327                                                             children))
328                       result-list))
329          #t)
330         ;; a note or rest
331         ((or (music-name? music 'EventChord)
332              (music-name? music 'MultiMeasureRestMusic)) ; 2.10
333          (debug "Simple music event" music)
334          (if *tempo-compression*
335              (set! music (ly:music-compress (ly:music-deep-copy music) *tempo-compression*)))
336          (let ((note (find-child-named music 'NoteEvent))
337                (rest (if (music-name? music 'MultiMeasureRestMusic) ; 2.10
338                          music
339                          (or (find-child-named music 'RestEvent)
340                              (find-child-named music 'MultiMeasureRestEvent) ; 2.8
341                              ))))
342            (cond
343             (note
344              (debug "Note" note)
345              (let* ((pitch (ly:music-property note 'pitch))
346                     (duration (* (duration->number (ly:music-property note 'duration)) 4))
347                     (events (filter identity (list
348                                               (find-child-named music 'SlurEvent)
349                                               (find-child-named music 'ManualMelismaEvent)
350                                               (and (not autobeaming)
351                                                    (find-child-named music 'BeamEvent)))))
352                     (slur-start (length (filter (lambda (e) (music-property-value? e 'span-direction -1))
353                                                 events)))
354                     (slur-end (length (filter (lambda (e) (music-property-value? e 'span-direction 1))
355                                               events))))
356                (set! in-slur (+ in-slur slur-start (- slur-end)))
357                (let ((note-spec (make-note #:pitch pitch #:duration duration #:joined in-slur
358                                                 #:origin (ly:music-property note 'origin)))
359                      (last-result (and (not (null? result-list)) (last result-list))))
360                  (set! last-note-spec note-spec)
361                  (if (and last-result
362                           (score-notes? last-result))
363                      (set-score-notes-note/rest-list!
364                       last-result
365                       (append (score-notes-note/rest-list last-result) (list note-spec)))
366                      (add! (make-score-notes #:note/rest-list (list note-spec)) result-list)))))
367             (rest
368              (debug "Rest" rest)
369              (let* ((duration (* (duration->number (ly:music-property rest 'duration)) 4))
370                     (rest-spec (make-rest #:duration duration
371                                                #:origin (ly:music-property rest 'origin)))
372                     (last-result (and (not (null? result-list)) (last result-list))))
373                (if (and last-result
374                         (score-notes? last-result))
375                    (set-score-notes-note/rest-list! last-result
376                                                          (append (score-notes-note/rest-list last-result)
377                                                                  (list rest-spec)))
378                    (add! (make-score-notes #:note/rest-list (list rest-spec)) result-list))))))
379          #f)
380         ;; autobeaming change
381         ((music-property? music 'autoBeaming)
382          (set! autobeaming (property-value music))
383          #t)
384         ;; melisma change
385         ((music-property? music 'melismaBusy) ; 2.10
386          (let ((change (if (property-value music) 1 -1)))
387            (set! in-slur (+ in-slur change))
388            (if last-note-spec
389                (set-note-joined! last-note-spec (+ (note-joined last-note-spec) change)))))
390         ;; tempo change
391         ((music-property? music 'tempoWholesPerMinute)
392          (set! *tempo-compression* (ly:moment-div *default-tempo* (property-value music))))
393         ;; breathe
394         ((music-name? music 'BreathingEvent)
395          (if last-note-spec
396              (let* ((note-duration (note-duration last-note-spec))
397                     (rest-spec (make-rest #:duration (* note-duration (- 1 *breathe-shortage*))
398                                                #:origin (ly:music-property music 'origin))))
399                (set-note-duration! last-note-spec (* note-duration *breathe-shortage*))
400                (add! (make-score-notes #:note/rest-list (list rest-spec)) result-list))
401              (warning music "\\\\breathe without previous note known")))
402         ;; anything else
403         (else
404          #f))))
405     (debug "Raw notes" result-list)))
407 (defstruct verse-block ; lyrics for a given piece of music
408   verse-list
409   (fresh #t) ; if #t, this block hasn't been yet included in the final output
410   )
412 (defstruct parallel-blocks ; several parallel blocks (e.g. stanzas)
413   block-list ; list of verse-blocks
414   )
416 (defstruct sequential-blocks
417   block-list ; list of verse-blocks
418   )
420 (defstruct repeated-blocks
421   block-list ; list of verse-blocks
422   count ; number of repetitions
423   )
425 (defstruct verse ;
426   text ; separate text element (syllable or word)
427   notelist/rests ; list of note lists (slurs) and rests
428   (unfinished #f) ; whether to be merged with the following verse
429   )
431 (define (find-lyrics-score score-list context accept-default)
432   ;; Returns score-* element of context or #f (if there's no such any).
433   (and (not (null? score-list))
434        (or (find-lyrics-score* (car score-list) context accept-default)
435            (find-lyrics-score (cdr score-list) context accept-default))))
437 (define (find-lyrics-score* score context accept-default)
438   (cond
439    ((and (score-voice? score)
440          (equal? (score-voice-context score) context))
441     score)
442    ((score-voice? score)
443     (find-lyrics-score (score-voice-elements score) context #f))
444    ((score-choice? score)
445     (letrec ((lookup (lambda (lists)
446                        (if (null? lists)
447                            #f
448                            (or (find-lyrics-score (car lists) context accept-default)
449                                (lookup (cdr lists)))))))
450       (lookup (score-choice-lists score))))
451    ((score-repetice? score)
452     (if accept-default
453         score
454         (find-lyrics-score (score-repetice-elements score) context accept-default)))
455    ((score-notes? score)
456     (if accept-default
457         score
458         #f))
459    (else
460     (error "Unknown score element" score))))
462 (define (insert-lyrics! lyrics/skip-list score-list context)
463   ;; Add verse-block-lists to score-list.
464   ;; Each processed score-notes instance must receive at most one block in each
465   ;; insert-lyrics! call.  (It can get other blocks if more pieces of
466   ;; lyrics are attached to the same score part.)
467   (let ((lyrics-score-list (find-lyrics-score score-list context #f)))
468     (debug "Lyrics+skip list" lyrics/skip-list)
469     (debug "Corresponding score-* list" score-list)
470     (if lyrics-score-list
471         (insert-lyrics*! lyrics/skip-list (list lyrics-score-list) context)
472         (warning #f "Lyrics context not found: ~a" context))))
474 (define (insert-lyrics*! lyrics/skip-list score-list context)
475   (debug "Processing lyrics" lyrics/skip-list)
476   (debug "Processing score" score-list)
477   (cond
478    ((and (null? lyrics/skip-list)
479          (null? score-list))
480     #f)
481    ((null? lyrics/skip-list)
482     (warning #f "Extra notes: ~a ~a" context score-list))
483    ((null? score-list)
484     (warning #f "Extra lyrics: ~a ~a" context lyrics/skip-list))
485    (else
486     (let* ((lyrics/skip (car lyrics/skip-list))
487            (lyrics-context ((if (lyrics? lyrics/skip) lyrics-context skip-context) lyrics/skip))
488            (score (car score-list)))
489       (cond
490        ((score-voice? score)
491         (let ((new-context (score-voice-context score)))
492           (if (equal? new-context lyrics-context)
493               (insert-lyrics*! lyrics/skip-list
494                                     (append (score-voice-elements score)
495                                             (if (null? (cdr score-list))
496                                                 '()
497                                                 (list (make-score-voice #:context context
498                                                                              #:elements (cdr score-list)))))
499                                     new-context)
500               (insert-lyrics*! lyrics/skip-list (cdr score-list) context))))
501        ((score-choice? score)
502         (let* ((lists* (score-choice-lists score))
503                (lists lists*)
504                (n-assigned (score-choice-n-assigned score))
505                (n 0)
506                (allow-default #f)
507                (score* #f))
508           (while (and (not score*)
509                       (not (null? lists)))
510             (set! score* (find-lyrics-score (car lists) lyrics-context allow-default))
511             (set! lists (cdr lists))
512             (if (not score*)
513                 (set! n (+ n 1)))
514             (if (and (null? lists)
515                      (not allow-default)
516                      (equal? lyrics-context context))
517                 (begin
518                   (set! allow-default #t)
519                   (set! n 0)
520                   (set! lists (score-choice-lists score)))))
521           (debug "Selected score" score*)
522           (if (and score*
523                    (>= n n-assigned))
524               (begin
525                 (if (> n n-assigned)
526                     (receive (assigned-elts unassigned-elts) (split-at lists* n-assigned)
527                       (set-score-choice-lists! score (append assigned-elts
528                                                                   (list (list-ref lists* n))
529                                                                   (take unassigned-elts (- n n-assigned))
530                                                                   lists))))
531                 (set-score-choice-n-assigned! score (+ n-assigned 1))))
532           (insert-lyrics*! lyrics/skip-list (append (if score* (list score*) '()) (cdr score-list)) context)))
533        ((score-repetice? score)
534         (insert-lyrics*! lyrics/skip-list
535                               (append (score-repetice-elements score) (cdr score-list)) context))
536        ((score-notes? score)
537         ;; This is the only part which actually attaches the processed lyrics.
538         ;; The subsequent calls return verses which we collect into a verse block.
539         ;; We add the block to the score element.
540         (if (equal? lyrics-context context)
541             (set! lyrics/skip-list (really-insert-lyrics! lyrics/skip-list score context)))
542         (insert-lyrics*! lyrics/skip-list (cdr score-list) context))
543        (else
544         (error "Unknown score element in lyrics processing" score)))))))
546 (define (really-insert-lyrics! lyrics/skip-list score context)
547   ;; Return new lyrics/skip-list.
548   ;; Score is modified by side effect.
549   (debug "Assigning notes" score)
550   (let ((note-list (score-notes-note/rest-list score))
551         (unfinished-verse #f)
552         (verse-list '()))
553     (while (not (null? note-list))
554       (if (null? lyrics/skip-list)
555           (let ((final-rests '()))
556             (while (and (not (null? note-list))
557                         (rest? (car note-list)))
558               (push! (car note-list) final-rests)
559               (set! note-list (cdr note-list)))
560             (if (not (null? final-rests))
561                 (set! verse-list (append verse-list
562                                          (list (make-verse #:text ""
563                                                                 #:notelist/rests (reverse! final-rests))))))
564             (if (not (null? note-list))
565                 (begin
566                   (warning (car note-list) "Missing lyrics: ~a ~a" context note-list)
567                   (set! note-list '()))))
568           (let ((lyrics/skip (car lyrics/skip-list)))
569             (receive (notelist/rest note-list*) (if (lyrics? lyrics/skip)
570                                                     (consume-lyrics-notes lyrics/skip note-list context)
571                                                     (consume-skip-notes lyrics/skip note-list context))
572               (debug "Consumed notes" (list lyrics/skip notelist/rest))
573               (set! note-list note-list*)
574               (cond
575                ((null? notelist/rest)
576                 #f)
577                ;; Lyrics
578                ((and (lyrics? lyrics/skip)
579                      unfinished-verse)
580                 (set-verse-text!
581                  unfinished-verse
582                  (string-append (verse-text unfinished-verse) (lyrics-text lyrics/skip)))
583                 (set-verse-notelist/rests!
584                  unfinished-verse
585                  (append (verse-notelist/rests unfinished-verse) (list notelist/rest)))
586                 (if (not (lyrics-unfinished lyrics/skip))
587                     (set! unfinished-verse #f)))
588                ((lyrics? lyrics/skip)
589                 (let ((verse (make-verse #:text (if (rest? notelist/rest)
590                                                          ""
591                                                          (lyrics-text lyrics/skip))
592                                               #:notelist/rests (list notelist/rest))))
593                   (add! verse verse-list)
594                   (set! unfinished-verse (if (lyrics-unfinished lyrics/skip) verse #f))))
595                ;; Skip
596                ((skip? lyrics/skip)
597                 (cond
598                  ((rest? notelist/rest)
599                   (if (null? verse-list)
600                       (set! verse-list (list (make-verse #:text ""
601                                                               #:notelist/rests (list notelist/rest))))
602                       (let ((last-verse (last verse-list)))
603                         (set-verse-notelist/rests!
604                          last-verse
605                          (append (verse-notelist/rests last-verse) (list notelist/rest))))))
606                  ((pair? notelist/rest)
607                   (add! (make-verse #:text *skip-word* #:notelist/rests (list notelist/rest))
608                              verse-list))
609                  (else
610                   (error "Unreachable branch reached")))
611                 (set! unfinished-verse #f)))
612               (if (not (rest? notelist/rest))
613                   (set! lyrics/skip-list (cdr lyrics/skip-list)))))))
614     (if unfinished-verse
615         (set-verse-unfinished! unfinished-verse #t))
616     (set-score-notes-verse-block-list!
617      score
618      (append (score-notes-verse-block-list score)
619              (list (make-verse-block #:verse-list verse-list)))))
620   lyrics/skip-list)
622 (define (consume-lyrics-notes lyrics note-list context)
623   ;; Returns list of note instances + new note-list.
624   (assert (lyrics? lyrics))
625   (if (and (not (null? note-list))
626            (rest? (car note-list)))
627       (values (car note-list) (cdr note-list))
628       (let ((ignore-melismata (lyrics-ignore-melismata lyrics))
629             (join #t)
630             (consumed '()))
631         (while (and join
632                     (not (null? note-list)))
633           (let ((note (car note-list)))
634             (push! note consumed)
635             (let ((note-slur (note-joined note)))
636               (if (< note-slur 0)
637                   (warning note "Slur underrun"))
638               (set! join (and (not ignore-melismata) (> note-slur 0)))))
639           (set! note-list (cdr note-list)))
640         (if join
641             (warning (safe-car (if (null? note-list) consumed note-list))
642                      "Unfinished slur: ~a ~a" context consumed))
643         (values (reverse consumed) note-list))))
645 (define (consume-skip-notes skip note-list context)
646   ;; Returns either note list (skip word defined) or rest instance (no skip word) + new note-list.
647   (assert (skip? skip))
648   (let ((duration (skip-duration skip))
649         (epsilon 0.001)
650         (consumed '()))
651     (while (and (> duration epsilon)
652                 (not (null? note-list)))
653       (let ((note (car note-list)))
654         (assert (note? note))
655         (push! note consumed)
656         (set! duration (- duration (note-duration note))))
657       (set! note-list (cdr note-list)))
658     (set! consumed (reverse! consumed))
659     (cond
660      ((> duration epsilon)
661       (warning (if (null? note-list) (safe-last consumed) (safe-car note-list))
662                     "Excessive skip: ~a ~a ~a ~a" context skip duration consumed))
663      ((< duration (- epsilon))
664       (warning (if (null? note-list) (safe-last consumed) (safe-car note-list))
665                     "Skip misalignment: ~a ~a ~a ~a" context skip duration consumed)))
666     (values (if *skip-word*
667                 consumed
668                 '())
669             note-list)))
671 (define (extract-verse-blocks score)
672   ;; Returns list of blocks and parallel blocks.
673   (debug "Extracting verse blocks" score)
674   (cond
675    ((score-voice? score)
676     (append-map extract-verse-blocks (score-voice-elements score)))
677    ((score-choice? score)
678     (list (make-parallel-blocks
679            #:block-list (map (lambda (block-list)
680                                (make-sequential-blocks
681                                 #:block-list (append-map extract-verse-blocks block-list)))
682                              (score-choice-lists score)))))
683    ((score-repetice? score)
684     (list (make-repeated-blocks #:count (score-repetice-count score)
685                                      #:block-list (append-map extract-verse-blocks
686                                                               (score-repetice-elements score)))))
687    ((score-notes? score)
688     (list (make-parallel-blocks #:block-list (score-notes-verse-block-list score))))
689    (else
690     (error "Invalid score element" score))))
692 (define (extract-verses score-list)
693   ;; Returns (final) list of verses.
694   ;; The primary purpose of this routine is to build complete stanzas from
695   ;; lists of verse blocks.
696   ;; Extract verse-blocks and process them until no unprocessed stanzas remain.
697   (debug "Final score list" score-list)
698   (let ((verse-block-list (debug "Verse blocks" (append-map extract-verse-blocks score-list))))
699     (letrec ((combine (lambda (lst-1 lst-2)
700                          (debug "Combining lists" (list lst-1 lst-2))
701                          (if (null? lst-2)
702                              lst-1
703                              (let ((diff (- (length lst-1) (length lst-2))))
704                                (if (< diff 0)
705                                    (let ((last-elt (last lst-1)))
706                                      (while (< diff 0)
707                                        (add! last-elt lst-1)
708                                        (set! diff (+ diff 1))))
709                                    (let ((last-elt (last lst-2)))
710                                      (while (> diff 0)
711                                        (add! last-elt lst-2)
712                                        (set! diff (- diff 1)))))
713                                (debug "Combined" (map append lst-1 lst-2))))))
714              (expand* (lambda (block)
715                         (cond
716                          ((parallel-blocks? block)
717                           (append-map (lambda (block) (expand (list block)))
718                                       (parallel-blocks-block-list block)))
719                          ((sequential-blocks? block)
720                           (expand (sequential-blocks-block-list block)))
721                          ((repeated-blocks? block)
722                           ;; Only simple repetice without nested parallel sections is supported.
723                           (let ((count (repeated-blocks-count block))
724                                 (expanded (expand (repeated-blocks-block-list block)))
725                                 (expanded* '()))
726                             (while (not (null? expanded))
727                               (let ((count* count)
728                                     (item '()))
729                                 (while (and (> count* 0) (not (null? expanded)))
730                                   (set! item (append item (car expanded)))
731                                   (set! expanded (cdr expanded))
732                                   (set! count* (- count* 1)))
733                                 (push! item expanded*)))
734                             (reverse expanded*)))
735                          (else
736                           (list (list block))))))
737              (expand (lambda (block-list)
738                        (debug "Expanding list" block-list)
739                        (if (null? block-list)
740                            '()
741                            (debug "Expanded" (combine (expand* (car block-list))
742                                                            (expand (cdr block-list)))))))
743              (merge (lambda (verse-list)
744                       (cond
745                        ((null? verse-list)
746                         '())
747                        ((verse-unfinished (car verse-list))
748                         (let ((verse-1 (first verse-list))
749                               (verse-2 (second verse-list)))
750                           (merge (cons (make-verse #:text (string-append (verse-text verse-1)
751                                                                               (verse-text verse-2))
752                                                         #:notelist/rests (append (verse-notelist/rests verse-1)
753                                                                                  (verse-notelist/rests verse-2))
754                                                         #:unfinished (verse-unfinished verse-2))
755                                        (cddr verse-list)))))
756                        (else
757                         (cons (car verse-list) (merge (cdr verse-list))))))))
758       (debug "Final verses" (merge (append-map (lambda (lst) (append-map verse-block-verse-list lst))
759                                                     (expand verse-block-list)))))))
761 (define (handle-music music)
762   ;; Returns list of verses.
763   ;; The main analysis function.
764   (if *debug*
765       (display-scheme-music music))
766   (let ((score-list (debug "Final raw notes" (get-notes music)))
767         (music-context-list (collect-lyrics-music music)))
768     (for-each (lambda (music-context)
769                 (let ((context (music-context-context music-context)))
770                   (set! *tempo-compression* #f)
771                   (insert-lyrics! (get-lyrics (music-context-music music-context) context)
772                                   score-list context)
773                   (debug "Final score list" score-list)))
774               music-context-list)
775     (extract-verses score-list)))
778 ;;; Output
781 (define festival-note-mapping '((0 "C") (1 "C#") (2 "D") (3 "D#") (4 "E") (5 "F") (6 "F#")
782                                      (7 "G") (8 "G#") (9 "A") (10 "A#") (11 "B")))
783 (define (festival-pitch pitch)
784   (let* ((semitones (ly:pitch-semitones pitch))
785          (octave (inexact->exact (floor (/ semitones 12))))
786          (tone (modulo semitones 12)))
787     (format #f "~a~a" (car (assoc-get tone festival-note-mapping))
788             (+ octave *base-octave* *base-octave-shift*))))
790 (define (write-header port tempo)
791   (let ((beats (or (tempo->beats tempo) 100)))
792     (format port "<?xml version=\"1.0\"?>
793 <!DOCTYPE SINGING PUBLIC \"-//SINGING//DTD SINGING mark up//EN\" \"Singing.v0_1.dtd\" []>
794 <SINGING BPM=\"~d\">
795 " beats)))
797 (define (write-footer port)
798   (format port "</SINGING>~%"))
800 (define (write-lyrics port music)
801   (let ((rest-dur 0))
802     (for-each (lambda (verse)
803                 (let ((text (verse-text verse))
804                       (note/rest-list (verse-notelist/rests verse)))
805                   (receive (rest-list note-listlist) (partition rest? note/rest-list)
806                     (debug "Rest list" rest-list)
807                     (debug "Note list" note-listlist)
808                     (if (not (null? rest-list))
809                         (set! rest-dur (+ rest-dur (apply + (map rest-duration rest-list)))))
810                     (if (not (null? note-listlist))
811                         (begin
812                           (if (> rest-dur 0)
813                               (begin
814                                 (write-rest-element port rest-dur)
815                                 (set! rest-dur 0)))
816                           (write-lyrics-element port text note-listlist))))))
817               (handle-music music))
818     (if (> rest-dur 0)
819         (write-rest-element port rest-dur))))
821 (define (write-lyrics-element port text slur-list)
822   (let ((fmt "~{~{~a~^+~}~^,~}")
823         (transform (lambda (function)
824                      (map (lambda (slur)
825                             (let ((rests (filter rest? slur)))
826                               (if (not (null? rests))
827                                   (begin
828                                     (warning (car rests) "Rests in a slur: ~a" slur)
829                                     (set! slur (remove rest? slur)))))
830                             (map function slur))
831                           slur-list))))
832     (format port "<DURATION BEATS=\"~@?\"><PITCH NOTE=\"~@?\">~a</PITCH></DURATION>~%"
833             fmt (transform note-duration)
834             fmt (transform (compose festival-pitch note-pitch))
835             text)))
837 (define (write-rest-element port duration)
838   (format port "<REST BEATS=\"~a\"></REST>~%" duration))