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