]> git.donarmstrong.com Git - lilypond.git/blob - scm/part-combiner.scm
Issue 913: improve \partcombine when parts have unequal lengths
[lilypond.git] / scm / part-combiner.scm
1 ;;;; This file is part of LilyPond, the GNU music typesetter.
2 ;;;;
3 ;;;; Copyright (C) 2004--2015 Han-Wen Nienhuys <hanwen@xs4all.nl>
4 ;;;;
5 ;;;; LilyPond is free software: you can redistribute it and/or modify
6 ;;;; it under the terms of the GNU General Public License as published by
7 ;;;; the Free Software Foundation, either version 3 of the License, or
8 ;;;; (at your option) any later version.
9 ;;;;
10 ;;;; LilyPond is distributed in the hope that it will be useful,
11 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 ;;;; GNU General Public License for more details.
14 ;;;;
15 ;;;; You should have received a copy of the GNU General Public License
16 ;;;; along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
17
18 ;; todo: figure out how to make module,
19 ;; without breaking nested ly scopes
20
21 (define-class <Voice-state> ()
22   (event-list #:init-value '() #:accessor events #:init-keyword #:events)
23   (when-moment #:accessor moment #:init-keyword #:moment)
24   (tuning #:accessor tuning #:init-keyword #:tuning)
25   (split-index #:accessor split-index)
26   (vector-index)
27   (state-vector)
28   ;;;
29   ;; spanner-state is an alist
30   ;; of (SYMBOL . RESULT-INDEX), which indicates where
31   ;; said spanner was started.
32   (spanner-state #:init-value '() #:accessor span-state))
33
34 (define-method (write (x <Voice-state> ) file)
35   (display (moment x) file)
36   (display " evs = " file)
37   (display (events x) file)
38   (display " active = " file)
39   (display (span-state x) file)
40   (display "\n" file))
41
42 ;; Return the duration of the longest event in the Voice-state.
43 (define-method (duration (vs <Voice-state>))
44   (define (duration-max event d1)
45     (let ((d2 (ly:event-property event 'duration #f)))
46       (if d2
47           (if (ly:duration<? d1 d2) d2 d1)
48           d1)))
49
50   (fold duration-max (ly:make-duration 0 0 0) (events vs)))
51
52 ;; Return the moment that the longest event in the Voice-state ends.
53 (define-method (end-moment (vs <Voice-state>))
54   (ly:moment-add (moment vs) (ly:duration-length (duration vs))))
55
56 (define-method (note-events (vs <Voice-state>))
57   (define (f? x)
58     (ly:in-event-class? x 'note-event))
59   (filter f? (events vs)))
60
61 ; Return a list of note events which is sorted and stripped of
62 ; properties that we do not want to prevent combining parts.
63 (define-method (comparable-note-events (vs <Voice-state>))
64   (define (note<? note1 note2)
65     (let ((p1 (ly:event-property note1 'pitch))
66           (p2 (ly:event-property note2 'pitch)))
67       (cond ((ly:pitch<? p1 p2) #t)
68             ((ly:pitch<? p2 p1) #f)
69             (else (ly:duration<? (ly:event-property note1 'duration)
70                                  (ly:event-property note2 'duration))))))
71   ;; TODO we probably should compare articulations too
72   (sort (map (lambda (x)
73                (ly:make-stream-event
74                 (ly:make-event-class 'note-event)
75                 (list (cons 'duration (ly:event-property x 'duration))
76                       (cons 'pitch (ly:event-property x 'pitch)))))
77              (note-events vs))
78         note<?))
79
80 (define-method (rest-or-skip-events (vs <Voice-state>))
81   (define (filtered-events event-class)
82     (filter (lambda(x) (ly:in-event-class? x event-class))
83             (events vs)))
84   (let ((result (filtered-events 'rest-event)))
85     ;; There may be skips in the same part with rests for various
86     ;; reasons.  Regard the skips only if there are no rests.
87     (if (and (not (pair? result)) (not (any-mmrest-events vs)))
88         (set! result (filtered-events 'skip-event)))
89   result))
90
91 (define-method (any-mmrest-events (vs <Voice-state>))
92   (define (f? x)
93     (ly:in-event-class? x 'multi-measure-rest-event))
94   (any f? (events vs)))
95
96 (define-method (previous-voice-state (vs <Voice-state>))
97   (let ((i (slot-ref vs 'vector-index))
98         (v (slot-ref vs 'state-vector)))
99     (if (< 0 i)
100         (vector-ref v (1- i))
101         #f)))
102
103 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
104
105 (define-class <Split-state> ()
106   ;; The automatically determined split configuration
107   (configuration #:init-value '() #:accessor configuration)
108   ;; Allow overriding split configuration, takes precedence over configuration
109   (forced-configuration #:init-value #f #:accessor forced-configuration)
110   (when-moment #:accessor moment #:init-keyword #:moment)
111   ;; voice-states are states starting with the Split-state or later
112   ;;
113   (is #:init-keyword #:voice-states #:accessor voice-states)
114   (synced  #:init-keyword #:synced #:init-value  #f #:getter synced?))
115
116
117 (define-method (write (x <Split-state> ) f)
118   (display (moment x) f)
119   (display " = " f)
120   (display (configuration x) f)
121   (if (synced? x)
122       (display " synced "))
123   (display "\n" f))
124
125 (define-method (current-or-previous-voice-states (ss <Split-state>))
126   "Return voice states meeting the following conditions.  For a voice
127 in sync, return the current voice state.  For a voice out of sync,
128 return the previous voice state."
129   (let* ((vss (voice-states ss))
130          (vs1 (car vss))
131          (vs2 (cdr vss)))
132     (if (and vs1 (not (equal? (moment vs1) (moment ss))))
133         (set! vs1 (previous-voice-state vs1)))
134     (if (and vs2 (not (equal? (moment vs2) (moment ss))))
135         (set! vs2 (previous-voice-state vs2)))
136     (cons vs1 vs2)))
137
138 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
139
140
141 (define (previous-span-state vs)
142   (let ((p (previous-voice-state vs)))
143     (if p (span-state p) '())))
144
145 (define (make-voice-states evl)
146   (let* ((states (map (lambda (v)
147                         (make <Voice-state>
148                           #:moment (caar v)
149                           #:tuning (cdar v)
150                           #:events (map car (cdr v))))
151                       (reverse evl))))
152
153     ;; add an entry with no events at the moment the last event ends
154     (if (pair? states)
155         (let ((last-real-event (car states)))
156           (set! states
157                 (cons (make <Voice-state>
158                         #:moment (end-moment last-real-event)
159                         #:tuning (tuning last-real-event)
160                         #:events '())
161                       states))))
162
163     ;; TODO: Add an entry at +inf.0 and see if it allows us to remove
164     ;; the many instances of conditional code handling the case that
165     ;; there is no voice state at a given moment.
166
167     (let ((vec (list->vector (reverse! states))))
168       (do ((i 0 (1+ i)))
169           ((= i (vector-length vec)) vec)
170         (slot-set! (vector-ref vec i) 'vector-index i)
171         (slot-set! (vector-ref vec i) 'state-vector vec)))))
172
173 (define (make-split-state vs1 vs2)
174   "Merge lists VS1 and VS2, containing Voice-state objects into vector
175 of Split-state objects, crosslinking the Split-state vector and
176 Voice-state objects
177 "
178   (define (helper ss-idx ss-list idx1 idx2)
179     (let* ((state1 (if (< idx1 (vector-length vs1)) (vector-ref vs1 idx1) #f))
180            (state2 (if (< idx2 (vector-length vs2)) (vector-ref vs2 idx2) #f))
181            (min (cond ((and state1 state2) (moment-min (moment state1) (moment state2)))
182                       (state1 (moment state1))
183                       (state2 (moment state2))
184                       (else #f)))
185            (inc1 (if (and state1 (equal? min (moment state1))) 1 0))
186            (inc2 (if (and state2 (equal? min (moment state2))) 1 0))
187            (ss-object (if min
188                           (make <Split-state>
189                             #:moment min
190                             #:voice-states (cons state1 state2)
191                             #:synced (= inc1 inc2))
192                           #f)))
193       (if state1
194           (set! (split-index state1) ss-idx))
195       (if state2
196           (set! (split-index state2) ss-idx))
197       (if min
198           (helper (1+ ss-idx)
199                   (cons ss-object ss-list)
200                   (+ idx1 inc1)
201                   (+ idx2 inc2))
202           ss-list)))
203   (list->vector (reverse! (helper 0 '() 0  0) '())))
204
205 (define (analyse-spanner-states voice-state-vec)
206
207   (define (helper index active)
208     "Analyse EVS at INDEX, given state ACTIVE."
209
210     (define (analyse-tie-start active ev)
211       (if (ly:in-event-class? ev 'tie-event)
212           (acons 'tie (split-index (vector-ref voice-state-vec index))
213                  active)
214           active))
215
216     (define (analyse-tie-end active ev)
217       (if (ly:in-event-class? ev 'note-event)
218           (assoc-remove! active 'tie)
219           active))
220
221     (define (analyse-absdyn-end active ev)
222       (if (or (ly:in-event-class? ev 'absolute-dynamic-event)
223               (and (ly:in-event-class? ev 'span-dynamic-event)
224                    (equal? STOP (ly:event-property ev 'span-direction))))
225           (assoc-remove! (assoc-remove! active 'cresc) 'decr)
226           active))
227
228     (define (active<? a b)
229       (cond ((symbol<? (car a) (car b)) #t)
230             ((symbol<? (car b) (car a)) #f)
231             (else (< (cdr a) (cdr b)))))
232
233     (define (analyse-span-event active ev)
234       (let* ((name (car (ly:event-property ev 'class)))
235              (key (cond ((equal? name 'slur-event) 'slur)
236                         ((equal? name 'phrasing-slur-event) 'tie)
237                         ((equal? name 'beam-event) 'beam)
238                         ((equal? name 'crescendo-event) 'cresc)
239                         ((equal? name 'decrescendo-event) 'decr)
240                         (else #f)))
241              (sp (ly:event-property ev 'span-direction)))
242         (if (and (symbol? key) (ly:dir? sp))
243             (if (= sp STOP)
244                 (assoc-remove! active key)
245                 (acons key
246                        (split-index (vector-ref voice-state-vec index))
247                        active))
248             active)))
249
250     (define (analyse-events active evs)
251       "Run all analyzers on ACTIVE and EVS"
252       (define (run-analyzer analyzer active evs)
253         (if (pair? evs)
254             (run-analyzer analyzer (analyzer active (car evs)) (cdr evs))
255             active))
256       (define (run-analyzers analyzers active evs)
257         (if (pair? analyzers)
258             (run-analyzers (cdr analyzers)
259                            (run-analyzer (car analyzers) active evs)
260                            evs)
261             active))
262       (sort ;; todo: use fold or somesuch.
263        (run-analyzers (list analyse-absdyn-end analyse-span-event
264                             ;; note: tie-start/span comes after tie-end/absdyn.
265                             analyse-tie-end analyse-tie-start)
266                       active evs)
267        active<?))
268
269     ;; must copy, since we use assoc-remove!
270     (if (< index (vector-length voice-state-vec))
271         (begin
272           (set! active (analyse-events active (events (vector-ref voice-state-vec index))))
273           (set! (span-state (vector-ref voice-state-vec index))
274                 (list-copy active))
275           (helper (1+ index) active))))
276
277   (helper 0 '()))
278
279 (define recording-group-functions
280   ;;Selected parts from @var{toplevel-music-functions} not requiring @code{parser}.
281   (list
282    (lambda (music) (expand-repeat-chords! '(rhythmic-event) music))
283    expand-repeat-notes!))
284
285
286 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
287 (define-public (recording-group-emulate music odef)
288   "Interpret @var{music} according to @var{odef}, but store all events
289 in a chronological list, similar to the @code{Recording_group_engraver} in
290 LilyPond version 2.8 and earlier."
291   (let*
292       ((context-list '())
293        (now-mom (ly:make-moment 0 0))
294        (global (ly:make-global-context odef))
295        (mom-listener (lambda (tev) (set! now-mom (ly:event-property tev 'moment))))
296        (new-context-listener
297         (lambda (sev)
298           (let*
299               ((child (ly:event-property sev 'context))
300                (this-moment-list (cons (ly:context-id child) '()))
301                (dummy (set! context-list (cons this-moment-list context-list)))
302                (acc '())
303                (accumulate-event-listener
304                 (lambda (ev)
305                   (set! acc (cons (cons ev #t) acc))))
306                (save-acc-listener
307                 (lambda (tev)
308                   (if (pair? acc)
309                       (let ((this-moment
310                              (cons (cons now-mom
311                                          (ly:context-property child 'instrumentTransposition))
312                                    ;; The accumulate-event-listener above creates
313                                    ;; the list of events in reverse order, so we
314                                    ;; have to revert it to the original order again
315                                    (reverse acc))))
316                         (set-cdr! this-moment-list
317                                   (cons this-moment (cdr this-moment-list)))
318                         (set! acc '()))))))
319             (ly:add-listener accumulate-event-listener
320                              (ly:context-event-source child) 'StreamEvent)
321             (ly:add-listener save-acc-listener
322                              (ly:context-event-source global) 'OneTimeStep)))))
323     (ly:add-listener new-context-listener
324                      (ly:context-events-below global) 'AnnounceNewContext)
325     (ly:add-listener mom-listener (ly:context-event-source global) 'Prepare)
326     (ly:interpret-music-expression
327      (make-non-relative-music
328       (fold (lambda (x m) (x m)) music recording-group-functions))
329      global)
330     context-list))
331
332 (define-public (determine-split-list evl1 evl2 chord-range)
333   "@var{evl1} and @var{evl2} should be ascending. @var{chord-range} is a pair of numbers (min . max) defining the distance in steps between notes that may be combined into a chord or unison."
334   (let* ((pc-debug #f)
335          (voice-state-vec1 (make-voice-states evl1))
336          (voice-state-vec2 (make-voice-states evl2))
337          (result (make-split-state voice-state-vec1 voice-state-vec2))
338          (chord-min-diff (car chord-range))
339          (chord-max-diff (cdr chord-range)))
340
341     ;; Go through all moments recursively and check if the events of that
342     ;; moment contain a part-combine-force-event override. If so, store its
343     ;; value in the forced-configuration field, which will override. The
344     ;; previous configuration is used to determine non-terminated settings.
345     (define (analyse-forced-combine result-idx prev-res)
346
347       (define (get-forced-event x)
348         (and (ly:in-event-class? x 'part-combine-force-event)
349              (cons (ly:event-property x 'forced-type)
350                    (ly:event-property x 'once))))
351       (define (part-combine-events vs)
352         (if (not vs)
353             '()
354             (filter-map get-forced-event (events vs))))
355       ;; end part-combine-events
356
357       ;; forced-result: Take the previous config and analyse whether
358       ;; any change happened.... Return new once and permanent config
359       (define (forced-result evt state)
360         ;; sanity check, evt should always be (new-state . once)
361         (if (not (and (pair? evt) (pair? state)))
362             state
363             (if (cdr evt)
364                 ;; Once-event, leave permanent state unchanged
365                 (cons (car evt) (cdr state))
366                 ;; permanent change, leave once state unchanged
367                 (cons (car state) (car evt)))))
368       ;; end forced-combine-result
369
370       ;; body of analyse-forced-combine:
371       (if (< result-idx (vector-length result))
372           (let* ((now-state (vector-ref result result-idx)) ; current result
373                  ;; Extract all part-combine force events
374                  (evts (if (synced? now-state)
375                            (append
376                             (part-combine-events (car (voice-states now-state)))
377                             (part-combine-events (cdr (voice-states now-state))))
378                            '()))
379                  ;; result is (once-state permament-state):
380                  (state (fold forced-result (cons 'automatic prev-res) evts))
381                  ;; Now let once override permanent changes:
382                  (force-state (if (equal? (car state) 'automatic)
383                                   (cdr state)
384                                   (car state))))
385             (set! (forced-configuration (vector-ref result result-idx))
386                   force-state)
387             ;; For the next moment, ignore the once override (car stat)
388             ;; and pass on the permanent override, stored as (cdr state)
389             (analyse-forced-combine (1+ result-idx) (cdr state)))))
390     ;; end analyse-forced-combine
391
392
393     (define (analyse-time-step result-idx)
394       (define (put x . index)
395         "Put the result to X, starting from INDEX backwards.
396
397 Only set if not set previously.
398 "
399         (let ((i (if (pair? index) (car index) result-idx)))
400           (if (and (<= 0 i)
401                    (not (symbol? (configuration (vector-ref result i)))))
402               (begin
403                 (set! (configuration (vector-ref result i)) x)
404                 (put x (1- i))))))
405
406       (define (copy-state-from state-vec vs)
407         (define (copy-one-state key-idx)
408           (let* ((idx (cdr key-idx))
409                  (prev-ss (vector-ref result idx))
410                  (prev (configuration prev-ss)))
411             (if (symbol? prev)
412                 (put prev))))
413         (for-each copy-one-state (span-state vs)))
414
415       (define (analyse-notes now-state)
416         (let* ((vs1 (car (voice-states now-state)))
417                (vs2 (cdr (voice-states now-state)))
418                (notes1 (comparable-note-events vs1))
419                (notes2 (comparable-note-events vs2)))
420           (cond
421            ;; if neither part has notes, do nothing
422            ((and (not (pair? notes1)) (not (pair? notes2))))
423
424            ;; if one part has notes and the other does not
425            ((or (not (pair? notes1)) (not (pair? notes2))) (put 'apart))
426
427            ;; if either part has a chord
428            ((or (> (length notes1) 1) 
429                 (> (length notes2) 1))
430             (if (and (<= chord-min-diff 0) ; user requests combined unisons
431                      (equal? notes1 notes2)) ; both parts have the same chord
432                 (put 'chords)
433                 (put 'apart)))
434
435            ;; if the durations are different
436            ;; TODO articulations too?
437            ((and (not (equal? (ly:event-property (car notes1) 'duration)
438                               (ly:event-property (car notes2) 'duration))))
439             (put 'apart))
440
441            (else
442             ;; Is the interval outside of chord-range?
443             (if (let ((diff (ly:pitch-steps
444                              (ly:pitch-diff 
445                               (ly:event-property (car notes1) 'pitch)
446                               (ly:event-property (car notes2) 'pitch)))))
447                   (or (< diff chord-min-diff)
448                       (> diff chord-max-diff)
449                       ))
450                 (put 'apart)
451                 ;; copy previous split state from spanner state
452                 (begin
453                   (if (previous-voice-state vs1)
454                       (copy-state-from voice-state-vec1
455                                        (previous-voice-state vs1)))
456                   (if (previous-voice-state vs2)
457                       (copy-state-from voice-state-vec2
458                                        (previous-voice-state vs2)))
459                   (if (and (null? (span-state vs1)) (null? (span-state vs2)))
460                       (put 'chords))))))))
461
462       (if (< result-idx (vector-length result))
463           (let* ((now-state (vector-ref result result-idx))
464                  (vs1 (car (voice-states now-state)))
465                  (vs2 (cdr (voice-states now-state))))
466
467             (cond ((not vs1) (put 'apart))
468                   ((not vs2) (put 'apart))
469                   (else
470                    (let ((active1 (previous-span-state vs1))
471                          (active2 (previous-span-state vs2))
472                          (new-active1 (span-state vs1))
473                          (new-active2 (span-state vs2)))
474                      (if #f ; debug
475                          (display (list (moment now-state) result-idx
476                                         active1 "->" new-active1
477                                         active2 "->" new-active2
478                                         "\n")))
479                      (if (and (synced? now-state)
480                               (equal? active1 active2)
481                               (equal? new-active1 new-active2))
482                          (analyse-notes now-state)
483
484                          ;; active states different:
485                          (put 'apart)))
486
487                    ;; go to the next one, if it exists.
488                    (analyse-time-step (1+ result-idx)))))))
489
490     (define (analyse-a2 result-idx)
491       (if (< result-idx (vector-length result))
492           (let* ((now-state (vector-ref result result-idx))
493                  (vs1 (car (voice-states now-state)))
494                  (vs2 (cdr (voice-states now-state))))
495
496             (define (analyse-synced-silence)
497               (let ((rests1 (if vs1 (rest-or-skip-events vs1) '()))
498                     (rests2 (if vs2 (rest-or-skip-events vs2) '())))
499                 (cond
500
501                  ;; multi-measure rests (probably), which the
502                  ;; part-combine iterator handles well
503                  ((and (= 0 (length rests1))
504                        (= 0 (length rests2)))
505                   (set! (configuration now-state) 'unisilence))
506
507                  ;; equal rests or equal skips, but not one of each
508                  ((and (= 1 (length rests1))
509                        (= 1 (length rests2))
510                        (equal? (ly:event-property (car rests1) 'class)
511                                (ly:event-property (car rests2) 'class))
512                        (equal? (ly:event-property (car rests1) 'duration)
513                                (ly:event-property (car rests2) 'duration)))
514                   (set! (configuration now-state) 'unisilence))
515
516                  ;; rests of different durations or mixed with
517                  ;; skips or multi-measure rests
518                  (else
519                   ;; TODO For skips, route the rest to the shared
520                   ;; voice and the skip to the voice for its part?
521                   (set! (configuration now-state) 'apart-silence))
522
523                  )))
524
525             (define (analyse-unsynced-silence vs1 vs2)
526               (let ((any-mmrests1 (if vs1 (any-mmrest-events vs1) #f))
527                     (any-mmrests2 (if vs2 (any-mmrest-events vs2) #f)))
528                 (cond
529                  ;; If a multi-measure rest begins now while the other
530                  ;; part has an ongoing multi-measure rest (or has
531                  ;; ended), start displaying the one that begins now.
532                  ((and any-mmrests1
533                        (equal? (moment vs1) (moment now-state))
534                        (or (not vs2) any-mmrests2))
535                   (set! (configuration now-state) 'silence1))
536
537                  ;; as above with parts swapped
538                  ((and any-mmrests2
539                        (equal? (moment vs2) (moment now-state))
540                        (or (not vs1) any-mmrests1))
541                   (set! (configuration now-state) 'silence2))
542                  )))
543
544             (if (or vs1 vs2)
545                 (let ((notes1 (if vs1 (comparable-note-events vs1) '()))
546                       (notes2 (if vs2 (comparable-note-events vs2) '())))
547                   (cond ((and (equal? (configuration now-state) 'chords)
548                               (pair? notes1)
549                               (equal? notes1 notes2))
550                          (set! (configuration now-state) 'unisono))
551
552                         ((synced? now-state)
553                          (if (and (= 0 (length notes1))
554                                   (= 0 (length notes2)))
555                              (analyse-synced-silence)))
556
557                         (else ;; not synchronized
558                          (let* ((vss
559                                  (current-or-previous-voice-states now-state))
560                                 (vs1 (car vss))
561                                 (vs2 (cdr vss)))
562                            (if (and
563                                 (or (not vs1) (= 0 (length (note-events vs1))))
564                                 (or (not vs2) (= 0 (length (note-events vs2)))))
565                                (analyse-unsynced-silence vs1 vs2))))
566                         )))
567             (analyse-a2 (1+ result-idx)))))
568
569     (define (analyse-solo12 result-idx)
570
571       (define (previous-config vs)
572         (let* ((pvs (previous-voice-state vs))
573                (spi (if pvs (split-index pvs) #f))
574                (prev-split (if spi (vector-ref result spi) #f)))
575           (if prev-split
576               (configuration prev-split)
577               'apart)))
578
579       (define (put-range x a b)
580         ;; (display (list "put range "  x a b "\n"))
581         (do ((i a (1+ i)))
582             ((> i b) b)
583           (set! (configuration (vector-ref result i)) x)))
584
585       (define (put x)
586         ;; (display (list "putting "  x "\n"))
587         (set! (configuration (vector-ref result result-idx)) x))
588
589       (define (current-voice-state now-state voice-num)
590         (define vs ((if (= 1 voice-num) car cdr)
591                     (voice-states now-state)))
592         (if (or (not vs) (equal? (moment now-state) (moment vs)))
593             vs
594             (previous-voice-state vs)))
595
596       (define (try-solo type start-idx current-idx)
597         "Find a maximum stretch that can be marked as solo.  Only set
598 the mark when there are no spanners active.
599
600       return next idx to analyse.
601 "
602         (if (< current-idx (vector-length result))
603             (let* ((now-state (vector-ref result current-idx))
604                    (solo-state (current-voice-state now-state (if (equal? type 'solo1) 1 2)))
605                    (silent-state (current-voice-state now-state (if (equal? type 'solo1) 2 1)))
606                    (silent-notes (if silent-state (note-events silent-state) '()))
607                    (solo-notes (if solo-state (note-events solo-state) '())))
608               ;; (display (list "trying " type " at "  (moment now-state) solo-state silent-state        "\n"))
609               (cond ((not (equal? (configuration now-state) 'apart))
610                      current-idx)
611                     ((> (length silent-notes) 0) start-idx)
612                     ((not solo-state)
613                      (put-range type start-idx current-idx)
614                      current-idx)
615                     ((and
616                       (null? (span-state solo-state)))
617
618                      ;;
619                      ;; This includes rests. This isn't a problem: long rests
620                      ;; will be shared with the silent voice, and be marked
621                      ;; as unisilence. Therefore, long rests won't
622                      ;;  accidentally be part of a solo.
623                      ;;
624                      (put-range type start-idx current-idx)
625                      (try-solo type (1+ current-idx) (1+  current-idx)))
626                     (else
627                      (try-solo type start-idx (1+ current-idx)))))
628             ;; try-solo
629             start-idx))
630
631       (define (analyse-apart-silence result-idx)
632         "Analyse 'apart-silence starting at RESULT-IDX.  Return next index."
633         (let* ((now-state (vector-ref result result-idx))
634                (vs1 (current-voice-state now-state 1))
635                (vs2 (current-voice-state now-state 2))
636                (rests1 (if vs1 (rest-or-skip-events vs1) '()))
637                (rests2 (if vs2 (rest-or-skip-events vs2) '()))
638                (prev-state (if (> result-idx 0)
639                                (vector-ref result (- result-idx 1))
640                                #f))
641                (prev-config (if prev-state
642                                 (configuration prev-state)
643                                 'apart-silence)))
644           (cond
645            ;; rest with multi-measure rest: choose the rest
646            ((and (synced? now-state)
647                  (= 1 (length rests1))
648                  (ly:in-event-class? (car rests1) 'rest-event)
649                  (= 0 (length rests2))) ; probably mmrest
650             (put 'silence1))
651
652            ;; as above with parts swapped
653            ((and (synced? now-state)
654                  (= 1 (length rests2))
655                  (ly:in-event-class? (car rests2) 'rest-event)
656                  (= 0 (length rests1))) ; probably mmrest
657             (put 'silence2))
658
659            ((synced? now-state)
660             (put 'apart-silence))
661
662            ;; remain in the silence1/2 states until resync
663            ((equal? prev-config 'silence1)
664             (put 'silence1))
665
666            ((equal? prev-config 'silence2)
667             (put 'silence2))
668
669            (else
670             (put 'apart-silence)))
671
672           (1+ result-idx)))
673
674       (define (analyse-apart result-idx)
675         "Analyse 'apart starting at RESULT-IDX.  Return next index."
676         (let* ((now-state (vector-ref result result-idx))
677                (vs1 (current-voice-state now-state 1))
678                (vs2 (current-voice-state now-state 2))
679                ;; (vs1 (car (voice-states now-state)))
680                ;; (vs2 (cdr (voice-states now-state)))
681                (notes1 (if vs1 (note-events vs1) '()))
682                (notes2 (if vs2 (note-events vs2) '()))
683                (n1 (length notes1))
684                (n2 (length notes2)))
685           ;; (display (list "analyzing step " result-idx "  moment " (moment now-state) vs1 vs2  "\n"))
686           (max
687            ;; we should always increase.
688            (cond ((and (= n1 0) (= n2 0))
689                   ;; If we hit this, it means that the previous passes
690                   ;; have designated as 'apart what is really
691                   ;; 'apart-silence.
692                   (analyse-apart-silence result-idx))
693                  ((and (= n2 0)
694                        (equal? (moment vs1) (moment now-state))
695                        (null? (previous-span-state vs1)))
696                   (try-solo 'solo1 result-idx result-idx))
697                  ((and (= n1 0)
698                        (equal? (moment vs2) (moment now-state))
699                        (null? (previous-span-state vs2)))
700                   (try-solo 'solo2 result-idx result-idx))
701
702                  (else (1+ result-idx)))
703            ;; analyse-moment
704            (1+ result-idx))))
705
706       (if (< result-idx (vector-length result))
707           (let ((conf (configuration (vector-ref result result-idx))))
708             (cond
709              ((equal? conf 'apart)
710               (analyse-solo12 (analyse-apart result-idx)))
711              ((equal? conf 'apart-silence)
712               (analyse-solo12 (analyse-apart-silence result-idx)))
713              (else
714               (analyse-solo12 (1+ result-idx))))))) ; analyse-solo12
715
716     (analyse-spanner-states voice-state-vec1)
717     (analyse-spanner-states voice-state-vec2)
718     (if #f
719         (begin
720           (display voice-state-vec1)
721           (display "***\n")
722           (display voice-state-vec2)
723           (display "***\n")
724           (display result)
725           (display "***\n")))
726
727     ;; Extract all forced combine strategies, i.e. events inserted by
728     ;; \partcombine(Apart|Automatic|SoloI|SoloII|Chords)[Once]
729     ;; They will in the end override the automaically determined ones.
730     ;; Initial state for both voices is no override
731     (analyse-forced-combine 0 #f)
732     ;; Now go through all time steps in a loop and find a combination strategy
733     ;; based only on the events of that one moment (i.e. neglecting longer
734     ;; periods of solo/apart, etc.)
735     (analyse-time-step 0)
736     ;; (display result)
737     ;; Check for unisono or unisilence moments
738     (analyse-a2 0)
739     ;;(display result)
740     (analyse-solo12 0)
741     ;; (display result)
742     (set! result (map
743                   ;; forced-configuration overrides, if it is set
744                   (lambda (x) (cons (moment x) (or (forced-configuration x) (configuration x))))
745                   (vector->list result)))
746     (if #f ;; pc-debug
747         (display result))
748     result))
749
750 (define-public default-part-combine-mark-state-machine
751   ;; (current-state . ((split-state-event .
752   ;;                      (output-voice output-event next-state)) ...))
753   '((Initial . ((solo1   . (solo   SoloOneEvent Solo1))
754                 (solo2   . (solo   SoloTwoEvent Solo2))
755                 (unisono . (shared UnisonoEvent Unisono))))
756     (Solo1   . ((apart   . (#f     #f           Initial))
757                 (chords  . (#f     #f           Initial))
758                 (solo2   . (solo   SoloTwoEvent Solo2))
759                 (unisono . (shared UnisonoEvent Unisono))))
760     (Solo2   . ((apart   . (#f     #f           Initial))
761                 (chords  . (#f     #f           Initial))
762                 (solo1   . (solo   SoloOneEvent Solo1))
763                 (unisono . (shared UnisonoEvent Unisono))))
764     (Unisono . ((apart   . (#f     #f           Initial))
765                 (chords  . (#f     #f           Initial))
766                 (solo1   . (solo   SoloOneEvent Solo1))
767                 (solo2   . (solo   SoloTwoEvent Solo2))))))
768
769 (define-public (make-part-combine-marks state-machine split-list)
770   "Generate a sequence of part combiner events from a split list"
771
772   (define (get-state state-name)
773     (assq-ref state-machine state-name))
774
775   (let ((full-seq '()) ; sequence of { \context Voice = "x" {} ... }
776         (segment '()) ; sequence within \context Voice = "x" {...}
777         (prev-moment ZERO-MOMENT)
778         (prev-voice #f)
779         (state (get-state 'Initial)))
780
781     (define (commit-segment)
782       "Add the current segment to the full sequence and begin another."
783       (if (pair? segment)
784           (set! full-seq
785                 (cons (make-music 'ContextSpeccedMusic
786                                   'context-id (symbol->string prev-voice)
787                                   'context-type 'Voice
788                                   'element (make-sequential-music (reverse! segment)))
789                       full-seq)))
790       (set! segment '()))
791
792     (define (handle-split split)
793       (let* ((moment (car split))
794              (action (assq-ref state (cdr split))))
795         (if action
796             (let ((voice (car action))
797                   (part-combine-event (cadr action))
798                   (next-state-name (caddr action)))
799               (if part-combine-event
800                   (let ((dur (ly:moment-sub moment prev-moment)))
801                     ;; start a new segment when the voice changes
802                     (if (not (eq? voice prev-voice))
803                         (begin
804                           (commit-segment)
805                           (set! prev-voice voice)))
806                     (if (not (equal? dur ZERO-MOMENT))
807                         (set! segment (cons (make-music 'SkipEvent
808                                                           'duration (make-duration-of-length dur)) segment)))
809                     (set! segment (cons (make-music part-combine-event) segment))
810
811                     (set! prev-moment moment)))
812               (set! state (get-state next-state-name))))))
813
814     (for-each handle-split split-list)
815     (commit-segment)
816     (make-sequential-music (reverse! full-seq))))
817
818 (define-public default-part-combine-context-change-state-machine-one
819   ;; (current-state . ((split-state-event . (output-voice next-state)) ...))
820   '((Initial . ((apart         . (one    . Initial))
821                 (apart-silence . (one    . Initial))
822                 (apart-spanner . (one    . Initial))
823                 (chords        . (shared . Initial))
824                 (silence1      . (shared . Initial))
825                 (silence2      . (null   . Demoted))
826                 (solo1         . (solo   . Initial))
827                 (solo2         . (null   . Demoted))
828                 (unisono       . (shared . Initial))
829                 (unisilence    . (shared . Initial))))
830
831     ;; After a part has been used as the exclusive input for a
832     ;; passage, we want to use it by default for unisono/unisilence
833     ;; passages because Part_combine_iterator might have killed
834     ;; multi-measure rests in the other part.  Here we call such a
835     ;; part "promoted".  Part one begins promoted.
836     (Demoted . ((apart         . (one    . Demoted))
837                 (apart-silence . (one    . Demoted))
838                 (apart-spanner . (one    . Demoted))
839                 (chords        . (shared . Demoted))
840                 (silence1      . (shared . Initial))
841                 (silence2      . (null   . Demoted))
842                 (solo1         . (solo   . Initial))
843                 (solo2         . (null   . Demoted))
844                 (unisono       . (null   . Demoted))
845                 (unisilence    . (null   . Demoted))))))
846
847 (define-public default-part-combine-context-change-state-machine-two
848   ;; (current-state . ((split-state-event . (output-voice next-state)) ...))
849   '((Initial . ((apart         . (two    . Initial))
850                 (apart-silence . (two    . Initial))
851                 (apart-spanner . (two    . Initial))
852                 (chords        . (shared . Initial))
853                 (silence1      . (null   . Initial))
854                 (silence2      . (shared . Promoted))
855                 (solo1         . (null   . Initial))
856                 (solo2         . (solo   . Promoted))
857                 (unisono       . (null   . Initial))
858                 (unisilence    . (null   . Initial))))
859
860     ;; See the part-one state machine for the meaning of "promoted".
861     (Promoted . ((apart         . (two    . Promoted))
862                  (apart-silence . (two    . Promoted))
863                  (apart-spanner . (two    . Promoted))
864                  (chords        . (shared . Promoted))
865                  (silence1      . (null   . Initial))
866                  (silence2      . (shared . Promoted))
867                  (solo1         . (null   . Initial))
868                  (solo2         . (solo   . Promoted))
869                  (unisono       . (shared . Promoted))
870                  (unisilence    . (shared . Promoted))))))
871
872 (define-public (make-part-combine-context-changes state-machine split-list)
873   "Generate a sequence of part combiner context changes from a split list"
874
875   (define (get-state state-name)
876     (assq-ref state-machine state-name))
877
878   (let ((change-list '())
879         (prev-voice #f)
880         (state (get-state 'Initial)))
881
882     (define (handle-split split)
883       (let* ((moment (car split))
884              (action (assq-ref state (cdr split))))
885         (if action
886             (let ((voice (car action))
887                   (next-state-name (cdr action)))
888               (if (not (eq? voice prev-voice))
889                   (begin
890                     (set! change-list (cons (cons moment voice) change-list))
891                     (set! prev-voice voice)))
892               (set! state (get-state next-state-name))))))
893
894     (for-each handle-split split-list)
895     (reverse! change-list)))
896
897 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
898
899 (define-public (add-quotable name mus)
900   (let* ((tab (eval 'musicQuotes (current-module)))
901          (voicename (get-next-unique-voice-name))
902          ;; recording-group-emulate returns an assoc list (reversed!), so
903          ;; hand it a proper unique context name and extract that key:
904          (ctx-spec (context-spec-music mus 'Voice voicename))
905          (listener (ly:parser-lookup 'partCombineListener))
906          (context-list (reverse (recording-group-emulate ctx-spec listener)))
907          (raw-voice (assoc voicename context-list))
908          (quote-contents (if (pair? raw-voice) (cdr raw-voice) '())))
909
910     ;; If the context-specced quoted music does not contain anything, try to
911     ;; use the first child, i.e. the next in context-list after voicename
912     ;; That's the case e.g. for \addQuote "x" \relative c \new Voice {...}
913     (if (null? quote-contents)
914         (let find-non-empty ((current-tail (member raw-voice context-list)))
915           ;; if voice has contents, use them, otherwise check next ctx
916           (cond ((null? current-tail) #f)
917                 ((and (pair? (car current-tail))
918                       (pair? (cdar current-tail)))
919                  (set! quote-contents (cdar current-tail)))
920                 (else (find-non-empty (cdr current-tail))))))
921
922     (if (not (null? quote-contents))
923         (hash-set! tab name (list->vector (reverse! quote-contents '())))
924         (ly:music-warning mus (ly:format (_ "quoted music `~a' is empty") name)))))