]> git.donarmstrong.com Git - lilypond.git/blob - scm/part-combiner.scm
[scm]: Use two spaces after full stop in doc strings.
[lilypond.git] / scm / part-combiner.scm
1 ;;;; This file is part of LilyPond, the GNU music typesetter.
2 ;;;;
3 ;;;; Copyright (C) 2004--2011 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 when #:init-keyword #:when)
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 (when 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 (define-method (note-events (vs <Voice-state>))
43   (define (f? x)
44     (equal? (ly:event-property  x 'class) 'note-event))
45   (filter f? (events vs)))
46
47 (define-method (previous-voice-state (vs <Voice-state>))
48   (let ((i (slot-ref vs 'vector-index))
49         (v (slot-ref vs 'state-vector)))
50     (if (< 0 i)
51         (vector-ref v (1- i))
52         #f)))
53
54 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
55
56 (define-class <Split-state> ()
57   ;; The automatically determined split configuration
58   (configuration #:init-value '() #:accessor configuration)
59   ;; Allow overriding split configuration, takes precedence over configuration
60   (forced-configuration #:init-value #f #:accessor forced-configuration)
61   (when-moment #:accessor when #:init-keyword #:when)
62   ;; voice-states are states starting with the Split-state or later
63   ;;
64   (is #:init-keyword #:voice-states #:accessor voice-states)
65   (synced  #:init-keyword #:synced #:init-value  #f #:getter synced?))
66
67
68 (define-method (write (x <Split-state> ) f)
69   (display (when x) f)
70   (display " = " f)
71   (display (configuration x) f)
72   (if (synced? x)
73       (display " synced "))
74   (display "\n" f))
75
76 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
77
78
79 (define (previous-span-state vs)
80   (let ((p (previous-voice-state vs)))
81     (if p (span-state p) '())))
82
83 (define (make-voice-states evl)
84   (let ((vec (list->vector (map (lambda (v)
85                                   (make <Voice-state>
86                                     #:when (caar v)
87                                     #:tuning (cdar v)
88                                     #:events (map car (cdr v))))
89                                 evl))))
90     (do ((i 0 (1+ i)))
91         ((= i (vector-length vec)) vec)
92       (slot-set! (vector-ref vec i) 'vector-index i)
93       (slot-set! (vector-ref vec i) 'state-vector vec))))
94
95 (define (make-split-state vs1 vs2)
96   "Merge lists VS1 and VS2, containing Voice-state objects into vector
97 of Split-state objects, crosslinking the Split-state vector and
98 Voice-state objects
99 "
100   (define (helper ss-idx ss-list idx1 idx2)
101     (let* ((state1 (if (< idx1 (vector-length vs1)) (vector-ref vs1 idx1) #f))
102            (state2 (if (< idx2 (vector-length vs2)) (vector-ref vs2 idx2) #f))
103            (min (cond ((and state1 state2) (moment-min (when state1) (when state2)))
104                       (state1 (when state1))
105                       (state2 (when state2))
106                       (else #f)))
107            (inc1 (if (and state1 (equal? min (when state1))) 1 0))
108            (inc2 (if (and state2 (equal? min (when state2))) 1 0))
109            (ss-object (if min
110                           (make <Split-state>
111                             #:when min
112                             #:voice-states (cons state1 state2)
113                             #:synced (= inc1 inc2))
114                           #f)))
115       (if state1
116           (set! (split-index state1) ss-idx))
117       (if state2
118           (set! (split-index state2) ss-idx))
119       (if min
120           (helper (1+ ss-idx)
121                   (cons ss-object ss-list)
122                   (+ idx1 inc1)
123                   (+ idx2 inc2))
124           ss-list)))
125   (list->vector (reverse! (helper 0 '() 0  0) '())))
126
127 (define (analyse-spanner-states voice-state-vec)
128
129   (define (helper index active)
130     "Analyse EVS at INDEX, given state ACTIVE."
131
132     (define (analyse-tie-start active ev)
133       (if (equal? (ly:event-property ev 'class) 'tie-event)
134           (acons 'tie (split-index (vector-ref voice-state-vec index))
135                  active)
136           active))
137
138     (define (analyse-tie-end active ev)
139       (if (equal? (ly:event-property ev 'class) 'note-event)
140           (assoc-remove! active 'tie)
141           active))
142
143     (define (analyse-absdyn-end active ev)
144       (if (or (equal? (ly:event-property ev 'class) 'absolute-dynamic-event)
145               (and (equal? (ly:event-property ev 'class) 'crescendo-event)
146                    (equal? STOP (ly:event-property ev 'span-direction))))
147           (assoc-remove! (assoc-remove! active 'cresc) 'decr)
148           active))
149
150     (define (active<? a b)
151       (cond ((symbol<? (car a) (car b)) #t)
152             ((symbol<? (car b) (car b)) #f)
153             (else (< (cdr a) (cdr b)))))
154
155     (define (analyse-span-event active ev)
156       (let* ((name (ly:event-property ev 'class))
157              (key (cond ((equal? name 'slur-event) 'slur)
158                         ((equal? name 'phrasing-slur-event) 'tie)
159                         ((equal? name 'beam-event) 'beam)
160                         ((equal? name 'crescendo-event) 'cresc)
161                         ((equal? name 'decrescendo-event) 'decr)
162                         (else #f)))
163              (sp (ly:event-property ev 'span-direction)))
164         (if (and (symbol? key) (ly:dir? sp))
165             (if (= sp STOP)
166                 (assoc-remove! active key)
167                 (acons key
168                        (split-index (vector-ref voice-state-vec index))
169                        active))
170             active)))
171
172     (define (analyse-events active evs)
173       "Run all analyzers on ACTIVE and EVS"
174       (define (run-analyzer analyzer active evs)
175         (if (pair? evs)
176             (run-analyzer analyzer (analyzer active (car evs)) (cdr evs))
177             active))
178       (define (run-analyzers analyzers active evs)
179         (if (pair? analyzers)
180             (run-analyzers (cdr analyzers)
181                            (run-analyzer (car analyzers) active evs)
182                            evs)
183             active))
184       (sort ;; todo: use fold or somesuch.
185        (run-analyzers (list analyse-absdyn-end analyse-span-event
186                             ;; note: tie-start/span comes after tie-end/absdyn.
187                             analyse-tie-end analyse-tie-start)
188                       active evs)
189        active<?))
190
191     ;; must copy, since we use assoc-remove!
192     (if (< index (vector-length voice-state-vec))
193         (begin
194           (set! active (analyse-events active (events (vector-ref voice-state-vec index))))
195           (set! (span-state (vector-ref voice-state-vec index))
196                 (list-copy active))
197           (helper (1+ index) active))))
198
199   (helper 0 '()))
200
201 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
202 (define-public (recording-group-emulate music odef)
203   "Interprets music according to odef, but stores all events in a chronological
204 list, similar to the Recording_group_engraver in 2.8 and earlier"
205   (let*
206      ((context-list '())
207       (now-mom (ly:make-moment 0 0))
208       (global (ly:make-global-context odef))
209       (mom-listener (ly:make-listener
210              (lambda (tev) (set! now-mom (ly:event-property tev 'moment)))))
211       (new-context-listener
212        (ly:make-listener
213         (lambda (sev)
214           (let*
215              ((child (ly:event-property sev 'context))
216               (this-moment-list (cons (ly:context-id child) '()))
217               (dummy (set! context-list (cons this-moment-list context-list)))
218               (acc '())
219               (accumulate-event-listener
220                   (ly:make-listener (lambda (ev)
221                                        (set! acc (cons (cons ev #t) acc)))))
222               (save-acc-listener
223                   (ly:make-listener (lambda (tev)
224                       (if (pair? acc)
225                         (let ((this-moment
226                               (cons (cons now-mom
227                                 (ly:context-property child 'instrumentTransposition))
228                                 ;; The accumulate-event-listener above creates
229                                 ;; the list of events in reverse order, so we
230                                 ;; have to revert it to the original order again
231                                 (reverse acc))))
232                           (set-cdr! this-moment-list
233                                 (cons this-moment (cdr this-moment-list)))
234                           (set! acc '())))))))
235             (ly:add-listener accumulate-event-listener
236                 (ly:context-event-source child) 'StreamEvent)
237             (ly:add-listener save-acc-listener
238                 (ly:context-event-source global) 'OneTimeStep))))))
239     (ly:add-listener new-context-listener
240         (ly:context-events-below global) 'AnnounceNewContext)
241     (ly:add-listener mom-listener (ly:context-event-source global) 'Prepare)
242     (ly:interpret-music-expression (make-non-relative-music music) global)
243     context-list))
244
245 (define-public (make-part-combine-music parser music-list)
246   (let* ((m (make-music 'PartCombineMusic))
247          (m1 (make-non-relative-music (context-spec-music (first music-list) 'Voice "one")))
248          (m2  (make-non-relative-music  (context-spec-music (second music-list) 'Voice "two")))
249          (listener (ly:parser-lookup parser 'partCombineListener))
250          (evs2 (recording-group-emulate m2 listener))
251          (evs1 (recording-group-emulate m1 listener)))
252
253     (set! (ly:music-property m 'elements) (list m1 m2))
254     (set! (ly:music-property m 'split-list)
255           (if (and (assoc "one" evs1) (assoc "two" evs2))
256               (determine-split-list (reverse! (assoc-get "one" evs1) '())
257                                     (reverse! (assoc-get "two" evs2) '()))
258               '()))
259     m))
260
261 (define-public (determine-split-list evl1 evl2)
262   "EVL1 and EVL2 should be ascending"
263   (let* ((pc-debug #f)
264          (chord-threshold 8)
265          (voice-state-vec1 (make-voice-states evl1))
266          (voice-state-vec2 (make-voice-states evl2))
267          (result (make-split-state voice-state-vec1 voice-state-vec2)))
268
269     ;; Go through all moments recursively and check if the events of that
270     ;; moment contain a part-combine-force-event override. If so, store its
271     ;; value in the forced-configuration field, which will override. The
272     ;; previous configuration is used to determine non-terminated settings.
273     (define (analyse-forced-combine result-idx prev-res)
274
275       (define (get-forced-event x)
276         (if (ly:in-event-class? x 'part-combine-force-event)
277             (cons (ly:event-property x 'forced-type) (ly:event-property x 'once))
278             #f))
279       (define (part-combine-events vs)
280         (if (not vs)
281             '()
282             (filter-map get-forced-event (events vs))))
283       ;; end part-combine-events
284
285       ;; forced-result: Take the previous config and analyse whether
286       ;; any change happened.... Return new once and permanent config
287       (define (forced-result evt state)
288         ;; sanity check, evt should always be (new-state . once)
289         (if (not (and (pair? evt) (pair? state)))
290             state
291             (if (cdr evt)
292                 ;; Once-event, leave permanent state unchanged
293                 (cons (car evt) (cdr state))
294                 ;; permanent change, leave once state unchanged
295                 (cons (car state) (car evt)))))
296       ;; end forced-combine-result
297
298       ;; body of analyse-forced-combine:
299       (if (< result-idx (vector-length result))
300           (let* ((now-state (vector-ref result result-idx)) ; current result
301                  ;; Extract all part-combine force events
302                  (ev1 (part-combine-events (car (voice-states now-state))))
303                  (ev2 (part-combine-events (cdr (voice-states now-state))))
304                  (evts (append ev1 ev2))
305                  ;; result is (once-state permament-state):
306                  (state (fold forced-result (cons 'automatic prev-res) evts))
307                  ;; Now let once override permanent changes:
308                  (force-state (if (equal? (car state) 'automatic)
309                                   (cdr state)
310                                   (car state))))
311             (set! (forced-configuration (vector-ref result result-idx))
312                   force-state)
313             ;; For the next moment, ignore the once override (car stat)
314             ;; and pass on the permanent override, stored as (cdr state)
315             (analyse-forced-combine (1+ result-idx) (cdr state)))))
316     ;; end analyse-forced-combine
317
318
319     (define (analyse-time-step result-idx)
320       (define (put x . index)
321         "Put the result to X, starting from INDEX backwards.
322
323 Only set if not set previously.
324 "
325         (let ((i (if (pair? index) (car index) result-idx)))
326           (if (and (<= 0 i)
327                    (not (symbol? (configuration (vector-ref result i)))))
328               (begin
329                 (set! (configuration (vector-ref result i)) x)
330                 (put x (1- i))))))
331
332       (define (copy-state-from state-vec vs)
333         (define (copy-one-state key-idx)
334           (let* ((idx (cdr key-idx))
335                  (prev-ss (vector-ref result idx))
336                  (prev (configuration prev-ss)))
337             (if (symbol? prev)
338                 (put prev))))
339         (map copy-one-state (span-state vs)))
340
341       (define (analyse-notes now-state)
342         (let* ((vs1 (car (voice-states now-state)))
343                (vs2 (cdr (voice-states now-state)))
344                (notes1 (note-events vs1))
345                (durs1 (sort (map (lambda (x) (ly:event-property x 'duration))
346                                  notes1)
347                             ly:duration<?))
348                (pitches1 (sort (map (lambda (x) (ly:event-property x 'pitch))
349                                     notes1)
350                                ly:pitch<?))
351                (notes2 (note-events vs2))
352                (durs2 (sort (map (lambda (x) (ly:event-property x 'duration))
353                                  notes2)
354                             ly:duration<?))
355                (pitches2 (sort (map (lambda (x) (ly:event-property x 'pitch))
356                                     notes2)
357                                ly:pitch<?)))
358           (cond ((> (length notes1) 1) (put 'apart))
359                 ((> (length notes2) 1) (put 'apart))
360                 ((= 1 (+ (length notes2) (length notes1))) (put 'apart))
361                 ((and (= (length durs1) 1)
362                       (= (length durs2) 1)
363                       (not (equal? (car durs1) (car durs2))))
364                  (put 'apart))
365                 (else
366                  (if (and (= (length pitches1) (length pitches2)))
367                      (if (and (pair? pitches1)
368                               (pair? pitches2)
369                               (or
370                                (< chord-threshold (ly:pitch-steps
371                                                    (ly:pitch-diff (car pitches1)
372                                                                   (car pitches2))))
373
374                                ;; voice crossings:
375                                (> 0 (ly:pitch-steps (ly:pitch-diff (car pitches1)
376                                                                    (car pitches2))))
377                                ))
378                          (put 'apart)
379                          ;; copy previous split state from spanner state
380                          (begin
381                            (if (previous-voice-state vs1)
382                                (copy-state-from voice-state-vec1
383                                                 (previous-voice-state vs1)))
384                            (if (previous-voice-state vs2)
385                                (copy-state-from voice-state-vec2
386                                                 (previous-voice-state vs2)))
387                            (if (and (null? (span-state vs1)) (null? (span-state vs2)))
388                                (put 'chords)))))))))
389
390       (if (< result-idx (vector-length result))
391           (let* ((now-state (vector-ref result result-idx))
392                  (vs1 (car (voice-states now-state)))
393                  (vs2 (cdr (voice-states now-state))))
394
395             (cond ((not vs1) (put 'apart))
396                   ((not vs2) (put 'apart))
397                   (else
398                    (let ((active1 (previous-span-state vs1))
399                          (active2 (previous-span-state vs2))
400                          (new-active1 (span-state vs1))
401                          (new-active2 (span-state vs2)))
402                      (if #f ; debug
403                          (display (list (when now-state) result-idx
404                                         active1 "->" new-active1
405                                         active2 "->" new-active2
406                                         "\n")))
407                      (if (and (synced? now-state)
408                               (equal? active1 active2)
409                               (equal? new-active1 new-active2))
410                          (analyse-notes now-state)
411
412                          ;; active states different:
413                          (put 'apart)))
414
415                    ;; go to the next one, if it exists.
416                    (analyse-time-step (1+ result-idx)))))))
417
418     (define (analyse-a2 result-idx)
419       (if (< result-idx (vector-length result))
420           (let* ((now-state (vector-ref result result-idx))
421                  (vs1 (car (voice-states now-state)))
422                  (vs2 (cdr (voice-states now-state))))
423             (if (and (equal? (configuration now-state) 'chords)
424                      vs1 vs2)
425                 (let ((notes1 (note-events vs1))
426                       (notes2 (note-events vs2)))
427                   (cond ((and (= 1 (length notes1))
428                               (= 1 (length notes2))
429                               (equal? (ly:event-property (car notes1) 'pitch)
430                                       (ly:event-property (car notes2) 'pitch)))
431                          (set! (configuration now-state) 'unisono))
432                         ((and (= 0 (length notes1))
433                               (= 0 (length notes2)))
434                          (set! (configuration now-state) 'unisilence)))))
435             (analyse-a2 (1+ result-idx)))))
436
437     (define (analyse-solo12 result-idx)
438
439       (define (previous-config vs)
440         (let* ((pvs (previous-voice-state vs))
441                (spi (if pvs (split-index pvs) #f))
442                (prev-split (if spi (vector-ref result spi) #f)))
443           (if prev-split
444               (configuration prev-split)
445               'apart)))
446
447       (define (put-range x a b)
448         ;; (display (list "put range "  x a b "\n"))
449         (do ((i a (1+ i)))
450             ((> i b) b)
451           (set! (configuration (vector-ref result i)) x)))
452
453       (define (put x)
454         ;; (display (list "putting "  x "\n"))
455         (set! (configuration (vector-ref result result-idx)) x))
456
457       (define (current-voice-state now-state voice-num)
458         (define vs ((if (= 1 voice-num) car cdr)
459                     (voice-states now-state)))
460         (if (or (not vs) (equal? (when now-state) (when vs)))
461             vs
462             (previous-voice-state vs)))
463
464       (define (try-solo type start-idx current-idx)
465         "Find a maximum stretch that can be marked as solo.  Only set
466 the mark when there are no spanners active.
467
468       return next idx to analyse.
469 "
470         (if (< current-idx (vector-length result))
471             (let* ((now-state (vector-ref result current-idx))
472                    (solo-state (current-voice-state now-state (if (equal? type 'solo1) 1 2)))
473                    (silent-state (current-voice-state now-state (if (equal? type 'solo1) 2 1)))
474                    (silent-notes (if silent-state (note-events silent-state) '()))
475                    (solo-notes (if solo-state (note-events solo-state) '())))
476               ;; (display (list "trying " type " at "  (when now-state) solo-state silent-state  "\n"))
477               (cond ((not (equal? (configuration now-state) 'apart))
478                      current-idx)
479                     ((> (length silent-notes) 0) start-idx)
480                     ((not solo-state)
481                      (put-range type start-idx current-idx)
482                      current-idx)
483                     ((and
484                       (null? (span-state solo-state)))
485
486                      ;;
487                      ;; This includes rests. This isn't a problem: long rests
488                      ;; will be shared with the silent voice, and be marked
489                      ;; as unisilence. Therefore, long rests won't
490                      ;;  accidentally be part of a solo.
491                      ;;
492                      (put-range type start-idx current-idx)
493                      (try-solo type (1+ current-idx) (1+  current-idx)))
494                     (else
495                      (try-solo type start-idx (1+ current-idx)))))
496             ;; try-solo
497             start-idx))
498
499       (define (analyse-moment result-idx)
500         "Analyse 'apart starting at RESULT-IDX.  Return next index."
501         (let* ((now-state (vector-ref result result-idx))
502                (vs1 (current-voice-state now-state 1))
503                (vs2 (current-voice-state now-state 2))
504                ;; (vs1 (car (voice-states now-state)))
505                ;; (vs2 (cdr (voice-states now-state)))
506                (notes1 (if vs1 (note-events vs1) '()))
507                (notes2 (if vs2 (note-events vs2) '()))
508                (n1 (length notes1))
509                (n2 (length notes2)))
510           ;; (display (list "analyzing step " result-idx "  moment " (when now-state) vs1 vs2  "\n"))
511           (max
512            ;; we should always increase.
513            (cond ((and (= n1 0) (= n2 0))
514                   (put 'apart-silence)
515                   (1+ result-idx))
516                  ((and (= n2 0)
517                        (equal? (when vs1) (when now-state))
518                        (null? (previous-span-state vs1)))
519                   (try-solo 'solo1 result-idx result-idx))
520                  ((and (= n1 0)
521                        (equal? (when vs2) (when now-state))
522                        (null? (previous-span-state vs2)))
523                   (try-solo 'solo2 result-idx result-idx))
524
525                  (else (1+ result-idx)))
526            ;; analyse-moment
527            (1+ result-idx))))
528
529       (if (< result-idx (vector-length result))
530           (if (equal? (configuration (vector-ref result result-idx)) 'apart)
531               (analyse-solo12 (analyse-moment result-idx))
532               (analyse-solo12 (1+ result-idx))))) ; analyse-solo12
533
534     (analyse-spanner-states voice-state-vec1)
535     (analyse-spanner-states voice-state-vec2)
536     (if #f
537         (begin
538           (display voice-state-vec1)
539           (display "***\n")
540           (display voice-state-vec2)
541           (display "***\n")
542           (display result)
543           (display "***\n")))
544
545     ;; Extract all forced combine strategies, i.e. events inserted by
546     ;; \partcombine(Apart|Automatic|SoloI|SoloII|Chords)[Once]
547     ;; They will in the end override the automaically determined ones.
548     ;; Initial state for both voices is no override
549     (analyse-forced-combine 0 #f)
550     ;; Now go through all time steps in a loop and find a combination strategy
551     ;; based only on the events of that one moment (i.e. neglecting longer
552     ;; periods of solo/apart, etc.)
553     (analyse-time-step 0)
554     ;; (display result)
555     ;; Check for unisono or unisilence moments
556     (analyse-a2 0)
557     ;;(display result)
558     (analyse-solo12 0)
559     ;; (display result)
560     (set! result (map
561                   ;; forced-configuration overrides, if it is set
562                   (lambda (x) (cons (when x) (or (forced-configuration x) (configuration x))))
563                   (vector->list result)))
564     (if #f ;; pc-debug
565          (display result))
566     result))
567
568
569 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
570
571 (define-public (add-quotable parser name mus)
572   (let* ((tab (eval 'musicQuotes (current-module)))
573          (context-list (recording-group-emulate (context-spec-music mus 'Voice)
574                                                 (ly:parser-lookup parser 'partCombineListener))))
575     (if (pair? context-list)
576         (hash-set! tab name
577                    ;; cdr : skip name string
578                    (list->vector (reverse! (cdar context-list)
579                                            '()))))))