-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathpatterns.lisp
3294 lines (2666 loc) · 129 KB
/
patterns.lisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;;; patterns.lisp - basic pattern functionality (`defpattern', etc) and a variety of basic patterns implemented with it.
(in-package #:cl-patterns)
;;; pattern glue
(defun make-default-event ()
"Get `*event*' if it's not nil, or get a fresh empty event."
(or *event* (event)))
(defvar *patterns* nil
"List of the names of all defined pattern types.
See also: `all-patterns'")
(defmacro defpattern (name superclasses slots &key documentation defun)
"Define a pattern. This macro automatically generates the pattern's class, its pstream class, and the function to create an instance of the pattern, and makes them external in the cl-patterns package.
NAME is the name of the pattern. Typically a word or two that describes its function, prefixed with p.
SUPERCLASSES is a list of superclasses of the pattern. Most patterns just subclass the 'pattern' class.
SLOTS is a list of slots that the pattern and pstreams derived from it have. Each slot can either be just a symbol, or a slot definition a la `defclass'. You can provide a default for the slot with the :initform key as usual, and you can set a slot as a state slot (which only appears in the pattern's pstream class) by setting the :state key to t.
DOCUMENTATION is a docstring describing the pattern. We recommend providing at least one example, and a \"See also\" section to refer to similar pattern classes.
DEFUN can either be a full defun form for the pattern, or an expression which will be inserted into the pattern creation function prior to initialization of the instance. Typically you'd use this for inserting `assert' statements, for example.
See also: `pattern', `pdef', `all-patterns'"
(let* ((superclasses (or superclasses (list 'pattern)))
(slots (mapcar #'ensure-list slots))
(name-pstream (pattern-pstream-class-name name))
(super-pstream (if (eql 'pattern (car superclasses))
'pstream
(pattern-pstream-class-name (car superclasses)))))
(labels ((desugar-slot (slot)
"Convert a slot into something appropriate for defclass to handle."
(destructuring-bind (name . rest) slot
(append (list name)
(remove-from-plist rest :state)
(unless (position :initarg (keys rest))
(list :initarg (make-keyword name))))))
(optional-slot-p (slot)
"Whether the slot is optional or not. A slot is considered optional if an initform is provided."
(position :initform (keys (cdr slot))))
(state-slot-p (slot)
"Whether the slot is a pstream state slot or not. Pstream state slots only appear as slots for the pattern's pstream class and not for the pattern itself."
(position :state (keys (cdr slot))))
(function-lambda-list (slots)
"Generate the lambda list for the pattern's creation function."
(let (optional-used)
(mappend (fn (unless (state-slot-p _)
(if (optional-slot-p _)
(prog1
(append (unless optional-used
(list '&optional))
(list (list (car _) (getf (cdr _) :initform))))
(setf optional-used t))
(list (car _)))))
slots)))
(make-defun (pre-init)
`(defun ,name ,(function-lambda-list slots)
,documentation
,@(when pre-init (list pre-init))
(make-instance ',name
,@(mappend (fn (unless (state-slot-p _)
(list (make-keyword (car _)) (car _))))
slots))))
(add-doc-to-defun (sexp)
(if (and (listp sexp)
(position (car sexp) (list 'defun 'defmacro))
(not (stringp (fourth sexp))))
(append (subseq sexp 0 3) (list documentation) (subseq sexp 3))
sexp)))
`(progn
(defclass ,name ,superclasses
,(mapcar #'desugar-slot (remove-if #'state-slot-p slots))
,@(when documentation
`((:documentation ,documentation))))
(defmethod print-object ((,name ,name) stream)
(print-unreadable-object (,name stream :type t)
(format stream "~{~S~^ ~}"
(mapcar (lambda (slot) (slot-value ,name slot))
',(mapcar #'car (remove-if (lambda (slot)
(or (state-slot-p slot)
;; FIX: don't show arguments that are set to the defaults?
))
slots))))))
(defclass ,name-pstream (,super-pstream ,name) ; FIX: this will overwrite custom pstream classes when redefining the pattern class. should we refrain from redefining the pstream class if it's already defined? or is it possible to remove this definition entirely and just use the standard pstream class by default?
,(mapcar #'desugar-slot (remove-if-not #'state-slot-p slots))
(:documentation ,(format nil "pstream for `~A'." (string-downcase name))))
,(let* ((gen-func-p (or (null defun)
(and (listp defun)
(position (car defun) (list 'assert 'check-type)))))
(pre-init (when gen-func-p
defun)))
(if gen-func-p
(make-defun pre-init)
(add-doc-to-defun defun)))
(pushnew ',name *patterns*)))))
(defvar *max-pattern-yield-length* 256
"The default maximum number of events or values that will be used by functions like `next-n' or patterns like `protate', in order to prevent hangs caused by infinite-length patterns.")
(defvar *default-pattern-length* :inf
"The default value of a pattern's LENGTH parameter.")
(defvar *default-pattern-repeats* :inf
"The default value of a pattern's REPEATS parameter.")
;;; pattern
(defgeneric pattern-source (pattern)
(:documentation "The source object that this object was created from. For example, for a `pstream', this would be the pattern that `as-pstream' was called on."))
(defgeneric pstream-count (pattern)
(:documentation "The number of pstreams that have been made of this pattern."))
(defclass pattern ()
((play-quant :initarg :play-quant :documentation "A list of numbers representing when the pattern's pstream can start playing. See `play-quant' and `quant'.")
(end-quant :initarg :end-quant :accessor end-quant :type list :documentation "A list of numbers representing when a pattern can end playing and when a `pdef' can be swapped out for a new definition. See `end-quant' and `quant'.")
(end-condition :initarg :end-condition :initform nil :accessor end-condition :type (or null function) :documentation "Nil or a function that is called by the clock with the pattern as its argument to determine whether the pattern should end or swap to a new definition.")
(source :initarg :source :initform nil :accessor pattern-source :documentation "The source object that this object was created from. For example, for a `pstream', this would be the pattern that `as-pstream' was called on.")
(parent :initarg :parent :initform nil :documentation "When a pattern is embedded in another pattern, the embedded pattern's parent slot points to the pattern it is embedded in.")
(loop-p :initarg :loop-p :documentation "Whether or not the pattern should loop when played.")
(cleanup :initarg :cleanup :initform nil :documentation "A list of functions that are run when the pattern ends or is stopped.")
(pstream-count :initform 0 :accessor pstream-count :documentation "The number of pstreams that have been made of this pattern.")
(metadata :initarg :metadata :initform (make-hash-table) :type hash-table :documentation "Hash table of additional data associated with the pattern, accessible with the `pattern-metadata' function."))
(:documentation "Abstract pattern superclass."))
(defun set-parents (pattern)
"Loop through PATTERN's slots and set the \"parent\" slot of any patterns to this pattern."
(labels ((set-parent (list parent)
"Recurse through LIST, setting the parent of any pattern found to PARENT."
(typecase list
(list
(mapc (lambda (x) (set-parent x parent)) list))
(pattern
(setf (slot-value list 'parent) parent)))))
(dolist (slot (mapcar #'closer-mop:slot-definition-name (closer-mop:class-slots (class-of pattern))) pattern)
(when (and (not (eql slot 'parent))
(slot-boundp pattern slot))
(set-parent (slot-value pattern slot) pattern)))))
(defmethod initialize-instance :after ((pattern pattern) &key)
(set-parents pattern))
(defun pattern-p (object)
"True if OBJECT is a pattern.
See also: `pattern', `defpattern'"
(typep object 'pattern))
(defun all-patterns ()
"Get a list of the names of all defined pattern classes.
See also: `all-pdefs'"
*patterns*)
(defmethod play-quant ((pattern pattern))
(if (slot-boundp pattern 'play-quant)
(slot-value pattern 'play-quant)
(list 1)))
(defmethod (setf play-quant) (value (pattern pattern))
(setf (slot-value pattern 'play-quant) (ensure-list value)))
(defmethod end-quant ((pattern pattern))
(when (slot-boundp pattern 'end-quant)
(slot-value pattern 'end-quant)))
(defmethod (setf end-quant) (value (pattern pattern))
(setf (slot-value pattern 'end-quant) (ensure-list value)))
(defmethod play ((pattern pattern))
(clock-add (as-pstream pattern) *clock*))
(defmethod launch ((pattern pattern))
(play pattern))
(defmethod playing-p ((pattern pattern) &optional (clock *clock*))
(when clock
(find pattern (clock-tasks clock)
:key (fn (slot-value _ 'item)))))
(defmethod loop-p ((pattern pattern))
(when (slot-boundp pattern 'loop-p)
(slot-value pattern 'loop-p)))
(defmethod (setf loop-p) (value (pattern pattern))
(setf (slot-value pattern 'loop-p) value))
(defmethod dur ((pattern pattern))
(reduce #'+ (next-upto-n pattern) :key #'dur))
(defun pattern-parent (pattern &key (num 1) (accumulate nil) (class 'pattern))
"Get the NUM-th containing pattern of PATTERN, or nil if there isn't one. If CLASS is specified, only consider patterns of that class.
See also: `pattern-children'"
(check-type num (integer 0))
(let ((i 0)
res)
(until (or (>= i num)
(null pattern))
(setf pattern (slot-value pattern 'parent))
(when (typep pattern class)
(incf i)
(when accumulate
(appendf res pattern))))
(if accumulate
res
pattern)))
(defun pattern-children (pattern &key (num 1) (accumulate nil) (class 'pattern))
"Get a list of all the direct child patterns of PATTERN, including any in slots or lists.
See also: `pattern-parent'"
(let ((cur (list pattern))
res)
(dotimes (n num res)
(setf cur (remove-if-not (lambda (pattern) (typep pattern class))
(mapcan #'%pattern-children cur)))
(if accumulate
(appendf res cur)
(setf res cur)))))
(defmethod %pattern-children ((object t))
nil)
(defmethod %pattern-children ((pattern pattern))
(mapcan (lambda (slot)
(copy-list (ensure-list (slot-value pattern (closer-mop:slot-definition-name slot)))))
(closer-mop:class-direct-slots (class-of pattern))))
(defgeneric pattern-metadata (pattern &optional key)
(:documentation "Get the value of PATTERN's metadata for KEY. Returns true as a second value if the metadata had an entry for KEY, or nil if it did not."))
(defmethod pattern-metadata ((pattern pattern) &optional key)
(with-slots (metadata) pattern
(if key
(gethash key metadata)
metadata)))
(defun (setf pattern-metadata) (value pattern key)
(setf (gethash key (slot-value pattern 'metadata)) value))
(defgeneric peek (pattern)
(:documentation "\"Peek\" at the next value of a pstream, without advancing its current position.
See also: `next', `peek-n', `peek-upto-n'"))
(defun peek-n (pstream &optional (n *max-pattern-yield-length*))
"Peek at the next N results of a pstream, without advancing it forward in the process.
See also: `peek', `peek-upto-n', `next', `next-n'"
(check-type n (integer 0))
(unless (pstream-p pstream)
(return-from peek-n (peek-n (as-pstream pstream) n)))
(with-slots (number future-number) pstream
(loop :for i :from 0 :below n
:collect (pstream-elt-future pstream (+ number (- future-number) i)))))
(defun peek-upto-n (pstream &optional (n *max-pattern-yield-length*))
"Peek at up to the next N results of a pstream, without advancing it forward in the process.
See also: `peek', `peek-n', `next', `next-upto-n'"
(check-type n (integer 0))
(unless (pstream-p pstream)
(return-from peek-upto-n (peek-upto-n (as-pstream pstream) n)))
(with-slots (number future-number) pstream
(loop :for i :from 0 :below n
:for res := (pstream-elt-future pstream (+ number (- future-number) i))
:until (eop-p res)
:collect res)))
(defgeneric next (pattern)
(:documentation "Get the next value of a pstream, function, or other object, advancing the pstream forward in the process.
See also: `next-n', `next-upto-n', `peek'"))
(defmethod next ((object t))
object)
(defmethod next ((pattern pattern))
(next (as-pstream pattern)))
(defmethod next ((function function))
(funcall function))
(defun next-n (pstream &optional (n *max-pattern-yield-length*))
"Get the next N outputs of a pstream, function, or other object, advancing the pstream forward N times in the process.
See also: `next', `next-upto-n', `peek', `peek-n'"
(check-type n (integer 0))
(let ((pstream (pattern-as-pstream pstream)))
(loop :repeat n
:collect (next pstream))))
(defun next-upto-n (pstream &optional (n *max-pattern-yield-length*))
"Get a list of up to N results from PSTREAM, not including the end of pattern.
See also: `next', `next-n', `peek', `peek-upto-n'"
(check-type n (integer 0))
(let ((pstream (pattern-as-pstream pstream)))
(loop
:for number :from 0 :upto n
:while (< number n)
:for val := (next pstream)
:if (eop-p val)
:do (loop-finish)
:else
:collect val)))
(defgeneric bsubseq (object start-beat &optional end-beat)
(:documentation "\"Beat subseq\" - get a list of all events from OBJECT whose `beat' is START-BEAT or above, and below END-BEAT.
See also: `events-in-range'"))
(defgeneric events-in-range (pstream min max)
(:documentation "Get all the events from PSTREAM whose start beat are MIN or greater, and less than MAX."))
(defmethod events-in-range ((pattern pattern) min max)
(events-in-range (as-pstream pattern) min max))
;;; pstream
;; FIX: can we avoid making this inherit from pattern?
(defclass pstream (pattern #+#.(cl:if (cl:find-package "SEQUENCE") '(:and) '(:or)) sequence)
((number :initform 0 :documentation "The number of outputs yielded from this pstream and any sub-pstreams that have ended.") ; FIX: rename to outputs-yielded ?
(pattern-stack :initform nil :documentation "The stack of pattern pstreams embedded in this pstream.")
(pstream-count :initarg :pstream-count :accessor pstream-count :type integer :documentation "How many times a pstream was made of this pstream's source prior to this pstream. For example, if it was the first time `as-pstream' was called on the pattern, this will be 0.")
(beat :initform 0 :reader beat :type number :documentation "The number of beats that have elapsed since the start of the pstream.")
(history :type vector :documentation "The history of outputs yielded by the pstream.")
(history-number :initform 0 :documentation "The number of items in this pstream's history. Differs from the number slot in that all outputs are immediately included in its count.")
(start-beat :initarg :start-beat :initform nil :documentation "The beat number of the parent pstream when this pstream started.")
(future-number :initform 0 :documentation "The number of peeks into the future that have been made in the pstream. For example, if `peek' is used once, this would be 1. If `next' is called after that, future-number decreases back to 0.")
(future-beat :initform 0 :documentation "The current beat including all future outputs (the `beat' slot does not include peeked outputs)."))
(:documentation "\"Pattern stream\". Keeps track of the current state of a pattern in process of yielding its outputs."))
(defmethod initialize-instance :before ((pstream pstream) &key)
(with-slots (history) pstream
(setf history (make-array *max-pattern-yield-length* :initial-element nil))))
(defmethod initialize-instance :after ((pstream pstream) &key)
(set-parents pstream))
(defmethod print-object ((pstream pstream) stream)
(with-slots (number) pstream
(print-unreadable-object (pstream stream :type t)
(format stream "~S ~S" :number number))))
(defun pstream-p (object)
"True if OBJECT is a pstream.
See also: `pstream', `as-pstream'"
(typep object 'pstream))
(defmethod loop-p ((pstream pstream))
(if (slot-boundp pstream 'loop-p)
(slot-value pstream 'loop-p)
(loop-p (slot-value pstream 'source))))
(defmethod ended-p ((pstream pstream))
(with-slots (number future-number) pstream
(and (not (zerop (- number future-number)))
(eop-p (pstream-elt pstream -1)))))
(defmethod events-in-range ((pstream pstream) min max)
(while (and (<= (beat pstream) max)
(not (ended-p pstream)))
(let ((next (next pstream)))
(unless (typep next '(or null event))
(error "events-in-range can only be used on event streams."))))
(loop :for i :across (slot-value pstream 'history)
:if (and i
(>= (beat i) min)
(< (beat i) max))
:collect i
:if (or (eop-p i)
(>= (beat i) max))
:do (loop-finish)))
(defgeneric last-output (pstream)
(:documentation "Returns the last output yielded by PSTREAM.
Example:
;; (defparameter *pstr* (as-pstream (pseq '(1 2 3) 1)))
;; (next *pstr*) ;=> 1
;; (last-output *pstr*) ;=> 1
See also: `ended-p'"))
(defmethod last-output ((pstream pstream))
(with-slots (number future-number) pstream
(let ((idx (- number future-number)))
(when (plusp idx)
(pstream-elt pstream (- idx (if (ended-p pstream) 2 1)))))))
(defun value-remaining-p (value)
"True if VALUE represents that a pstream has outputs \"remaining\"; i.e. VALUE is a symbol (i.e. :inf), or a number greater than 0.
See also: `remaining-p', `decf-remaining'"
(typecase value
(null nil)
(symbol (eql value :inf))
(number (plusp value))
(otherwise nil)))
(defun remaining-p (pattern &optional (repeats-key 'repeats) (remaining-key 'current-repeats-remaining))
"True if PATTERN's REMAINING-KEY slot value represents outputs \"remaining\" (see `value-remaining-p'). If PATTERN's REMAINING-KEY slot is unbound or 0, and REPEATS-KEY is not nil, then it is automatically set to the `next' of PATTERN's REPEATS-KEY slot. Then if that new value is 0 or nil, remaining-p returns nil. Otherwise, :reset is returned as a generalized true value and to indicate that `next' was called on PATTERN's REPEATS-KEY slot.
See also: `value-remaining-p', `decf-remaining'"
(labels ((set-next ()
(setf (slot-value pattern remaining-key) (next (slot-value pattern repeats-key)))
(when (value-remaining-p (slot-value pattern remaining-key))
:reset)))
(if (not (slot-boundp pattern remaining-key))
(set-next)
(let ((rem-key (slot-value pattern remaining-key)))
(typecase rem-key
(null nil)
(symbol (eql rem-key :inf))
(number (if (plusp rem-key)
t
(set-next))) ; if it's already set to 0, it was decf'd to 0 in the pattern, so we get the next one. if the next is 0, THEN we return nil.
(otherwise nil))))))
(defun decf-remaining (pattern &optional (key 'current-repeats-remaining))
"Decrease PATTERN's KEY value.
See also: `remaining-p'"
(when (numberp (slot-value pattern key))
(decf (slot-value pattern key))))
(defmethod peek ((pstream pstream))
(with-slots (number future-number) pstream
(pstream-elt-future pstream (- number future-number))))
(defmethod peek ((pattern pattern))
(next (as-pstream pattern)))
(defmethod next ((pstream pstream))
;; fallback method; patterns should override their pstream subclasses with their own behaviors
nil)
(defvar *post-pattern-output-processors* (list 'remap-instrument-to-parameters)
"List of functions that are applied as the last step of pattern output generation. Each output yielded by an \"outermost\" pattern (i.e. one without a `pattern-parent') will be processed (along with the pstream as a second argument) through each function in this list, allowing for arbitrary transformations of the generated outputs. The return value of each function is used as the input to the next function, and the return value of the last function is used as the output yielded by the pattern.
This can be used, for example, to implement mappings from friendly instrument names to the full parameters needed to specify the instrument in question for backends such as MIDI which require it; in fact this feature is already implemented more conveniently with the setf-able `instrument-mapping' function.
See also: `*instrument-map*', `remap-instrument-to-parameters'")
(defvar *instrument-map* (make-hash-table :test #'equal)
"Hash table mapping instrument names (as symbols) to arbitrary parameter lists. Used by `remap-instrument-to-parameters' as part of post-pattern output processing. Any events whose :instrument is not found in this table will not be affected.
See also: `remap-instrument-to-parameters'")
(defun remap-instrument-to-parameters (output &optional pstream)
"Remap OUTPUT's instrument key to arbitrary parameters specified in `*instrument-map*'. If OUTPUT is not an event or the instrument is not found in the map, it is passed through unchanged.
See also: `instrument-mapping', `*instrument-map*', `*post-pattern-output-processors*'"
(declare (ignore pstream))
(unless (event-p output)
(return-from remap-instrument-to-parameters output))
(when-let ((mapping (gethash (event-value output :instrument) *instrument-map*)))
(etypecase mapping
(symbol
(setf (event-value output :instrument) mapping))
(list
(doplist (key value mapping)
(setf (event-value output key) value)))))
output)
(defun instrument-mapping (instrument)
"Get a mapping from INSTRUMENT (an instrument name as a string or symbol) to a plist of parameters which should be set in the event by `remap-instrument-to-parameters'.
See also: `remap-instrument-to-parameters', `*instrument-map*'"
(gethash instrument *instrument-map*))
(defun (setf instrument-mapping) (value instrument)
"Set a mapping from INSTRUMENT (an instrument name as a string or symbol) to a plist of parameters which will be set in the event by `remap-instrument-to-parameters'. Setting an instrument to nil with this function removes it from the map.
See also: `instrument-mapping', `remap-instrument-to-parameters', `*instrument-map*'"
(assert (or (typep value '(or symbol number))
(and (listp value)
(evenp (list-length value))))
(value)
"~S's VALUE argument must be a symbol, a number, or a plist; got ~S instead" 'instrument-mapping value)
(if value
(setf (gethash instrument *instrument-map*) value)
(remhash instrument *instrument-map*)))
(defmethod next :around ((pstream pstream))
(labels ((get-value-from-stack (pattern)
(with-slots (number pattern-stack) pattern
(if pattern-stack
(let* ((popped (pop pattern-stack))
(nv (next popped)))
(if (eop-p nv)
(get-value-from-stack pattern)
(progn
(push popped pattern-stack)
nv)))
(prog1
(let ((res (call-next-method)))
(typecase res
(pattern
(if (typep pattern '(or function t-pstream))
res
(progn ; if `next' returns a pattern, we push it to the pattern stack as a pstream
(let ((pstr (as-pstream res)))
(setf (slot-value pstr 'start-beat) (beat pattern))
(push pstr pattern-stack))
(get-value-from-stack pattern))))
(t res)))
(incf number))))))
(with-slots (number history history-number future-number) pstream
(let ((result (if (plusp future-number)
(let ((result (elt history (- number future-number))))
(decf future-number)
(when (event-p result)
(incf (slot-value pstream 'beat) (event-value result :delta)))
result)
(let ((result (restart-case
(get-value-from-stack pstream)
(yield-output (&optional (value 1))
:report (lambda (s) (format s "Yield an alternate output for ~S." pstream))
:interactive (lambda ()
(format *query-io* "~&Enter a form to yield: ")
(finish-output *query-io*)
(list (eval (read *query-io*))))
value))))
(when (event-p result)
(setf result (copy-event result))
(when (and (null (raw-event-value result :beat))
(null (slot-value pstream 'parent)))
(setf (beat result) (slot-value pstream 'future-beat)))
(incf (slot-value pstream 'beat) (event-value result :delta))
(incf (slot-value pstream 'future-beat) (event-value result :delta)))
(setf (elt history (mod history-number (length (slot-value pstream 'history)))) result)
(incf history-number)
result))))
(unless (pattern-parent pstream)
(dolist (proc *post-pattern-output-processors*)
(setf result (funcall proc result pstream))))
result))))
(defgeneric as-pstream (thing) ; FIX: add &key to allow for stuff like specifying the history length?
(:documentation "Return THING as a pstream object.
See also: `pattern-as-pstream'"))
(defun pattern-as-pstream (thing)
"Like `as-pstream', but only converts THING to a pstream if it is a pattern."
(if (typep thing 'pattern)
(as-pstream thing)
thing))
(defgeneric t-pstream-value (object)
(:documentation "The value that is yielded by the t-pstream."))
(defgeneric t-pstream-length (object)
(:documentation "The number of times to yield the value."))
(defclass t-pstream (pstream)
((value :initarg :value :initform nil :accessor t-pstream-value :documentation "The value that is yielded by the t-pstream.")
(length :initarg :length :initform 1 :accessor t-pstream-length :documentation "The number of times to yield the value."))
(:documentation "Pattern stream object that by default yields its value only once."))
(defun t-pstream (value &optional (length 1))
"Make a t-pstream object with the value VALUE."
(check-type length (or (integer 0) (eql :inf)))
(make-instance 't-pstream
:value value
:length length))
(defmethod print-object ((t-pstream t-pstream) stream)
(with-slots (value length) t-pstream
(print-unreadable-object (t-pstream stream :type t)
(format stream "~S ~S" value length))))
(defun t-pstream-p (object)
"True if OBJECT is a `t-pstream'.
See also: `t-pstream', `as-pstream'"
(typep object 't-pstream))
(defmethod as-pstream ((value t))
(t-pstream value))
(defmethod next ((t-pstream t-pstream))
(with-slots (value length number) t-pstream
(when (and (not (eql :inf length))
(>= number length))
(return-from next eop))
(if (functionp value)
(funcall value)
value)))
(defmethod as-pstream ((pattern pattern))
(let* ((class (class-of pattern))
(name (class-name class))
(slots (remove 'parent (mapcar #'closer-mop:slot-definition-name (closer-mop:class-slots class)))))
(apply #'make-instance
(pattern-pstream-class-name name)
(mapcan (fn (when (slot-boundp pattern _)
(let ((kw (make-keyword _)))
(list kw (funcall (if (member kw (list :length :repeats))
#'as-pstream
#'pattern-as-pstream)
(slot-value pattern _))))))
slots))))
(defmethod as-pstream :around ((object t))
(let ((pstream (call-next-method)))
(with-slots (pstream-count source) pstream
(setf pstream-count (if (slot-exists-p object 'pstream-count)
(slot-value object 'pstream-count)
0)
source object))
(when (slot-exists-p object 'pstream-count)
(incf (slot-value object 'pstream-count)))
pstream))
(defmethod as-pstream ((pstream pstream)) ; prevent pstreams from being "re-converted" to pstreams
pstream)
(define-condition pstream-out-of-range ()
((index :initarg :index :reader pstream-elt-index))
(:report (lambda (condition stream)
(format stream "The index ~D falls outside the scope of the pstream's history." (pstream-elt-index condition)))))
(defun pstream-elt-index-to-history-index (pstream index)
"Given INDEX, an absolute index into PSTREAM's history, return the actual index into the current recorded history of the pstream.
See also: `pstream-history-advance-by'"
(check-type index (integer 0))
(with-slots (history) pstream
(mod index (length history))))
(defun pstream-elt (pstream n)
"Get the Nth item in PSTREAM's history. For negative N, get the -Nth most recent item.
Example:
;; (let ((pstream (as-pstream (pseq '(1 2 3)))))
;; (next pstream) ;=> 1
;; (pstream-elt pstream 0) ;=> 1 ; first item in the pstream's history
;; (next pstream) ;=> 2
;; (pstream-elt pstream 1) ;=> 2 ; second item in the pstream's history
;; (pstream-elt pstream -1)) ;=> 2 ; most recent item in the pstream's history
See also: `pstream-elt-future', `phistory'"
(check-type n integer)
(unless (pstream-p pstream)
(return-from pstream-elt (pstream-elt (as-pstream pstream) n)))
(with-slots (history history-number) pstream
(let ((real-index (if (minusp n)
(+ history-number n)
n)))
(if (and (>= real-index (max 0 (- history-number (length history))))
(< real-index history-number))
(elt history (pstream-elt-index-to-history-index pstream real-index))
(error 'pstream-out-of-range :index n)))))
(defun pstream-history-advance-by (pstream index) ; FIX: add tests for this
"Convert a history index (i.e. a positive number provided to `pstream-elt-future') to the amount that the history must be advanced by.
If the provided index is before the earliest item in history, the result will be a negative number denoting how far beyond the earliest history the index is.
If the provided index is within the current history, the result will be zero.
If the provided index is in the future, the result will be a positive number denoting how far in the future it is.
See also: `pstream-elt-index-to-history-index'"
(check-type index (integer 0))
(with-slots (history history-number) pstream
(let ((history-length (length history)))
(if (< index (- history-number history-length))
(- history-number history-length)
(if (>= index history-number)
(- index (1- history-number))
0)))))
(defun pstream-elt-future (pstream n)
"Get the element N away from the most recent in PSTREAM's history. Unlike `pstream-elt', this function will automatically peek into the future for any positive N.
Example:
;; (let ((pstream (as-pstream (pseq '(1 2 3)))))
;; (pstream-elt-future pstream 0) ;=> 1
;; (next pstream) ;=> 1
;; (pstream-elt-future pstream 1) ;=> 2
;; (next pstream)) ;=> 2
See also: `pstream-elt', `phistory'"
(check-type n integer)
(unless (pstream-p pstream)
(return-from pstream-elt-future (pstream-elt-future (as-pstream pstream) n)))
(when (minusp n)
(return-from pstream-elt-future (pstream-elt pstream n)))
(with-slots (history history-number future-number) pstream
(let ((advance-by (pstream-history-advance-by pstream n)))
(when (or (minusp advance-by)
(> (+ future-number advance-by) (length history)))
;; the future and history are recorded to the same array.
;; since the array is of finite size, requesting more from the future than history is able to hold would result in the oldest elements of the future being overwritten with the newest, thus severing the timeline...
(error 'pstream-out-of-range :index n))
(let ((prev-future-number future-number))
(setf future-number 0) ; temporarily set it to 0 so the `next' method runs normally
(loop :repeat advance-by
:for next := (next pstream)
:if (event-p next)
:do (decf (slot-value pstream 'beat) (event-value next :delta)))
(setf future-number (+ prev-future-number advance-by))))
(let ((real-index (pstream-elt-index-to-history-index pstream n)))
(elt history real-index))))
;;; pbind
(defvar *pbind-special-init-keys* nil
"The list of special keys for pbind that alters it during its initialization.
See also: `define-pbind-special-init-key'")
(defvar *pbind-special-wrap-keys* nil
"The list of special keys for pbind that causes the pbind to be replaced by another pattern during its initialization.
See also: `define-pbind-special-wrap-key'")
(defvar *pbind-special-process-keys* nil
"The list of special keys for pbind that alter the outputs of the pbind.
See also: `define-pbind-special-process-key'")
(defclass pbind (pattern)
((pairs :initarg :pairs :initform nil :accessor pbind-pairs :documentation "The pattern pairs of the pbind; a plist mapping its keys to their values."))
(:documentation "Please refer to the `pbind' documentation."))
(defun pbind (&rest pairs)
"pbind yields events determined by its PAIRS, which are a list of keys and values. Each key corresponds to a key in the resulting events, and each value is treated as a pattern that is evaluated for each step of the pattern to generate the value for its key.
Example:
;; (next-n (pbind :foo (pseq '(1 2 3)) :bar :hello) 4)
;;
;; ;=> ((EVENT :FOO 1 :BAR :HELLO) (EVENT :FOO 2 :BAR :HELLO) (EVENT :FOO 3 :BAR :HELLO) EOP)
See also: `pmono', `pb'"
(assert (evenp (length pairs)) (pairs) "~S's PAIRS argument must be a list of key/value pairs." 'pbind)
(when (> (count :pdef (keys pairs)) 1)
(warn "More than one :pdef key detected in pbind."))
(let* ((res-pairs nil)
(pattern-chain nil)
(pattern (make-instance 'pbind)))
(doplist (key value pairs)
(when (pattern-p value)
(setf (slot-value value 'parent) pattern))
(cond ((position key *pbind-special-init-keys*)
(when-let ((result (funcall (getf *pbind-special-init-keys* key) value pattern)))
(appendf res-pairs result)))
((position key *pbind-special-wrap-keys*)
(unless (null res-pairs)
(setf (slot-value pattern 'pairs) res-pairs)
(setf res-pairs nil))
(unless (null pattern-chain)
(setf pattern (apply #'pchain (append pattern-chain (list pattern))))
(setf pattern-chain nil))
(setf pattern (funcall (getf *pbind-special-wrap-keys* key) value pattern)))
(t
(unless (typep pattern 'pbind)
(appendf pattern-chain (list pattern))
(setf pattern (make-instance 'pbind)))
(appendf res-pairs (list key (if (and (eql key :embed)
(typep value 'symbol))
(pdef value)
value))))))
(unless (null res-pairs)
(setf (slot-value pattern 'pairs) res-pairs))
(appendf pattern-chain (list pattern))
(unless (length= 1 pattern-chain)
(setf pattern (apply #'pchain pattern-chain)))
;; process quant keys.
(doplist (k v pairs)
(when (member k (list :quant :play-quant :end-quant))
(funcall (fdefinition (list 'setf (ensure-symbol k 'cl-patterns))) (next v) pattern)))
;; process :pdef key.
(when-let ((pdef-name (getf pairs :pdef)))
(pdef pdef-name pattern))
pattern))
(pushnew 'pbind *patterns*)
(setf (documentation 'pbind 'type) (documentation 'pbind 'function))
(defmethod print-object ((pbind pbind) stream)
(format stream "(~S~{ ~S ~S~})" 'pbind (slot-value pbind 'pairs)))
(defmethod %pattern-children ((pbind pbind))
(mapcan (lambda (slot)
(let ((slot-name (closer-mop:slot-definition-name slot)))
(copy-list (ensure-list
(if (eql slot-name 'pairs)
(loop :for (k v) :on (slot-value pbind slot-name) :by #'cddr :collect v)
(slot-value pbind slot-name))))))
(closer-mop:class-direct-slots (find-class 'pbind))))
(defmethod keys ((pbind pbind))
(keys (slot-value pbind 'pairs)))
(defvar *pattern-function-translations* nil
"The list of names of functions and the forms they will be translated to in `pb' and other pattern macros.
See also: `define-pattern-function-translation'")
(defmacro define-pattern-function-translation (function pattern)
"Define a translation from FUNCTION to PATTERN in `pb'."
`(setf (getf *pattern-function-translations* ',function) ',pattern))
(define-pattern-function-translation + p+)
(define-pattern-function-translation - p-)
(define-pattern-function-translation * p*)
(define-pattern-function-translation / p/)
(define-pattern-function-translation round (pnary 'round))
(defun pattern-translate-sexp (sexp)
"Translate SEXP to the equivalent pattern as per `*pattern-function-translations*', or pass it through unchanged if there is no translation.
See also: `pb-translate-body-functions'"
(typecase sexp
(null sexp)
(atom sexp)
(list (let* ((first (car sexp))
(rest (cdr sexp))
(translated-p (getf *pattern-function-translations* first))
(head (list (if (find-if (fn (typep _ '(or pattern list))) rest)
(or translated-p first)
first))))
`(,@head ,@(if translated-p
(mapcar #'pattern-translate-sexp rest)
rest))))))
(defun pb-translate-body-functions (body)
"Translate functions in BODY to their equivalent pattern as per `*pattern-function-translations*'.
See also: `pattern-translate-sexp'"
(loop :for (k v) :on body :by #'cddr
:collect k
:collect (pattern-translate-sexp v)))
;; FIX: allow keys to be lists, in which case results are destructured, i.e. (pb :blah (list :foo :bar) (pcycles (a 1!4))) results in four (EVENT :FOO 1 :DUR 1/4)
(defmacro pb (name &body pairs)
"pb is a convenience macro, wrapping the functionality of `pbind' and `pdef' while also providing additional syntax sugar. NAME is the name of the pattern (same as pbind's :pdef key or `pdef' itself), and PAIRS is the same as in regular pbind. If PAIRS is only one element, pb operates like `pdef', otherwise it operates like `pbind'.
The expressions in PAIRS are also automatically translated to equivalent patterns if applicable; for example:
;; (pb :foo :bar (+ (pseries) (pseq (list -1 0 1))))
...is the same as:
;; (pb :foo :bar (p+ (pseries) (pseq (list -1 0 1))))
See also: `pbind', `pdef'"
(if (length= 1 pairs)
`(pdef ,name ,@pairs)
`(pdef ,name (pbind ,@(pb-translate-body-functions pairs)))))
(pushnew 'pb *patterns*)
(defclass pbind-pstream (pbind pstream)
()
(:documentation "pstream for `pbind'"))
(defmethod print-object ((pbind pbind-pstream) stream)
(print-unreadable-object (pbind stream :type t)
(format stream "~{~S ~S~^ ~}" (slot-value pbind 'pairs))))
(defmethod as-pstream ((pbind pbind))
(let ((name (class-name (class-of pbind)))
(slots (mapcar #'closer-mop:slot-definition-name (closer-mop:class-slots (class-of pbind)))))
(apply #'make-instance
(pattern-pstream-class-name name)
(loop :for slot :in slots
:for slot-kw := (make-keyword slot)
:for bound := (slot-boundp pbind slot)
:if bound
:collect slot-kw
:if (eql :pairs slot-kw)
:collect (mapcar 'pattern-as-pstream (slot-value pbind 'pairs))
:if (and bound (not (eql :pairs slot-kw)))
:collect (slot-value pbind slot)))))
(defmacro define-pbind-special-init-key (key &body body)
"Define a special key for pbind that alters the pbind during its initialization, either by embedding a plist into its pattern-pairs or in another way. These functions are called once, when the pbind is created, and must return a plist if the key should embed values into the pbind pairs, or NIL if it should not."
`(setf (getf *pbind-special-init-keys* ,(make-keyword key))
(lambda (value pattern)
(declare (ignorable value pattern))
,@body)))
;; (define-pbind-special-init-key inst ; FIX: this should be part of event so it will affect the event as well. maybe just rename to something else?
;; (list :instrument value))
(define-pbind-special-init-key loop-p
(setf (loop-p pattern) value)
nil)
(defmacro define-pbind-special-wrap-key (key &body body)
"Define a special key for pbind that replaces the pbind with another pattern during the pbind's initialization. Each encapsulation key is run once on the pbind after it has been initialized, altering the type of pattern returned if the return value of the function is non-NIL."
`(setf (getf *pbind-special-wrap-keys* ,(make-keyword key))
(lambda (value pattern)
(declare (ignorable value pattern))
,@body)))
(define-pbind-special-wrap-key pfor
(pfor pattern value))
(define-pbind-special-wrap-key parp ; deprecated
(parp pattern value))
(define-pbind-special-wrap-key pfin
(pfin pattern value))
(define-pbind-special-wrap-key pfindur
(pfindur pattern value))
(define-pbind-special-wrap-key psync
(destructuring-bind (quant &optional maxdur) (ensure-list value)
(psync pattern quant (or maxdur quant))))
(define-pbind-special-wrap-key pdurstutter
(pdurstutter pattern value))
(define-pbind-special-wrap-key pr
(pr pattern value))
(define-pbind-special-wrap-key pn
(pn pattern value))
(define-pbind-special-wrap-key ptrace
(if value
(if (eql t value)
(ptrace pattern)
(pchain pattern
(pbind :- (ptrace value))))
pattern))
(define-pbind-special-wrap-key pmeta
(if (eql t value)
(pmeta pattern)
pattern))
(define-pbind-special-wrap-key pchain ; basically the same as the :embed key, but we have it anyway for convenience.
(pchain pattern value))
(define-pbind-special-wrap-key pparchain
(pparchain pattern value))
(defmacro define-pbind-special-process-key (key &body body)
"Define a special key for pbind that alters the pattern in a nonstandard way. These functions are called for each event created by the pbind and must return an event if the key should embed values into the event stream, or `eop' if the pstream should end."
`(setf (getf *pbind-special-process-keys* ,(make-keyword key))
(lambda (value)
,@body)))
(define-pbind-special-process-key embed
value)
(defmethod next ((pbind pbind-pstream))
(labels ((accumulator (pairs)
(let ((key (car pairs))
(val (cadr pairs)))
(when (and (pstream-p val)
(null (slot-value val 'start-beat)))
(setf (slot-value val 'start-beat) (beat pbind)))
(let ((next-val (next val)))
(when (eop-p next-val)
(return-from accumulator eop))
(if (position key (keys *pbind-special-process-keys*))
(setf *event* (combine-events *event*
(funcall (getf *pbind-special-process-keys* key) next-val)))
(setf (event-value *event* key) next-val))
(if-let ((cddr (cddr pairs)))
(accumulator cddr)
*event*)))))
(let ((*event* (make-default-event)))
(when (eop-p *event*)
(return-from next eop))
(setf (slot-value *event* '%beat) (+ (or (slot-value pbind 'start-beat) 0) (beat pbind)))
(if-let ((pairs (slot-value pbind 'pairs)))
(accumulator pairs)
*event*))))
(defmethod as-pstream ((pbind pbind-pstream))
pbind)
;;; prest
;; FIX: allow `prest' to be used as an event on its own (it should parse as (event :type :rest :dur VALUE))