@kairotic/app 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +9 -2
  2. package/index.html +1101 -0
  3. package/kairotic/api.cljs +362 -0
  4. package/kairotic/assistant.cljs +505 -0
  5. package/kairotic/backends/gun-backend.js +371 -0
  6. package/kairotic/canvas.cljs +751 -0
  7. package/kairotic/code.cljs +108 -0
  8. package/kairotic/components.cljs +838 -0
  9. package/kairotic/core.cljs +96 -0
  10. package/kairotic/corefns.cljs +473 -0
  11. package/kairotic/docs.mjs +2 -0
  12. package/kairotic/engine.cljs +482 -0
  13. package/kairotic/examples.mjs +96 -0
  14. package/kairotic/faust.cljs +225 -0
  15. package/kairotic/help.cljs +1036 -0
  16. package/kairotic/hiccup.cljs +566 -0
  17. package/kairotic/input.cljs +271 -0
  18. package/kairotic/kfile.mjs +138 -0
  19. package/kairotic/library.cljs +214 -0
  20. package/kairotic/links.cljs +41 -0
  21. package/kairotic/mt.cljs +1604 -0
  22. package/kairotic/mtboxes.cljs +276 -0
  23. package/kairotic/packages/analysis.mjs +64 -0
  24. package/kairotic/packages/controls.mjs +28 -0
  25. package/kairotic/packages/data.mjs +22 -0
  26. package/kairotic/packages/faust-units/cmaes.mjs +82 -0
  27. package/kairotic/packages/faust-units/graph.mjs +212 -0
  28. package/kairotic/packages/faust-units/listen.mjs +125 -0
  29. package/kairotic/packages/faust-units/notation.mjs +139 -0
  30. package/kairotic/packages/faust-units/parse.mjs +439 -0
  31. package/kairotic/packages/faust-units/recipe.mjs +195 -0
  32. package/kairotic/packages/faust-units/render.mjs +69 -0
  33. package/kairotic/packages/faust-units/units.mjs +130 -0
  34. package/kairotic/packages/faust-units/view.mjs +353 -0
  35. package/kairotic/packages/faust-units.mjs +9 -0
  36. package/kairotic/packages/io.mjs +58 -0
  37. package/kairotic/packages/net.mjs +28 -0
  38. package/kairotic/packages/patterns.mjs +34 -0
  39. package/kairotic/packages/spatial.mjs +22 -0
  40. package/kairotic/packages/spectral/shift.mjs +169 -0
  41. package/kairotic/packages/spectral.mjs +16 -0
  42. package/kairotic/packages/synth.mjs +28 -0
  43. package/kairotic/packages/theory/counterpoint.mjs +798 -0
  44. package/kairotic/packages/theory/mirror.mjs +221 -0
  45. package/kairotic/packages/theory.mjs +46 -0
  46. package/kairotic/patterns.cljs +538 -0
  47. package/kairotic/presets.cljs +227 -0
  48. package/kairotic/quantize.cljs +782 -0
  49. package/kairotic/record.cljs +169 -0
  50. package/kairotic/release.cljs +90 -0
  51. package/kairotic/ring.cljs +129 -0
  52. package/kairotic/ringaudio.cljs +232 -0
  53. package/kairotic/ringcore.mjs +270 -0
  54. package/kairotic/score.cljs +176 -0
  55. package/kairotic/shapes.cljs +283 -0
  56. package/kairotic/signal.cljs +327 -0
  57. package/kairotic/sounds.cljs +565 -0
  58. package/kairotic/sounds.mjs +108 -0
  59. package/kairotic/span.cljs +129 -0
  60. package/kairotic/spell.cljs +281 -0
  61. package/kairotic/structure.cljs +145 -0
  62. package/kairotic/talk.cljs +115 -0
  63. package/kairotic/tempo.cljs +226 -0
  64. package/kairotic/treecanvas.cljs +299 -0
  65. package/kairotic/tutorials.mjs +1283 -0
  66. package/kairotic/vendor/codemirror.mjs +23 -0
  67. package/package.json +23 -4
  68. package/page/00-work.cljs +862 -0
  69. package/page/01-commands.cljs +1219 -0
  70. package/page/02-patch-view.cljs +1051 -0
  71. package/page/03-history-view.cljs +481 -0
  72. package/page/04-panels.cljs +448 -0
  73. package/page/05-gestures.cljs +1247 -0
  74. package/page/06-connection.cljs +219 -0
  75. package/page/07-claude.cljs +430 -0
  76. package/page/08-sessions.cljs +423 -0
  77. package/page/09-learn.cljs +602 -0
  78. package/page/10-embed.cljs +469 -0
  79. package/page/11-startup.cljs +61 -0
  80. package/page/12-feedback.cljs +172 -0
  81. package/page/13-perform.cljs +325 -0
  82. package/page/14-editor.cljs +656 -0
  83. package/page/15-presets.cljs +230 -0
  84. package/page/16-release.cljs +242 -0
  85. package/page/17-sounds.cljs +147 -0
  86. package/page/18-lines.cljs +594 -0
  87. package/page/19-files.cljs +247 -0
  88. package/page/19-html.cljs +152 -0
  89. package/page/20-talk.cljs +527 -0
  90. package/page/21-net.cljs +110 -0
  91. package/page/22-learn.cljs +303 -0
  92. package/page/23-ids.cljs +233 -0
  93. package/page/24-clipboard.cljs +136 -0
  94. package/page/25-tidy.cljs +74 -0
  95. package/page/26-probes.cljs +111 -0
  96. package/sources.mjs +2 -0
@@ -0,0 +1,169 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · record
3
+ ;; Any stream of numbers written into a canvas (or a freqt) as strokes over time: an envelope from
4
+ ;; snapshot~, a descriptor from features~, a gesture on a knob, a position. Then it can be edited like
5
+ ;; any drawing and read again with reader~, as an automation.
6
+ ;;
7
+ ;; record [lo hi] [log] [tolerance]
8
+ ;; left: numbers; rec starts a take from 0 (its first write clears the buffer), stop ends it;
9
+ ;; rec t (a msg :rec 4, or [:rec 4]) records from t on: what was there before t stays, from t
10
+ ;; on it is replaced (punch-in); ovr t (msg :ovr 4) overwrites only what the take covers, from t
11
+ ;; to where it stops, and keeps what comes after (punch-in/out); ovr alone, from 0
12
+ ;; right: a bang ends the stroke that is being drawn; the next number begins another
13
+ ;; out: edits for the canvas (or freqt) on its inlet
14
+ ;;
15
+ ;; Senders such as snapshot~ only send what changed, so a value holds until the next one: the stroke is a
16
+ ;; staircase (each new value starts where the last one held), simplified within `tolerance` (in the units
17
+ ;; of the values; 1% of their range without it). Time is seconds from rec (a freqt reads them as beats:
18
+ ;; one a second, at 60). With lo hi the Y axis of a canvas is set to them (log with `log`); without them it
19
+ ;; follows the values; X follows the take. A freqt keeps its own axes and takes only values from 1 to
20
+ ;; 30000 (Hz). It writes at most every 2 seconds, each write one event of the history.
21
+
22
+ (ns kairotic.record
23
+ (:require [kairotic.components :as comp]))
24
+
25
+ (def flush-every 2)
26
+ (def max-points 2000)
27
+
28
+ (defn r4 [x] (/ (js/Math.round (* x 10000)) 10000))
29
+
30
+ (defn simplify
31
+ "Ramer–Douglas–Peucker for a time series: keeps the points whose value is more than eps away from the
32
+ line between the ones kept around them (the error measured in value, not in a mixed distance)."
33
+ [pts eps]
34
+ (if (< (count pts) 3)
35
+ (vec pts)
36
+ (let [pts (vec pts)
37
+ keep? (fn keep? [a b acc]
38
+ (if (<= (- b a) 1)
39
+ acc
40
+ (let [[ta va] (nth pts a) [tb vb] (nth pts b)
41
+ dt (- tb ta)
42
+ err (fn [i] (let [[t v] (nth pts i)
43
+ line (if (zero? dt) va (+ va (* (- vb va) (/ (- t ta) dt))))]
44
+ (js/Math.abs (- v line))))
45
+ [i e] (reduce (fn [[bi be] i] (let [x (err i)] (if (> x be) [i x] [bi be]))) [a -1] (range (inc a) b))]
46
+ (if (> e eps) (keep? i b (keep? a i (conj acc i))) acc))))
47
+ idx (sort (keep? 0 (dec (count pts)) #{0 (dec (count pts))}))]
48
+ (mapv (fn [i] (nth pts i)) idx))))
49
+
50
+ (defn args-of
51
+ "lo hi tolerance (numbers in that order) and the word log, from the raw words of the box."
52
+ [args]
53
+ (let [ns (filterv number? args)]
54
+ {:lo (get ns 0) :hi (get ns 1) :tol (get ns 2) :log (boolean (some #{:log} args))}))
55
+
56
+ (defn tolerance [state]
57
+ (or (:tol state)
58
+ (let [lo (or (:lo state) (:min state)) hi (or (:hi state) (:max state))]
59
+ (if (and lo hi (> hi lo)) (* 0.01 (- hi lo)) 0))))
60
+
61
+ (defn axes
62
+ "The axes a canvas should have now, as edits (a freqt leaves them out)."
63
+ [state]
64
+ (let [t1 (max 1 (:t-end state 0))
65
+ ;; a take from t keeps the Y axis the canvas had (what is before t was drawn on it), unless lo hi
66
+ lo (or (:lo state) (when-not (:from state) (:min state))) hi (or (:hi state) (when-not (:from state) (:max state)))
67
+ [lo hi] (cond (and lo hi (< lo hi)) (if (:lo state) [lo hi] (let [m (* 0.05 (- hi lo))] [(- lo m) (+ hi m)]))
68
+ (and lo hi) [(- lo 0.5) (+ hi 0.5)]
69
+ :else nil)]
70
+ ;; over a take (ovr) what comes after it stays: X is left as it was
71
+ (cond-> (if (:ovr state) [] [[:axis :x 0 (r4 t1)]])
72
+ lo (conj (cond-> [:axis :y (r4 lo) (r4 hi)] (and (:log state) (pos? lo)) (conj :log))))))
73
+
74
+ (defn stroke-edit [state [id pts]]
75
+ (let [ps (simplify pts (tolerance state))
76
+ ps (if (> (count ps) max-points) (vec (take-nth (js/Math.ceil (/ (count ps) max-points)) ps)) ps)]
77
+ (when (>= (count ps) 2) [:stroke id (mapv (fn [[t v]] [(r4 t) (r4 v)]) ps)])))
78
+
79
+ (defn write-out
80
+ "[state edit later]: the strokes that changed since the last write, with the axes, as one [:batch …],
81
+ at most every flush-every seconds (force: now)."
82
+ [state at force]
83
+ (let [dirty (:dirty state)]
84
+ (cond
85
+ (empty? dirty) [state nil nil]
86
+ (or force (nil? (:sent state)) (>= (- at (:sent state)) flush-every))
87
+ (let [strokes (keep (fn [id] (stroke-edit state [id (get-in state [:strokes id])])) (sort-by name dirty))]
88
+ ;; a stroke of one point waits for the next one (nothing is written, nothing is marked as sent)
89
+ (if (seq strokes)
90
+ [(cond-> (assoc state :dirty #{} :sent at :pending false :fresh false)
91
+ (:ovr state) (assoc :cut-from (:t-end state)))
92
+ [:batch (vec (concat (cond
93
+ ;; ovr: what the take covered since the last write goes first (strokes kept
94
+ ;; from before end there, those after begin where the take stops)
95
+ (:ovr state) [[:cut (:cut-from state) (:t-end state)]]
96
+ (:fresh state) [(if (:from state) [:cut (:from state)] [:clear])])
97
+ (axes state) strokes))]
98
+ nil]
99
+ [state nil nil]))
100
+ (:pending state) [state nil nil]
101
+ :else [(assoc state :pending true) nil [(+ (:sent state) flush-every) 0 [:flush]]])))
102
+
103
+ (defn add-value
104
+ "A value v at instant at: it continues the stroke being drawn (a step from where the last value held),
105
+ or begins one."
106
+ [state v at]
107
+ (let [t (- at (:t0 state))
108
+ id (:cur state)
109
+ ;; ids of a take from t carry the take, so they do not replace strokes kept from an earlier one
110
+ state (if id state (-> state (update :n inc)
111
+ (as-> s (assoc s :cur (keyword (str "r" (when (:from s) (str (:take s) "-")) (:n s)))))))
112
+ id (:cur state)
113
+ pts (get-in state [:strokes id] [])
114
+ [_ lv] (peek pts)
115
+ pts (cond-> pts (and lv (not= lv v)) (conj [t lv]) true (conj [t v]))]
116
+ (-> state
117
+ (assoc-in [:strokes id] pts)
118
+ (update :dirty conj id)
119
+ (assoc :t-end t)
120
+ (update :min (fn [m] (if (some? m) (min m v) v)))
121
+ (update :max (fn [m] (if (some? m) (max m v) v))))))
122
+
123
+ (defn end-stroke
124
+ "The stroke being drawn ends: held until now, so a value that never changed still has a length."
125
+ [state at]
126
+ (if-let [id (:cur state)]
127
+ (let [t (- at (:t0 state)) [lt lv] (peek (get-in state [:strokes id]))]
128
+ (cond-> (dissoc state :cur)
129
+ (and lv (> t lt)) (-> (update-in [:strokes id] conj [t lv]) (update :dirty conj id) (assoc :t-end t))))
130
+ state))
131
+
132
+ (defn result [[st edit later]]
133
+ (cond-> {:state st :show (select-keys st [:on :n])}
134
+ edit (assoc :out [[0 edit]])
135
+ later (assoc :later [later])))
136
+
137
+ (comp/define! "record"
138
+ {:doc "Writes any stream of numbers into a canvas (or a freqt) as strokes over time: an envelope (snapshot~ 50 rms), a descriptor (features~), a knob, a position. :rec starts a take from 0 (its first write clears the buffer); :rec t (msg :rec 4) records from t seconds on, keeping what is before t and replacing what is after (punch-in); :ovr t (msg :ovr 4) overwrites only what the take covers, from t to where it stops, keeping what comes after (punch-in/out); :stop ends it; a bang on the right ends a stroke, and the next number begins another. A value holds until the next one (snapshot~ sends only what changed), simplified within tolerance (1% of the range without it). Time in seconds from rec. With lo hi the Y axis of a canvas is set to them (log with log); without them it follows the values. It writes at most every 2 seconds, each write one event of the history; then reader~ reads it back as an automation."
139
+ :usage "record [lo hi] [log] [tolerance]"
140
+ :license "MPL-2.0"
141
+ :io [2 1]
142
+ :size [124 30]
143
+ :receive (fn [{:keys [inlet value state args at]}]
144
+ (let [state (or state {})]
145
+ (cond
146
+ (or (#{:rec :ovr} value) (and (vector? value) (#{:rec :ovr} (first value))))
147
+ (let [{:keys [lo hi tol log]} (args-of args)
148
+ ovr (or (= value :ovr) (and (vector? value) (= :ovr (first value))))
149
+ from (or (when (vector? value) (let [x (second value)] (when (and (number? x) (>= x 0)) x)))
150
+ (when ovr 0))]
151
+ {:state (cond-> {:on true :t0 (- at (or from 0)) :lo lo :hi hi :tol tol :log log :n 0 :strokes {}
152
+ :dirty #{} :fresh true}
153
+ from (assoc :from from :take (js/Math.round (* 1000 at)))
154
+ ovr (assoc :ovr true :cut-from from))
155
+ :show {:on true :n 0}})
156
+ (not (:on state)) {}
157
+ (= value :stop)
158
+ (let [[st edit _] (write-out (end-stroke state at) at true)]
159
+ (cond-> {:state (assoc st :on false) :show {:on false :n (:n st)}}
160
+ edit (assoc :out [[0 edit]])))
161
+ (= value [:flush]) (result (write-out (assoc state :pending false) at false))
162
+ (= inlet 1) (result (write-out (end-stroke state at) at false))
163
+ (and (number? value) (js/isFinite value)) (result (write-out (add-value state value at) at false))
164
+ :else {})))
165
+ :derive (fn [{:keys [shown]}]
166
+ {:label (str (if (:on shown) "● recording · " "record · ") (or (:n shown) 0)
167
+ (if (= 1 (:n shown)) " stroke" " strokes"))})
168
+ :view [[:rect {:x 2 :y 2 :w 120 :h 26 :r 3 :stroke :grid :fill :bg}]
169
+ [:text {:x 8 :y 19 :size 10 :fill :soft} :$label]]})
@@ -0,0 +1,90 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · release (issue #45)
3
+ ;; A release is a compact history: one point per keyframe, each written as the changes from the one before,
4
+ ;; ending at the work as it is. Forgetting points of a history squashes them the same way. Both need the
5
+ ;; changes that turn one patch into another, as events of the history: patch-diff. And presets that
6
+ ;; travel with the patch (in its EDN, in links and embeds) keep only what changes between their keyframes:
7
+ ;; stored-presets.
8
+ ;;
9
+ ;; Pure: the page reads and writes the history (app/page/16-release.cljs).
10
+
11
+ (ns kairotic.release
12
+ (:require [clojure.string :as str]))
13
+
14
+ ;; ───────── the changes from one patch to another ─────────
15
+
16
+ (def box-keys
17
+ "What a box keeps besides its text and place, and the event that sets each (nil removes it)."
18
+ [:present :view :size :recipe])
19
+
20
+ (defn- set-ev [k id v]
21
+ (case k
22
+ :present (if v (into [:present id] v) [:present id nil])
23
+ :view [:view id v]
24
+ :size (if v (into [:size id] v) [:size id nil])
25
+ :recipe [:recipe id v]))
26
+
27
+ (defn patch-diff
28
+ "The events that turn patch p into patch q (top level; a sub-patch that changed is written whole, as the
29
+ data of its box). Applying them in order, with the step of the history, gives q."
30
+ [p q]
31
+ (let [pb (:boxes p) qb (:boxes q)
32
+ gone (sort (remove (fn [id] (contains? qb id)) (keys pb)))
33
+ lines-p (set (:lines p)) lines-q (set (:lines q))
34
+ ;; lines that a deleted box takes with it are not disconnected again
35
+ alive? (fn [[a _ b _]] (and (contains? qb a) (contains? qb b)))
36
+ ;; the order of lines is the order messages fan out in: kept as it is in q
37
+ kept (filter (fn [l] (and (contains? lines-q l) (alive? l))) (:lines p))
38
+ in-order? (= (vec (concat kept (remove lines-p (:lines q)))) (vec (:lines q)))
39
+ old-lines (if in-order? (remove lines-q (:lines p)) (:lines p))
40
+ new-lines (if in-order? (remove lines-p (:lines q)) (:lines q))]
41
+ (vec
42
+ (concat
43
+ (for [id gone] [:delete id])
44
+ (mapcat
45
+ (fn [[id b]]
46
+ (let [a (get pb id)
47
+ new? (or (nil? a) (not (contains? pb id)))]
48
+ (concat
49
+ (cond new? [[:box id (:text b) (:x b) (:y b)]]
50
+ :else (concat (when (not= (:text a) (:text b)) [[:text id (:text b)]])
51
+ (when (or (not= (:x a) (:x b)) (not= (:y a) (:y b))) [[:move id (:x b) (:y b)]])))
52
+ (for [k box-keys :when (not= (get a k) (get b k)) :when (or (not new?) (some? (get b k)))]
53
+ (set-ev k id (get b k)))
54
+ (when (and (not= (:data a) (:data b)) (or (not new?) (some? (:data b))))
55
+ [[:data id (:data b)]]))))
56
+ (sort-by key qb))
57
+ (for [l old-lines :when (alive? l)] (into [:disconnect] l))
58
+ (for [l new-lines] (into [:connect] l))))))
59
+
60
+ (defn as-event
61
+ "Several events as one event of the history: nothing, the event itself, or a [:batch …]."
62
+ [evs]
63
+ (case (count evs) 0 nil 1 (first evs) [:batch (vec evs)]))
64
+
65
+ ;; ───────── presets that travel with the patch ─────────
66
+
67
+ (defn stored-presets
68
+ "Keyframes as presets a box can keep in its data: [{:label :kind :texts {id text}}], where :texts holds only
69
+ the boxes whose text is not the same in all of them (with a single keyframe, every box). `kfs` is
70
+ [{:label :kind :config {id text}}]."
71
+ [kfs]
72
+ (let [cfgs (map :config kfs)
73
+ ids (distinct (mapcat keys cfgs))
74
+ changing (if (< (count kfs) 2)
75
+ (set ids)
76
+ (set (filter (fn [id] (not (apply = (map (fn [c] (get c id)) cfgs)))) ids)))]
77
+ (vec (for [{:keys [label kind config]} kfs]
78
+ (cond-> {:kind (or kind :snapshot)
79
+ :texts (into (sorted-map) (filter (fn [[id _]] (changing id)) config))}
80
+ (seq (str label)) (assoc :label (str label)))))))
81
+
82
+ (defn sane-presets
83
+ "Stored presets as they may arrive from anyone (a link, a room): only labels, kinds and texts."
84
+ [x]
85
+ (if (sequential? x)
86
+ (vec (for [p x :when (and (map? p) (map? (:texts p)))]
87
+ (cond-> {:kind (if (keyword? (:kind p)) (:kind p) :snapshot)
88
+ :texts (into (sorted-map) (for [[k v] (:texts p) :when (and (keyword? k) (string? v))] [k v]))}
89
+ (string? (:label p)) (assoc :label (:label p)))))
90
+ []))
@@ -0,0 +1,129 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · ring and writer: a span of time for messages and the heads that write it (discussion "Heads on a span
3
+ ;; of time"; Studies 44 and 47). The model is kairotic.span; reader reads a ring (components.cljs).
4
+ ;;
5
+ ;; ring [seconds]
6
+ ;; left: any value, written where its time is (its implicit write head, a tape head: what is older than one
7
+ ;; turn is gone); a writer's edits ([:write p v mode], [:cut a b], [:erase]); :clear (empty, its time
8
+ ;; starts again at the next message); [:data] → what it keeps, on the left
9
+ ;; right outlet: the buffer, for a reader or a writer (on their right inlet); :start goes out on it when the
10
+ ;; ring's time starts, so a reader given a d begins to follow
11
+ ;;
12
+ ;; writer [ovr|mix] [jump s] [norm]
13
+ ;; left: what is written where the writer is; :rec t / :ovr t (msg :rec 2) send it to t, moving on at speed 1
14
+ ;; and replacing what it passes (:rec on a ring also erases everything, as rec t cuts what is after t);
15
+ ;; :stop holds it where it is
16
+ ;; middle: the buffer (a ring's right outlet), to know its length
17
+ ;; right: a position (seconds of the span, or 0…1 with norm), from any source — a ramp, a counter, a
18
+ ;; phasor~ through snapshot~. Moving, with ovr (the default) it erases what it passes; a move larger than
19
+ ;; its jump is a seek, which erases nothing between
20
+ ;; out: edits for the ring (its left inlet). Without a position, it writes where the ring's head is
21
+
22
+ (ns kairotic.ring
23
+ (:require [kairotic.components :as comp]
24
+ [kairotic.span :as span]))
25
+
26
+ (def tick 0.05)
27
+
28
+ (defn- after-word
29
+ "The number after word k in the raw args (reader d 1 → 1)."
30
+ [args k]
31
+ (let [x (second (drop-while #(not= k %) args))] (when (number? x) x)))
32
+
33
+ ;; ───────── ring ─────────
34
+
35
+ (defn- summary [r at]
36
+ {:dur (:dur r) :n (count (span/alive r at)) :on (boolean (:t0 r))
37
+ :p (when-let [h (span/head r at)] (span/wrap r h))})
38
+
39
+ (defn ring-receive [{:keys [state args value at]}]
40
+ (let [dur (or (comp/num-of (first args)) 8)
41
+ r (assoc (or state (span/ring dur)) :dur dur)
42
+ done (fn [r2]
43
+ (cond-> {:state r2 :show (summary r2 at)}
44
+ ;; its time starts now: the readers on its buffer are told
45
+ (and (nil? (:t0 r)) (:t0 r2)) (assoc :out [[1 :start]])))]
46
+ (cond
47
+ (nil? value) {}
48
+ (= value :clear) {:state (span/ring dur) :show (summary (span/ring dur) at)}
49
+ (and (vector? value) (= :write (first value)))
50
+ (let [[_ p v mode] value] (done (span/write r at p v (or mode :mix))))
51
+ (and (vector? value) (= :cut (first value)))
52
+ (let [[_ a b] value] {:state (span/cut r at a b) :show (summary r at)})
53
+ (= value [:erase]) {:state (span/erase r) :show (summary (span/erase r) at)}
54
+ (= value [:data])
55
+ {:out [[0 {:dur dur :events (mapv (fn [e] [(span/wrap r (:t e)) (:v e)]) (span/alive r at))}]]}
56
+ :else (done (span/write r at value)))))
57
+
58
+ (comp/define! "ring"
59
+ {:doc "A span of time for messages: it keeps what reached it in the last seconds (8 by default), each at its time. Its time starts at its first message; its write head goes round as a tape head, so what is older than one turn is gone. Its right outlet is the buffer for a reader (d behind, then a speed: a canon, a delay; or at a position from any source) and for a writer (several heads, anywhere, at any speed). :clear empties it, and its time starts again."
60
+ :usage "ring [seconds]"
61
+ :license "MPL-2.0"
62
+ :io [1 2]
63
+ :size [124 30]
64
+ :receive ring-receive
65
+ ;; its length from its text (what it shows comes only with its first message)
66
+ :derive (fn [{:keys [shown args]}]
67
+ {:label (str "ring " (comp/nice (or (comp/num-of (first args)) 8)) " s · " (or (:n shown) 0) " kept")})
68
+ :view [[:rect {:x 2 :y 2 :w 120 :h 26 :r 13 :stroke :grid :fill :bg}]
69
+ [:text {:x 10 :y 19 :size 10 :fill :soft} :$label]]})
70
+
71
+ ;; ───────── writer ─────────
72
+
73
+ (defn writer-args [args]
74
+ {:mode (if (some #{:mix} args) :mix :ovr)
75
+ :jump (or (after-word args :jump) 0.5)
76
+ :norm (boolean (some #{:norm} args))})
77
+
78
+ (defn- clock-at [{:keys [clock]} at] (when clock (+ (:p clock) (- at (:at clock)))))
79
+
80
+ (defn writer-receive [{:keys [state args inlet value at buffer]}]
81
+ (let [{:keys [mode jump norm]} (writer-args args)
82
+ st (or state {})
83
+ l (when (span/ring? buffer) (:dur buffer))
84
+ gen (inc (:gen st 0))
85
+ cue (fn [kind t]
86
+ (let [t (or t 0)]
87
+ {:state (assoc st :clock {:at at :p t} :p t :gen gen)
88
+ :out (if (= kind :rec) [[0 [:erase]]] [])
89
+ :later [[(+ at tick) 0 [:tick gen]]]}))]
90
+ (cond
91
+ ;; the buffer's wire (:start when the ring's time starts): nothing to do
92
+ (= inlet 1) {}
93
+ ;; a position, from any source
94
+ (= inlet 2)
95
+ (if-let [u (comp/num-of value)]
96
+ (let [q (if norm (* u (or l 1)) u)
97
+ prev (when-not (:clock st) (:p st))
98
+ p (if (and prev l) (+ prev (span/shortest l (mod prev l) q)) q)
99
+ seek (or (nil? prev) (> (js/Math.abs (- p prev)) jump))]
100
+ (cond-> {:state (-> st (assoc :p p :gen gen) (dissoc :clock))}
101
+ (and (= mode :ovr) (not seek)) (assoc :out [[0 [:cut prev p]]])))
102
+ {})
103
+ ;; :rec t and :ovr t: to t, then at speed 1, replacing
104
+ (or (#{:rec :ovr} value) (and (vector? value) (#{:rec :ovr} (first value))))
105
+ (let [[kind t] (if (vector? value) value [value 0])]
106
+ (cue kind (comp/num-of t)))
107
+ (= value :stop) {:state (-> st (assoc :p (or (clock-at st at) (:p st)) :gen gen) (dissoc :clock))}
108
+ ;; moving on its own clock it erases what it passes, a little at a time
109
+ (comp/tick? value nil)
110
+ (if (and (:clock st) (= (second value) (:gen st)))
111
+ (let [p (clock-at st at)]
112
+ {:state (assoc st :p p) :out [[0 [:cut (:p st) p]]] :later [[(+ at tick) 0 [:tick (:gen st)]]]})
113
+ {})
114
+ :else
115
+ (let [p (or (clock-at st at) (:p st) :now)
116
+ m (if (:clock st) :ovr mode)]
117
+ ;; on its clock, first what it passed since the last tick is erased, then the value is written
118
+ {:state (cond-> st (:clock st) (assoc :p p))
119
+ :out (cond-> []
120
+ (and (:clock st) (number? (:p st)) (not= p (:p st))) (conj [0 [:cut (:p st) p]])
121
+ true (conj [0 [:write p value m]]))}))))
122
+
123
+ (comp/define! "writer"
124
+ {:doc "A write head on a buffer (a ring): what reaches its left inlet is written where it is. Its position comes in on the right, from any source (a ramp, a counter, a phasor~ through snapshot~), in seconds of the span (0…1 with norm); without one it writes where the ring's head is. Moving, it replaces what it passes, as a tape head — silence too (ovr, the default) — or leaves it (mix); a move larger than its jump is a seek. :rec t / :ovr t send it to t, moving on at speed 1. Its outlet goes to the ring's left inlet; the ring's right outlet to its middle inlet."
125
+ :usage "writer [ovr|mix] [jump s] [norm]"
126
+ :license "MPL-2.0"
127
+ :io [3 1]
128
+ :reads-buffer true
129
+ :receive writer-receive})
@@ -0,0 +1,232 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · ring~ and writer~: a span of sound and the heads that write it (discussion "Heads on a span of time";
3
+ ;; Studies 45 and 48). One AudioWorklet node per ring~ (kairotic/ringcore.mjs) holds the buffer and every head on
4
+ ;; it: the writer~ and reader~ boxes connected to its right outlet take a slot of that node, so they share the
5
+ ;; buffer and a feedback inside the ring is exact (a loop through other boxes costs a block, 128 samples).
6
+ ;;
7
+ ;; ring~ [seconds]
8
+ ;; left: the sound written where its time is (its own write head, a tape head: the last seconds are kept;
9
+ ;; with nothing on its left it does not write, and the ring is what its writer~s write); :clear
10
+ ;; right outlet: the buffer, for reader~ and writer~ (on their right / middle inlet)
11
+ ;;
12
+ ;; writer~ [ovr|mix [keep]] [jump s] [norm]
13
+ ;; left: the sound it writes; :rec t / :ovr t (from t at speed 1, replacing; rec erases the ring first);
14
+ ;; :stop holds it where it is
15
+ ;; middle: the ring~'s buffer
16
+ ;; right: a position signal (seconds, or 0…1 with norm; a phasor~); without one it writes where the ring's
17
+ ;; head is — ovr replaces what the ring writes there, mix adds to it
18
+ ;;
19
+ ;; reader~ on a ring~ (kairotic.signal): with a position signal on its left it reads there; without one it
20
+ ;; follows the ring's head d behind, then its speed (reader~ d 1 speed 0.5; msg :d 2, :speed −1).
21
+
22
+ (ns kairotic.ringaudio
23
+ (:require [kairotic.components :as comp]
24
+ [kairotic.code :as code]))
25
+
26
+ (def slots 8)
27
+
28
+ (defonce modules (atom {}))
29
+
30
+ (defn ready
31
+ "Promise that resolves when kairotic/ringcore.mjs is loaded as a worklet module in this AudioContext."
32
+ [ac]
33
+ (or (get @modules ac)
34
+ (let [p (.addModule (.-audioWorklet ac) (.-href (js/URL. "kairotic/ringcore.mjs" (.-baseURI js/document))))]
35
+ (swap! modules assoc ac p)
36
+ p)))
37
+
38
+ (defn handle? [x] (and (map? x) (= ::ring (:kind x))))
39
+
40
+ (defn post!
41
+ "A message to the ring's node, once it is there (in the order they were sent)."
42
+ [h m]
43
+ (when h (.then (:ready h) (fn [w] (when w (.postMessage (.-port w) (clj->js m)))))))
44
+
45
+ (defn attach!
46
+ "A head takes a free slot of ring h: a promise of [worklet slot], or of nil when it is full or gone."
47
+ [h opts]
48
+ (.then (:ready h)
49
+ (fn [w]
50
+ (when (and w @(:alive h))
51
+ (when-let [s (first (remove @(:used h) (range slots)))]
52
+ (swap! (:used h) conj s)
53
+ (post! h {:attach (assoc opts :slot s)})
54
+ [w s])))))
55
+
56
+ (defn detach! [h s]
57
+ (when (and h s)
58
+ (swap! (:used h) disj s)
59
+ (post! h {:detach s})))
60
+
61
+ (defn- after-word [args k] (let [x (second (drop-while #(not= k %) args))] (when (number? x) x)))
62
+
63
+ (defn head-args
64
+ "What a reader~ or writer~ says about its head on a ring~: d, speed, jump, norm, ovr/mix, keep."
65
+ [args]
66
+ (cond-> {:norm (boolean (some #{:norm} args))}
67
+ (after-word args :d) (assoc :d (after-word args :d))
68
+ (after-word args :speed) (assoc :speed (after-word args :speed))
69
+ (after-word args :jump) (assoc :jump (after-word args :jump))
70
+ (some #{:mix} args) (assoc :write "mix" :keep (or (after-word args :mix) 1))))
71
+
72
+ (defn head-message
73
+ "A message to a head (:d 2, :speed 0.5, :jump 1, :gain 0.5) as the change it makes, or nil."
74
+ [v]
75
+ (when (and (vector? v) (#{:d :speed :jump :gain :keep} (first v)) (number? (second v)))
76
+ {(first v) (second v)}))
77
+
78
+ ;; ───────── a box that is a head of a ring~ (its node: :ring the ring it is on, :slot its slot) ─────────
79
+
80
+ (defn hook!
81
+ "Puts the head of box node on ring h (nil: on none): it leaves the slot it had, takes one on h, and wires
82
+ its input (and, for a reader, the slot's output) there."
83
+ [node h role]
84
+ (let [{:keys [ring slot]} node]
85
+ (when-let [[w s] @slot]
86
+ (try (.disconnect (:m node) w) (catch :default _ nil))
87
+ (when-let [o (:out node)] (try (.disconnect w o) (catch :default _ nil)))
88
+ (detach! @ring s))
89
+ (reset! slot nil) (reset! ring h)
90
+ (when h
91
+ (-> (attach! h (merge {:role role} @(:opts node)))
92
+ (.then (fn [ws]
93
+ (when-let [[w s] ws]
94
+ (if (and @(:alive node) (= h @ring))
95
+ (do (reset! slot ws)
96
+ (.connect (:m node) w 0 (inc s))
97
+ (when-let [o (:out node)] (.connect w o s 0)))
98
+ (detach! h s)))))))))
99
+
100
+ (defn set-head!
101
+ "Changes the head of box node (kept for when it is hooked again)."
102
+ [node o]
103
+ (swap! (:opts node) merge o)
104
+ (when-let [[_ s] @(:slot node)] (post! @(:ring node) {:set (assoc o :slot s)})))
105
+
106
+ (defn unhook! "The box is gone: its head leaves the ring." [node] (reset! (:alive node) false) (hook! node nil nil))
107
+
108
+ ;; ───────── ring~ ─────────
109
+
110
+ (comp/define! "ring~"
111
+ {:doc "A span of sound: it keeps the last seconds (8 by default) of what reaches its left inlet, written where its time is, going round as a tape head. Its right outlet is the buffer for reader~ (d behind its head, then a speed: a canon, a delay, an octave down at 0.5, backwards at −1; or at a position signal) and for writer~ (more heads, anywhere, from any signal). Up to 8 heads share one node, so a feedback inside the ring is exact. :clear silences it."
112
+ :usage "ring~ [seconds]"
113
+ :license "MPL-2.0"
114
+ :io [1 2]
115
+ :size [124 30]
116
+ :receive (fn [{:keys [value]}] (if (= value :clear) {:effects [[:clear true]]} {}))
117
+ :derive (fn [{:keys [args]}] {:label (str "ring~ " (comp/nice (or (comp/num-of (first args)) 8)) " s")})
118
+ :view [[:rect {:x 2 :y 2 :w 120 :h 26 :r 13 :stroke :grid :fill :bg}]
119
+ [:text {:x 10 :y 19 :size 10 :fill :soft} :$label]]
120
+ :audio {:create (fn [ac b _]
121
+ (let [len (or (comp/num-of (first (:args b))) 8)
122
+ in (.createGain ac)
123
+ w (atom nil) alive (atom true)
124
+ p (-> (ready ac)
125
+ (.then (fn [_]
126
+ (when @alive
127
+ (let [n (js/AudioWorkletNode.
128
+ ac "kairotic-ring"
129
+ (clj->js {:numberOfInputs (inc slots) :numberOfOutputs slots
130
+ :outputChannelCount (vec (repeat slots 1))
131
+ :channelCount 2 :channelCountMode "explicit" :channelInterpretation "discrete"
132
+ :processorOptions {:len len :max 60 :slots slots}}))]
133
+ (.connect in n 0 0)
134
+ (reset! w n)
135
+ n))))
136
+ (.catch (fn [e] (js/console.error "ring~" e) nil)))]
137
+ {:in in :inlets [[in 0]] :outlets []
138
+ :ring {:kind ::ring :w w :ready p :used (atom #{}) :alive alive :len len}}))
139
+ ;; with nothing on its left its own head does not write: the ring is only what its writer~s write
140
+ :wired (fn [node ins] (post! (:ring node) {:own (contains? ins 0)}))
141
+ :effects {:clear (fn [node _ _] (post! (:ring node) {:clear true}))}
142
+ :dispose (fn [node]
143
+ (reset! (:alive (:ring node)) false)
144
+ (when-let [n @(:w (:ring node))] (try (.disconnect n) (catch :default _ nil)))
145
+ (try (.disconnect (:in node)) (catch :default _ nil)))}})
146
+
147
+ ;; ───────── writer~ ─────────
148
+
149
+ (comp/define! "writer~"
150
+ {:doc "A write head on a ring~: the sound on its left is written where it is, as a tape head — ovr (the default) replaces what is there, silence too; mix adds to it (mix 0.8: what was there fades a little at each pass). Its position: a signal on the right (seconds, or 0…1 with norm: a phasor~), any speed, either way — a jump larger than its jump is a seek; or, without one, the ring's head. :rec t / :ovr t send it to t, moving on at speed 1 (rec erases the ring first); :stop holds it. The ring~'s right outlet goes to its middle inlet."
151
+ :usage "writer~ [ovr|mix [keep]] [jump s] [norm]"
152
+ :license "MPL-2.0"
153
+ :io [3 0]
154
+ :reads-buffer true
155
+ :receive (fn [{:keys [inlet value]}]
156
+ (cond
157
+ (not= inlet 0) {}
158
+ (or (#{:rec :ovr} value) (and (vector? value) (#{:rec :ovr} (first value))))
159
+ (let [[k t] (if (vector? value) value [value 0])] {:effects [[:cue {:kind (name k) :t (or (comp/num-of t) 0)}]]})
160
+ (= value :stop) {:effects [[:cue {:kind "stop"}]]}
161
+ (head-message value) {:effects [[:head (head-message value)]]}
162
+ :else {}))
163
+ :audio {:create (fn [ac b _]
164
+ (let [vin (.createGain ac) pin (.createGain ac) m (.createChannelMerger ac 2)]
165
+ (.connect vin m 0 0) (.connect pin m 0 1)
166
+ {:m m :inlets [[vin 0] nil [pin 0]] :outlets []
167
+ :fed (atom ::none) :ring (atom nil) :slot (atom nil) :alive (atom true) :folded (atom nil)
168
+ :opts (atom (merge {:mode "head"} (head-args (:args b))))}))
169
+ ;; a position signal on the right: it writes there; without one, where the ring's head is
170
+ :wired (fn [node ins] (set-head! node {:mode (if (contains? ins 2) "pos" "head")}))
171
+ :feed (fn [node d] (hook! node (when (handle? d) d) "write"))
172
+ :effects {:cue (fn [node x _]
173
+ (when-let [[_ s] @(:slot node)] (post! @(:ring node) {:cue (assoc x :slot s)})))
174
+ :head (fn [node x _] (set-head! node x))}
175
+ :dispose unhook!}})
176
+
177
+ ;; ───────── a faust~ in a loop of a ring~ runs inside it (Study 49) ─────────
178
+ ;; reader~ → faust~ → writer~, all on one ring~: the faust~'s compiled bytes go to the ring's node, where they run
179
+ ;; one sample at a time in the writer's slot, hearing those readers; the line from the faust~ to the writer~ is
180
+ ;; taken away (what it would bring, a block late, is already written). The faust~ keeps its own node for whatever
181
+ ;; else it is connected to (a dac~), and its parameters reach its copy in the ring as well. Every tick, after the
182
+ ;; nodes are fed: a loop that appears is folded, one that is gone unfolded.
183
+
184
+ (defn loops
185
+ "The faust~ boxes in a loop of a ring~: [{:faust id :ring id :readers [id …] :writers [id …]}]. Every input of
186
+ the faust~ comes from a reader~ on the ring, and its output reaches the left inlet of a writer~ on the same ring."
187
+ [p]
188
+ (let [k (fn [id] (comp/klass (get-in p [:boxes id :text])))
189
+ ring-of (fn [id] (some (fn [[a _ b i]] (when (and (= b id) (= i 1) (= "ring~" (k a))) a)) (:lines p)))]
190
+ (vec (for [[f _] (:boxes p) :when (= "faust~" (k f))
191
+ :let [ins (filter (fn [[_ _ b _]] (= b f)) (:lines p))
192
+ rs (vec (distinct (map first ins)))
193
+ ring (when (seq rs) (ring-of (first rs)))
194
+ ws (vec (distinct (keep (fn [[a _ b i]] (when (and (= a f) (= i 0) (= "writer~" (k b)) (= ring (ring-of b))) b)) (:lines p))))]
195
+ :when (and ring (seq ws) (every? (fn [r] (and (= "reader~" (k r)) (= ring (ring-of r)))) rs))]
196
+ {:faust f :ring ring :readers rs :writers ws}))))
197
+
198
+ (defn- bytes-of [source]
199
+ (let [r (code/compiled "faust" source)]
200
+ (when (and (= :ok (:status r)) (not (:poly (:info r))) (:value r))
201
+ (let [f (.-factory (:value r))] (when (and f (.-code f)) [f (:info r)])))))
202
+
203
+ (defn fold-pass!
204
+ "Folds the loops of p into their rings, and unfolds what no longer is one (called every tick by the engine)."
205
+ [p nodes sig]
206
+ (let [want (into {} (for [{:keys [faust ring readers writers]} (loops p) w writers] [w [faust ring readers]]))]
207
+ ;; unfolded: a writer~ that was folded and no longer is
208
+ (doseq [[id node] nodes :let [fa (:folded node)] :when (and fa @fa (not (contains? want id)))]
209
+ (when-let [[_ s] @(:slot node)] (post! @(:ring node) {:unfold s}))
210
+ (when-let [m (:mirrors (get nodes (:faust @fa)))] (swap! m dissoc id))
211
+ (reset! fa nil))
212
+ ;; folded: when every head has its slot and the faust~ is compiled
213
+ (doseq [[w [faust ring readers]] want
214
+ :let [wn (get nodes w) fnode (get nodes faust) rnode (get nodes ring)
215
+ h (:ring rnode) ws @(:slot wn)
216
+ rslots (mapv (fn [r] (second @(:slot (get nodes r)))) readers)
217
+ src (get-in p [:boxes faust :data :source])
218
+ [fac info] (bytes-of src)]
219
+ :when (and wn fnode h ws (= h @(:ring wn)) (every? some? rslots) fac)
220
+ :let [key [h (second ws) rslots src sig]]
221
+ :when (not= key (:key @(:folded wn)))]
222
+ (post! h {:fold {:slot (second ws) :readers rslots :code (.slice (.-code fac)) :json (.-json fac)}})
223
+ ;; its parameters as they are, and from now on as they change
224
+ (doseq [prm (:params info) :let [v (get @(:values fnode) (:label prm))] :when (number? v)]
225
+ (post! h {:param {:slot (second ws) :address (:address prm) :value v}}))
226
+ (swap! (:mirrors fnode) assoc w (fn [address v] (post! h {:param {:slot (second ws) :address address :value v}})))
227
+ ;; what the faust~'s own node would bring into the writer~, a block late, is taken away
228
+ (let [vin (ffirst (:inlets wn))]
229
+ (doseq [[n _] (:outlets fnode)] (try (.disconnect n vin) (catch :default _ nil))))
230
+ (reset! (:folded wn) {:key key :faust faust}))))
231
+
232
+ (reset! comp/after-feed fold-pass!)