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