@kairotic/io 0.0.0-stage → 0.2.5
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.
- package/README.md +57 -2
- package/dist/control.mjs +9 -0
- package/dist/gamepad.mjs +9 -0
- package/dist/index.mjs +58 -0
- package/dist/midiin.mjs +9 -0
- package/dist/midiout.mjs +9 -0
- package/dist/motion.mjs +9 -0
- package/dist/oscin.mjs +9 -0
- package/dist/oscout.mjs +9 -0
- package/dist/serial.mjs +9 -0
- package/package.json +38 -4
- package/src/control.cljs +55 -0
- package/src/gamepad.cljs +80 -0
- package/src/midiin.cljs +135 -0
- package/src/midiout.cljs +146 -0
- package/src/motion.cljs +80 -0
- package/src/oscin.cljs +95 -0
- package/src/oscout.cljs +76 -0
- package/src/serial.cljs +95 -0
package/README.md
CHANGED
|
@@ -1,3 +1,58 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @kairotic/io
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
*Official package of [Kairotic](https://github.com/bonuoq/kairotic) · [all packages](../README.md)*
|
|
4
|
+
|
|
5
|
+
Kairotic talking to the outside (discussion [#135](https://github.com/bonuoq/kairotic/discussions/135),
|
|
6
|
+
first tried in Study 34 · io). Whatever comes in or goes out is **one kind of event**: an EDN map in the
|
|
7
|
+
shape of a pattern event, with pitch as `:freq` in Hz, so a patch never needs to know where a message came
|
|
8
|
+
from — `midiin` can feed `synth~` or `oscout`, a phone's tilt can glide an MPE synthesizer.
|
|
9
|
+
|
|
10
|
+
```clojure
|
|
11
|
+
{:src :midi :type :note :id 60 :ch 1 :note 60 :freq 261.626 :amp 0.79 :gate true}
|
|
12
|
+
{:src :midi :type :glide :id 60 :freq 266.1} ; a pitch bend moves the notes of its channel
|
|
13
|
+
{:src :midi :type :cc :ch 1 :cc 74 :value 0.42}
|
|
14
|
+
{:src :osc :type :osc :address "/synth/cutoff" :args [1200] :from "127.0.0.1:57120"}
|
|
15
|
+
{:src :motion :type :tilt :x 0.62 :y 0.48}
|
|
16
|
+
{:src :gamepad :type :button :pad 0 :button 0 :name :a :value 1 :gate true}
|
|
17
|
+
{:src :serial :type :serial :key "pot" :value 512}
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
| Class | What it does |
|
|
21
|
+
|---|---|
|
|
22
|
+
| `midiin [channel] [range]` | MIDI from every input of the page as events; out: the Hz of the notes sounding and their voice ids (as a keyboard or a player, for `synth~` or a polyphonic `faust~`) and every event. A bend glides the notes of its channel; an MPE controller's bend range (RPN 0) is read |
|
|
23
|
+
| `midiout [mpe] [channel] [port] [range]` | notes and events to a MIDI port: what sounds as a player sends it (Hz after voice ids), or events. With `mpe`, a channel per note and its exact Hz as key + bend: microtones and glides without rounding |
|
|
24
|
+
| `oscout [target]` | events as `/kairotic/note id freq amp gate`, `/kairotic/glide`, `/kairotic/cc`, `/kairotic/tilt`…, or a list that starts with an address as it is — through a relay's OSC bridge |
|
|
25
|
+
| `oscin [pattern]` | OSC from the bridge as events (the `/kairotic/…` addresses) or `{:type :osc …}`; an OSC address pattern (`/synth/*/cutoff`, `{note,glide}`) keeps some |
|
|
26
|
+
| `motion [smooth] [shake]` | a phone's tilt as `[x y]` (0…1, flat 0.5), smoothed and sent only when it moves, and its shakes |
|
|
27
|
+
| `gamepad [pad] [deadzone]` | a controller's buttons (with a gate when pressed or let go) and sticks (−1…1, without their dead zone), by name with the standard mapping |
|
|
28
|
+
| `serial [baud]` | a board on a serial port (Web Serial): `open` asks for the port; lines of numbers or `key:value` go out as values and events; a text on the left goes to the board |
|
|
29
|
+
|
|
30
|
+
```clojure
|
|
31
|
+
(box :b1 "midiin" 40 30)
|
|
32
|
+
(box :b2 "midiout mpe" 40 90)
|
|
33
|
+
(box :b3 "oscout" 180 90)
|
|
34
|
+
(connect :b1 0 :b2 0) (connect :b1 1 :b2 1) (connect :b1 2 :b3 0)
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## While ▶ runs
|
|
38
|
+
|
|
39
|
+
Input from outside is like sound: `midiin`, `oscin`, `motion`, `gamepad` and `serial` listen while ▶
|
|
40
|
+
runs, and so `midiout` sends (on the audio clock: a note of a player goes out at its time). `oscout` sends
|
|
41
|
+
with or without ▶, as a message.
|
|
42
|
+
|
|
43
|
+
## Where each works
|
|
44
|
+
|
|
45
|
+
| | Chrome, Edge | Firefox | Safari, iOS |
|
|
46
|
+
|---|---|---|---|
|
|
47
|
+
| MIDI (Web MIDI) | ✓ (asks once) | ✓ (asks once) | — |
|
|
48
|
+
| OSC (relay bridge) | ✓ | ✓ | the page may not reach `ws://localhost` from https |
|
|
49
|
+
| motion | ✓ on phones | ✓ on phones | ✓ (asks at ▶) |
|
|
50
|
+
| gamepad | ✓ | ✓ | ✓ |
|
|
51
|
+
| serial (Web Serial) | ✓ | 151+ | — |
|
|
52
|
+
|
|
53
|
+
**OSC** needs a relay with the bridge on the same machine as SuperCollider, Max or Pd:
|
|
54
|
+
`npx @kairotic/relay --osc` (pages on `ws://localhost:8765/osc`, OSC out to sclang on 57120, OSC in on
|
|
55
|
+
57121; see [relay/README.md](../../relay/README.md#osc-bridge)). `[:relay "ws://…/osc"]` to an `oscin` or
|
|
56
|
+
`oscout` changes the bridge for the page.
|
|
57
|
+
|
|
58
|
+
Writing one of its classes in a work brings the package into it. Licence: [MPL-2.0](../../LICENSE).
|
package/dist/control.mjs
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Generated by packages/build.mjs from src/control.cljs
|
|
2
|
+
export default {
|
|
3
|
+
"class": "control",
|
|
4
|
+
"version": "0.2.5",
|
|
5
|
+
"author": "bonuoq",
|
|
6
|
+
"license": "MPL-2.0",
|
|
7
|
+
"doc": "One control of a controller, out of the events that midiin, gamepad, motion, oscin or serial send (on their event outlet): its value, every time it moves. cc 74 [channel] a MIDI controller (0…1); note [n] a key (its loudness on, 0 off); bend the pitch of a glided note (Hz); pad lx · pad a · pad a3 a stick or button of a gamepad (by name, or a0 b3); tilt x · tilt y a phone's tilt (0…1); shake; osc /synth/cut the first number of an OSC address (* and ? allowed); serial pot · serial 0 a board's key, or the nth number of its lines. Into scale, to bring it to the range of what it moves — which is what learn makes.",
|
|
8
|
+
"source": ";; control · one control of a controller, out of the events of midiin, gamepad, motion, oscin or serial\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135.\n(let [num (fn [s] (let [n (js/parseFloat s)] (when (js/isFinite n) n)))\n ;; an OSC address pattern, only * and ? (the rest as it is)\n osc-re (fn [p] (js/RegExp. (str \"^\" (-> p (.replace (js/RegExp. \"[.+^${}()|[\\\\]\\\\\\\\]\" \"g\") \"\\\\$&\") (.replaceAll \"*\" \"[^/]*\") (.replaceAll \"?\" \"[^/]\")) \"$\")))\n ;; the spec, from the words after the class: [kind & words]\n ;; (a word such as /synth/cut is read as a keyword with an empty namespace: put its / back)\n spec-of (fn [args] (mapv (fn [a] (cond (and (keyword? a) (re-find #\"/\" (str a))) (subs (str a) 1)\n (keyword? a) (name a)\n :else (str a)))\n args))\n ;; the value of the event for the spec, or nil if the event is not that control\n pick (fn [[kind a b] e]\n (case kind\n \"cc\" (when (and (= :cc (:type e)) (= (num a) (:cc e)) (or (nil? b) (= (num b) (:ch e)))) (:value e))\n \"note\" (when (and (= :note (:type e)) (or (nil? a) (= (num a) (:note e))))\n (if (:gate e) (or (:amp e) 1) 0))\n \"bend\" (when (= :glide (:type e)) (:freq e))\n \"pad\" (when (and (#{:axis :button} (:type e))\n (or (= a (some-> (:name e) name))\n (= a (str (if (= :axis (:type e)) \"a\" \"b\") (or (:axis e) (:button e))))))\n (:value e))\n \"tilt\" (when (= :tilt (:type e)) (if (= a \"y\") (:y e) (:x e)))\n \"shake\" (when (= :shake (:type e)) (:value e))\n \"osc\" (when (and a (:address e) (.test (osc-re a) (:address e)))\n (let [v (first (:args e))] (when (number? v) v)))\n \"serial\" (when (= :serial (:type e))\n (cond (and (:key e) (= a (:key e))) (:value e)\n (and (:values e) (num a)) (get (:values e) (js/Math.round (num a)))))\n nil))]\n {;; ── about ──\n :class \"control\"\n :license \"MPL-2.0\"\n :doc \"One control of a controller, out of the events that midiin, gamepad, motion, oscin or serial send (on their event outlet): its value, every time it moves. cc 74 [channel] a MIDI controller (0…1); note [n] a key (its loudness on, 0 off); bend the pitch of a glided note (Hz); pad lx · pad a · pad a3 a stick or button of a gamepad (by name, or a0 b3); tilt x · tilt y a phone's tilt (0…1); shake; osc /synth/cut the first number of an OSC address (* and ? allowed); serial pot · serial 0 a board's key, or the nth number of its lines. Into scale, to bring it to the range of what it moves — which is what learn makes.\"\n :usage \"control kind [which] [channel]\"\n :io [1 1]\n :size [110 24]\n :help {:inlets [\"the events of midiin, gamepad, motion, oscin or serial\"]\n :outlets [\"the value of that one control, when it moves\"]\n :example \"(box :b1 \\\"midiin\\\" 40 30)\\n(box :b2 \\\"control cc 1\\\" 40 80)\\n(box :b3 \\\"scale 0 1 200 2000 log\\\" 40 120)\\n(box :b4 \\\"print\\\" 40 160)\\n(connect :b1 2 :b2 0)\\n(connect :b2 0 :b3 0)\\n(connect :b3 0 :b4 0)\"\n :try \"Press ▶ and move the modulation wheel (CC 1) of a MIDI keyboard: 200 to 2000, in tune with the ear.\"\n :see [\"scale\" \"midiin\" \"gamepad\" \"motion\" \"oscin\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [value args]}]\n (if-let [v (and (map? value) (pick (spec-of args) value))]\n {:out [[0 v]] :show {:v v}}\n {}))\n\n ;; ── view ──\n :derive (fn [{:keys [shown args]}]\n (let [s (str \"control \" (apply str (interpose \" \" (spec-of args))))]\n {:label (if (number? (:v shown)) (str s \" · \" (api/nice (:v shown))) s)}))\n :view [[:rect {:x 1 :y 1 :w 108 :h 22 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 6 :y 16 :size 10.5} :$label]]})\n"
|
|
9
|
+
};
|
package/dist/gamepad.mjs
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Generated by packages/build.mjs from src/gamepad.cljs
|
|
2
|
+
export default {
|
|
3
|
+
"class": "gamepad",
|
|
4
|
+
"version": "0.2.5",
|
|
5
|
+
"author": "bonuoq",
|
|
6
|
+
"license": "MPL-2.0",
|
|
7
|
+
"doc": "A game controller while ▶ runs (press a button to wake it): each button pressed or let go is {:type :button :pad :button :name :value :gate}, a trigger that moves without crossing is the same without :gate, and a stick {:type :axis :pad :axis :name :value −1…1}, with its dead zone (deadzone, 0.12) taken out. With the standard mapping they have names: :a :b :x :y :lb :rb :lt :rt :back :start :ls :rs :up :down :left :right :home, and :lx :ly :rx :ry. pad (-1, all) keeps one. Out: every event, and [name value] for a route or a number box.",
|
|
8
|
+
"source": ";; gamepad · a game controller's buttons and sticks as Kairotic events\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [buttons [:a :b :x :y :lb :rb :lt :rt :back :start :ls :rs :up :down :left :right :home]\n axes [:lx :ly :rx :ry]\n r3 (fn [x] (/ (js/Math.round (* x 1000)) 1000))\n ;; a stick's value without its dead zone (its rest is never exactly 0), still −1…1 outside it\n dead (fn [v dz] (if (< (js/Math.abs v) dz) 0 (* (js/Math.sign v) (/ (- (js/Math.abs v) dz) (- 1 dz)))))\n ;; one pad now against the same pad before: the events between them\n pad-diff (fn [i before pad dz]\n (let [std? (= \"standard\" (:mapping pad))\n ev (fn [m] (assoc m :src :gamepad :pad i))\n ax (mapv (fn [v] (r3 (dead v dz))) (:axes pad))\n axis-evs (for [[k v] (map-indexed vector ax)\n :let [old (get-in before [:axes k] 0)]\n :when (or (>= (js/Math.abs (- v old)) 0.01) (and (zero? v) (not (zero? old))))]\n (ev (cond-> {:type :axis :axis k :value v} (and std? (< k 4)) (assoc :name (nth axes k)))))\n btn-evs (for [[k [p v]] (map-indexed vector (:buttons pad))\n :let [[op ov] (get-in before [:buttons k] [false 0]) v (r3 v)]\n :when (or (not= (boolean p) (boolean op)) (>= (js/Math.abs (- v ov)) 0.01))]\n (ev (cond-> {:type :button :button k :value v}\n (and std? (< k 17)) (assoc :name (nth buttons k))\n (not= (boolean p) (boolean op)) (assoc :gate (boolean p)))))]\n [{:axes ax :buttons (mapv (fn [[p v]] [(boolean p) (r3 v)]) (:buttons pad))} (vec (concat btn-evs axis-evs))]))\n read-pads (fn []\n (let [raw (or (.-kairoticFakePads js/window) (when (.-getGamepads js/navigator) (.getGamepads js/navigator)) #js [])]\n (vec (for [p (js/Array.from raw) :when p]\n {:index (.-index p) :id (.-id p) :mapping (.-mapping p) :axes (vec (js/Array.from (.-axes p)))\n :buttons (mapv (fn [b] [(.-pressed b) (.-value b)]) (js/Array.from (.-buttons p)))}))))]\n {;; ── about ──\n :class \"gamepad\"\n :license \"MPL-2.0\"\n :doc \"A game controller while ▶ runs (press a button to wake it): each button pressed or let go is {:type :button :pad :button :name :value :gate}, a trigger that moves without crossing is the same without :gate, and a stick {:type :axis :pad :axis :name :value −1…1}, with its dead zone (deadzone, 0.12) taken out. With the standard mapping they have names: :a :b :x :y :lb :rb :lt :rt :back :start :ls :rs :up :down :left :right :home, and :lx :ly :rx :ry. pad (-1, all) keeps one. Out: every event, and [name value] for a route or a number box.\"\n :usage \"gamepad [pad] [deadzone]\"\n :io [0 2]\n :size [96 30]\n :args [[:pad -1] [:deadzone 0.12]]\n :help {:inlets []\n :outlets [\"every event, as a map\" \"[name value]: (:a 1), (:lx -0.4)…\"]\n :example \"(box :b1 \\\"gamepad\\\" 40 30)\\n(box :b2 \\\"print\\\" 40 80)\\n(connect :b1 1 :b2 0)\"\n :try \"Press ▶, then any button of a controller to wake it: print shows the buttons and sticks by name.\"\n :see [\"motion\" \"midiin\" \"oscout\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value args]}]\n (if (and (= inlet :audio) (:event value))\n (let [e (:event value)]\n (if (and (>= (:pad args) 0) (:pad e) (not= (:pad args) (:pad e)))\n {}\n {:out (cond-> [[0 e]] (#{:button :axis} (:type e)) (conj [1 [(or (:name e) (if (= :axis (:type e)) (:axis e) (:button e))) (:value e)]]))\n :show {:label (case (:type e)\n :connect (str \"pad \" (:pad e))\n :disconnect \"no pad\"\n (str (name (or (:name e) (:type e))) \" \" (api/nice (:value e))))}}))\n {}))\n\n ;; ── view ──\n :derive (fn [{:keys [shown]}] {:label (or (:label shown) \"gamepad\")})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]\n\n ;; ── outside: the pads, read on every frame while ▶ runs ──\n :audio {:create (fn [_ b _]\n (let [dz (let [n (js/parseFloat (nth (.split (.trim (str (:text b))) #\"\\s+\") 2 \"\"))] (if (js/isNaN n) 0.12 n))\n node {:alive (atom true) :last (atom {}) :inlets [] :outlets []}\n report (fn [e] (api/report! (:id b) {:event e} nil))\n poll (fn poll [& _]\n (when @(:alive node)\n (let [pads (into {} (map (fn [p] [(:index p) p]) (read-pads)))\n before @(:last node)]\n (doseq [i (keys before) :when (not (contains? pads i))] (report {:src :gamepad :type :disconnect :pad i}))\n (reset! (:last node)\n (into {} (for [[i p] (sort-by key pads)]\n (let [[after es] (pad-diff i (get before i) p dz)]\n (when-not (contains? before i) (report {:src :gamepad :type :connect :pad i :name (:id p)}))\n (doseq [e es] (report e))\n [i after])))))\n (js/requestAnimationFrame poll)))]\n (poll)\n node))\n :dispose (fn [node] (reset! (:alive node) false))}})\n"
|
|
9
|
+
};
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Generated by packages/build.mjs
|
|
2
|
+
export default {
|
|
3
|
+
"package": "@kairotic/io",
|
|
4
|
+
"version": "0.2.5",
|
|
5
|
+
"api": 1,
|
|
6
|
+
"author": "bonuoq",
|
|
7
|
+
"license": "MPL-2.0",
|
|
8
|
+
"components": [
|
|
9
|
+
{
|
|
10
|
+
"class": "control",
|
|
11
|
+
"license": "MPL-2.0",
|
|
12
|
+
"doc": "One control of a controller, out of the events that midiin, gamepad, motion, oscin or serial send (on their event outlet): its value, every time it moves. cc 74 [channel] a MIDI controller (0…1); note [n] a key (its loudness on, 0 off); bend the pitch of a glided note (Hz); pad lx · pad a · pad a3 a stick or button of a gamepad (by name, or a0 b3); tilt x · tilt y a phone's tilt (0…1); shake; osc /synth/cut the first number of an OSC address (* and ? allowed); serial pot · serial 0 a board's key, or the nth number of its lines. Into scale, to bring it to the range of what it moves — which is what learn makes.",
|
|
13
|
+
"source": ";; control · one control of a controller, out of the events of midiin, gamepad, motion, oscin or serial\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135.\n(let [num (fn [s] (let [n (js/parseFloat s)] (when (js/isFinite n) n)))\n ;; an OSC address pattern, only * and ? (the rest as it is)\n osc-re (fn [p] (js/RegExp. (str \"^\" (-> p (.replace (js/RegExp. \"[.+^${}()|[\\\\]\\\\\\\\]\" \"g\") \"\\\\$&\") (.replaceAll \"*\" \"[^/]*\") (.replaceAll \"?\" \"[^/]\")) \"$\")))\n ;; the spec, from the words after the class: [kind & words]\n ;; (a word such as /synth/cut is read as a keyword with an empty namespace: put its / back)\n spec-of (fn [args] (mapv (fn [a] (cond (and (keyword? a) (re-find #\"/\" (str a))) (subs (str a) 1)\n (keyword? a) (name a)\n :else (str a)))\n args))\n ;; the value of the event for the spec, or nil if the event is not that control\n pick (fn [[kind a b] e]\n (case kind\n \"cc\" (when (and (= :cc (:type e)) (= (num a) (:cc e)) (or (nil? b) (= (num b) (:ch e)))) (:value e))\n \"note\" (when (and (= :note (:type e)) (or (nil? a) (= (num a) (:note e))))\n (if (:gate e) (or (:amp e) 1) 0))\n \"bend\" (when (= :glide (:type e)) (:freq e))\n \"pad\" (when (and (#{:axis :button} (:type e))\n (or (= a (some-> (:name e) name))\n (= a (str (if (= :axis (:type e)) \"a\" \"b\") (or (:axis e) (:button e))))))\n (:value e))\n \"tilt\" (when (= :tilt (:type e)) (if (= a \"y\") (:y e) (:x e)))\n \"shake\" (when (= :shake (:type e)) (:value e))\n \"osc\" (when (and a (:address e) (.test (osc-re a) (:address e)))\n (let [v (first (:args e))] (when (number? v) v)))\n \"serial\" (when (= :serial (:type e))\n (cond (and (:key e) (= a (:key e))) (:value e)\n (and (:values e) (num a)) (get (:values e) (js/Math.round (num a)))))\n nil))]\n {;; ── about ──\n :class \"control\"\n :license \"MPL-2.0\"\n :doc \"One control of a controller, out of the events that midiin, gamepad, motion, oscin or serial send (on their event outlet): its value, every time it moves. cc 74 [channel] a MIDI controller (0…1); note [n] a key (its loudness on, 0 off); bend the pitch of a glided note (Hz); pad lx · pad a · pad a3 a stick or button of a gamepad (by name, or a0 b3); tilt x · tilt y a phone's tilt (0…1); shake; osc /synth/cut the first number of an OSC address (* and ? allowed); serial pot · serial 0 a board's key, or the nth number of its lines. Into scale, to bring it to the range of what it moves — which is what learn makes.\"\n :usage \"control kind [which] [channel]\"\n :io [1 1]\n :size [110 24]\n :help {:inlets [\"the events of midiin, gamepad, motion, oscin or serial\"]\n :outlets [\"the value of that one control, when it moves\"]\n :example \"(box :b1 \\\"midiin\\\" 40 30)\\n(box :b2 \\\"control cc 1\\\" 40 80)\\n(box :b3 \\\"scale 0 1 200 2000 log\\\" 40 120)\\n(box :b4 \\\"print\\\" 40 160)\\n(connect :b1 2 :b2 0)\\n(connect :b2 0 :b3 0)\\n(connect :b3 0 :b4 0)\"\n :try \"Press ▶ and move the modulation wheel (CC 1) of a MIDI keyboard: 200 to 2000, in tune with the ear.\"\n :see [\"scale\" \"midiin\" \"gamepad\" \"motion\" \"oscin\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [value args]}]\n (if-let [v (and (map? value) (pick (spec-of args) value))]\n {:out [[0 v]] :show {:v v}}\n {}))\n\n ;; ── view ──\n :derive (fn [{:keys [shown args]}]\n (let [s (str \"control \" (apply str (interpose \" \" (spec-of args))))]\n {:label (if (number? (:v shown)) (str s \" · \" (api/nice (:v shown))) s)}))\n :view [[:rect {:x 1 :y 1 :w 108 :h 22 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 6 :y 16 :size 10.5} :$label]]})\n"
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
"class": "gamepad",
|
|
17
|
+
"license": "MPL-2.0",
|
|
18
|
+
"doc": "A game controller while ▶ runs (press a button to wake it): each button pressed or let go is {:type :button :pad :button :name :value :gate}, a trigger that moves without crossing is the same without :gate, and a stick {:type :axis :pad :axis :name :value −1…1}, with its dead zone (deadzone, 0.12) taken out. With the standard mapping they have names: :a :b :x :y :lb :rb :lt :rt :back :start :ls :rs :up :down :left :right :home, and :lx :ly :rx :ry. pad (-1, all) keeps one. Out: every event, and [name value] for a route or a number box.",
|
|
19
|
+
"source": ";; gamepad · a game controller's buttons and sticks as Kairotic events\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [buttons [:a :b :x :y :lb :rb :lt :rt :back :start :ls :rs :up :down :left :right :home]\n axes [:lx :ly :rx :ry]\n r3 (fn [x] (/ (js/Math.round (* x 1000)) 1000))\n ;; a stick's value without its dead zone (its rest is never exactly 0), still −1…1 outside it\n dead (fn [v dz] (if (< (js/Math.abs v) dz) 0 (* (js/Math.sign v) (/ (- (js/Math.abs v) dz) (- 1 dz)))))\n ;; one pad now against the same pad before: the events between them\n pad-diff (fn [i before pad dz]\n (let [std? (= \"standard\" (:mapping pad))\n ev (fn [m] (assoc m :src :gamepad :pad i))\n ax (mapv (fn [v] (r3 (dead v dz))) (:axes pad))\n axis-evs (for [[k v] (map-indexed vector ax)\n :let [old (get-in before [:axes k] 0)]\n :when (or (>= (js/Math.abs (- v old)) 0.01) (and (zero? v) (not (zero? old))))]\n (ev (cond-> {:type :axis :axis k :value v} (and std? (< k 4)) (assoc :name (nth axes k)))))\n btn-evs (for [[k [p v]] (map-indexed vector (:buttons pad))\n :let [[op ov] (get-in before [:buttons k] [false 0]) v (r3 v)]\n :when (or (not= (boolean p) (boolean op)) (>= (js/Math.abs (- v ov)) 0.01))]\n (ev (cond-> {:type :button :button k :value v}\n (and std? (< k 17)) (assoc :name (nth buttons k))\n (not= (boolean p) (boolean op)) (assoc :gate (boolean p)))))]\n [{:axes ax :buttons (mapv (fn [[p v]] [(boolean p) (r3 v)]) (:buttons pad))} (vec (concat btn-evs axis-evs))]))\n read-pads (fn []\n (let [raw (or (.-kairoticFakePads js/window) (when (.-getGamepads js/navigator) (.getGamepads js/navigator)) #js [])]\n (vec (for [p (js/Array.from raw) :when p]\n {:index (.-index p) :id (.-id p) :mapping (.-mapping p) :axes (vec (js/Array.from (.-axes p)))\n :buttons (mapv (fn [b] [(.-pressed b) (.-value b)]) (js/Array.from (.-buttons p)))}))))]\n {;; ── about ──\n :class \"gamepad\"\n :license \"MPL-2.0\"\n :doc \"A game controller while ▶ runs (press a button to wake it): each button pressed or let go is {:type :button :pad :button :name :value :gate}, a trigger that moves without crossing is the same without :gate, and a stick {:type :axis :pad :axis :name :value −1…1}, with its dead zone (deadzone, 0.12) taken out. With the standard mapping they have names: :a :b :x :y :lb :rb :lt :rt :back :start :ls :rs :up :down :left :right :home, and :lx :ly :rx :ry. pad (-1, all) keeps one. Out: every event, and [name value] for a route or a number box.\"\n :usage \"gamepad [pad] [deadzone]\"\n :io [0 2]\n :size [96 30]\n :args [[:pad -1] [:deadzone 0.12]]\n :help {:inlets []\n :outlets [\"every event, as a map\" \"[name value]: (:a 1), (:lx -0.4)…\"]\n :example \"(box :b1 \\\"gamepad\\\" 40 30)\\n(box :b2 \\\"print\\\" 40 80)\\n(connect :b1 1 :b2 0)\"\n :try \"Press ▶, then any button of a controller to wake it: print shows the buttons and sticks by name.\"\n :see [\"motion\" \"midiin\" \"oscout\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value args]}]\n (if (and (= inlet :audio) (:event value))\n (let [e (:event value)]\n (if (and (>= (:pad args) 0) (:pad e) (not= (:pad args) (:pad e)))\n {}\n {:out (cond-> [[0 e]] (#{:button :axis} (:type e)) (conj [1 [(or (:name e) (if (= :axis (:type e)) (:axis e) (:button e))) (:value e)]]))\n :show {:label (case (:type e)\n :connect (str \"pad \" (:pad e))\n :disconnect \"no pad\"\n (str (name (or (:name e) (:type e))) \" \" (api/nice (:value e))))}}))\n {}))\n\n ;; ── view ──\n :derive (fn [{:keys [shown]}] {:label (or (:label shown) \"gamepad\")})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]\n\n ;; ── outside: the pads, read on every frame while ▶ runs ──\n :audio {:create (fn [_ b _]\n (let [dz (let [n (js/parseFloat (nth (.split (.trim (str (:text b))) #\"\\s+\") 2 \"\"))] (if (js/isNaN n) 0.12 n))\n node {:alive (atom true) :last (atom {}) :inlets [] :outlets []}\n report (fn [e] (api/report! (:id b) {:event e} nil))\n poll (fn poll [& _]\n (when @(:alive node)\n (let [pads (into {} (map (fn [p] [(:index p) p]) (read-pads)))\n before @(:last node)]\n (doseq [i (keys before) :when (not (contains? pads i))] (report {:src :gamepad :type :disconnect :pad i}))\n (reset! (:last node)\n (into {} (for [[i p] (sort-by key pads)]\n (let [[after es] (pad-diff i (get before i) p dz)]\n (when-not (contains? before i) (report {:src :gamepad :type :connect :pad i :name (:id p)}))\n (doseq [e es] (report e))\n [i after])))))\n (js/requestAnimationFrame poll)))]\n (poll)\n node))\n :dispose (fn [node] (reset! (:alive node) false))}})\n"
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
"class": "midiin",
|
|
23
|
+
"license": "MPL-2.0",
|
|
24
|
+
"doc": "MIDI from every input of the page (a keyboard, a controller, another program) as Kairotic events, while ▶ runs: a note is {:type :note :id :ch :note :freq :amp :gate}, a pitch bend moves the notes of its channel ({:type :glide :id :freq}), and controllers, pressure, program changes and the clock come as {:type :cc :ch :cc :value 0…1}, {:type :pressure …}, {:type :clock}…. Pitch travels as :freq in Hz: a bend, or an MPE controller (a channel per note; its bend range, RPN 0, is read), is only a different :freq. Out: the Hz of the notes sounding (with [:gain amp] just before a note starts) and their voice ids, as a keyboard or a player sends them, for synth~ or a polyphonic faust~; and every event. channel (0, all) keeps one; range (2) is the bend range of a controller that does not say its own. :clear (or :stop) lets every held note go. Chrome, Edge and Firefox ask once to use MIDI; Safari has no MIDI.",
|
|
25
|
+
"source": ";; midiin · MIDI from a keyboard, a controller or another program, as Kairotic events\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [;; ── the page's MIDI, asked once and shared by every midi box (Chrome, Edge, Firefox; not Safari) ──\n access (fn []\n (or (.-kairoticMidi js/window)\n (let [p (if (.-requestMIDIAccess js/navigator)\n (.requestMIDIAccess js/navigator #js {:sysex false})\n (js/Promise.reject (js/Error. \"this browser has no Web MIDI (Chrome, Edge or Firefox; not Safari)\")))]\n (set! (.-kairoticMidi js/window) p)\n ;; refused: ask again next time\n (.catch p (fn [_] (set! (.-kairoticMidi js/window) nil)))\n p)))\n r3 (fn [x] (/ (js/Math.round (* x 1000)) 1000))\n r4 (fn [x] (/ (js/Math.round (* x 10000)) 10000))\n ;; ── bytes → messages ──\n decode (fn [[s a b]]\n (let [hi (bit-and (or s 0) 0xF0) ch (inc (bit-and (or s 0) 0x0F))]\n (case hi\n 0x80 {:type :note-off :ch ch :note a}\n 0x90 (if (zero? b) {:type :note-off :ch ch :note a} {:type :note-on :ch ch :note a :vel b})\n 0xA0 {:type :poly :ch ch :note a :value b}\n 0xB0 {:type :cc :ch ch :cc a :value b}\n 0xC0 {:type :program :ch ch :value a}\n 0xD0 {:type :pressure :ch ch :value a}\n 0xE0 {:type :bend :ch ch :value (- (+ a (* 128 b)) 8192)}\n 0xF0 (case s 0xF8 {:type :clock} 0xFA {:type :start} 0xFB {:type :continue} 0xFC {:type :stop} nil)\n nil)))\n ;; ── messages → events, with the state of what is held ──\n ;; a voice id names a note on a channel: the same key on two MPE channels is two voices\n voice-id (fn [ch note] (+ note (* 128 (dec ch))))\n fresh (fn [range0] {:range0 range0 :ranges {} :bends {} :rpn {} :held {} :order []})\n freq-of (fn [st ch note] (api/midi->hz (+ note (* (get (:bends st) ch 0) (get (:ranges st) ch (:range0 st))))))\n ev (fn [m] (assoc m :src :midi))\n step (fn [st m]\n (let [ch (:ch m)]\n (case (:type m)\n :note-on (let [id (voice-id ch (:note m)) f (r3 (freq-of st ch (:note m))) a (r3 (/ (:vel m) 127))\n offs (when (get (:held st) id) [(ev {:type :note :id id :ch ch :note (:note m) :freq f :gate false})])]\n [(-> st (assoc-in [:held id] {:ch ch :note (:note m) :freq f})\n (update :order (fn [o] (vec (cons id (remove #(= % id) o))))))\n (conj (vec offs) (ev {:type :note :id id :ch ch :note (:note m) :freq f :amp a :gate true}))])\n :note-off (let [id (voice-id ch (:note m)) h (get (:held st) id)]\n (if h\n [(-> st (update :held dissoc id) (update :order (fn [o] (vec (remove #(= % id) o)))))\n [(ev {:type :note :id id :ch ch :note (:note m) :freq (:freq h) :gate false})]]\n [st []]))\n :bend (let [st (assoc-in st [:bends ch] (/ (:value m) (if (neg? (:value m)) 8192 8191)))]\n (reduce (fn [[st out] id]\n (let [{:keys [note]} (get (:held st) id) f (r3 (freq-of st ch note))]\n [(assoc-in st [:held id :freq] f) (conj out (ev {:type :glide :id id :ch ch :note note :freq f}))]))\n [st []] (filter #(= ch (:ch (get (:held st) %))) (:order st))))\n ;; RPN 0 (CC 101 = 0, CC 100 = 0, then CC 6) is the bend range an MPE controller announces: read, not sent\n :cc (let [n (:cc m) rpn (get (:rpn st) ch {})]\n (cond (= n 101) [(assoc-in st [:rpn ch :msb] (:value m)) []]\n (= n 100) [(assoc-in st [:rpn ch :lsb] (:value m)) []]\n (and (= n 6) (= 0 (:msb rpn)) (= 0 (:lsb rpn))) [(assoc-in st [:ranges ch] (:value m)) []]\n (= n 38) [st []]\n :else [st [(ev {:type :cc :ch ch :cc n :value (r4 (/ (:value m) 127))})]]))\n :pressure (let [id (first (filter #(= ch (:ch (get (:held st) %))) (:order st)))]\n [st [(ev (cond-> {:type :pressure :ch ch :value (r4 (/ (:value m) 127))} id (assoc :id id)))]])\n :poly [st [(ev {:type :pressure :ch ch :id (voice-id ch (:note m)) :value (r4 (/ (:value m) 127))})]]\n :program [st [(ev {:type :program :ch ch :value (:value m)})]]\n (:clock :start :stop :continue) [st [(ev {:type (:type m)})]]\n [st []])))\n sounding (fn [st] [(:order st) (mapv #(:freq (get (:held st) %)) (:order st))])\n label (fn [e] (case (:type e)\n :note (str (api/midi-name (:note e)) (if (:gate e) (str \" \" (js/Math.round (* 127 (or (:amp e) 0)))) \" off\"))\n :glide (str (api/nice (:freq e)) \" Hz\")\n :cc (str \"cc \" (:cc e) \" \" (api/nice (:value e)))\n (name (:type e))))]\n {;; ── about ──\n :class \"midiin\"\n :license \"MPL-2.0\"\n :doc \"MIDI from every input of the page (a keyboard, a controller, another program) as Kairotic events, while ▶ runs: a note is {:type :note :id :ch :note :freq :amp :gate}, a pitch bend moves the notes of its channel ({:type :glide :id :freq}), and controllers, pressure, program changes and the clock come as {:type :cc :ch :cc :value 0…1}, {:type :pressure …}, {:type :clock}…. Pitch travels as :freq in Hz: a bend, or an MPE controller (a channel per note; its bend range, RPN 0, is read), is only a different :freq. Out: the Hz of the notes sounding (with [:gain amp] just before a note starts) and their voice ids, as a keyboard or a player sends them, for synth~ or a polyphonic faust~; and every event. channel (0, all) keeps one; range (2) is the bend range of a controller that does not say its own. :clear (or :stop) lets every held note go. Chrome, Edge and Firefox ask once to use MIDI; Safari has no MIDI.\"\n :usage \"midiin [channel] [range]\"\n :io [1 3]\n :size [96 30]\n :args [[:channel 0] [:range 2]]\n :help {:inlets [\":clear (or :stop): every held note goes\"]\n :outlets [\"the Hz of the notes sounding, most recent first ([:gain amp] before a note starts)\" \"their voice ids (note + 128 per channel above the first)\" \"every event, as a map\"]\n :example \"(box :b1 \\\"midiin\\\" 40 30)\\n(box :b2 \\\"synth~\\\" 40 90)\\n(box :b3 \\\"dac~\\\" 40 140)\\n(box :b4 \\\"print\\\" 160 90)\\n(connect :b1 0 :b2 0)\\n(connect :b1 1 :b2 1)\\n(connect :b2 0 :b3 0)\\n(connect :b2 0 :b3 1)\\n(connect :b1 2 :b4 0)\"\n :try \"Press ▶ and play a MIDI keyboard: synth~ plays it and print shows every event. Bend a note: it glides.\"\n :see [\"midiout\" \"keyboard\" \"synth~\" \"oscin\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args]}]\n (let [st (or state (fresh (api/clamp (:range args) 1 96)))]\n (cond\n (and (= inlet :audio) (:error value)) {:effects [[:print (:error value)]] :show {:label \"no MIDI\"}}\n (and (= inlet :audio) (:ports value)) {:state st :show {:label (if (pos? (:ports value)) (str \"midi · \" (:ports value) \" in\") \"no MIDI input\")}}\n (and (= inlet :audio) (:bytes value))\n (let [m (decode (:bytes value))\n ch (:channel args)]\n (if (or (nil? m) (and (pos? ch) (:ch m) (not= ch (:ch m))))\n {:state st}\n (let [[st2 es] (step st m)]\n (if (empty? es)\n {:state st2}\n (let [[ids hz] (sounding st2)\n notes? (some #(#{:note :glide} (:type %)) es)\n on (first (filter #(and (= :note (:type %)) (:gate %)) es))]\n {:state st2\n :show {:label (label (last es))}\n :out (vec (concat (when notes? [[1 ids]])\n (when on [[0 [:gain (:amp on)]]])\n (when notes? [[0 hz]])\n (map (fn [e] [2 e]) es)))})))))\n (#{:clear :stop} value)\n (let [offs (for [id (:order st) :let [h (get (:held st) id)]]\n {:src :midi :type :note :id id :ch (:ch h) :note (:note h) :freq (:freq h) :gate false})]\n {:state (fresh (:range0 st)) :out (vec (concat [[1 []] [0 []]] (map (fn [e] [2 e]) offs)))})\n :else {:state st})))\n\n ;; ── view ──\n :derive (fn [{:keys [shown]}] {:label (or (:label shown) \"midiin\")})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]\n\n ;; ── outside: the inputs, while ▶ runs ──\n :audio {:create (fn [_ b _]\n (let [node {:alive (atom true) :ins (atom []) :inlets [] :outlets []}\n on-msg (fn [e] (when @(:alive node) (api/report! (:id b) {:bytes (vec (js/Array.from (.-data e)))} nil)))\n wire! (fn [m]\n (doseq [i @(:ins node)] (.removeEventListener i \"midimessage\" on-msg))\n (let [ins (vec (js/Array.from (.values (.-inputs m))))]\n (doseq [i ins] (.addEventListener i \"midimessage\" on-msg))\n (reset! (:ins node) ins)\n (api/report! (:id b) {:ports (count ins)} nil)))]\n (assoc node :unwire (fn [] (doseq [i @(:ins node)] (.removeEventListener i \"midimessage\" on-msg)))\n :ready (-> (access)\n (.then (fn [m] (when @(:alive node)\n (wire! m)\n (.addEventListener m \"statechange\" (fn [_] (when @(:alive node) (wire! m)))))))\n (.catch (fn [e] (api/report! (:id b) {:error (str \"midiin: \" (.-message e))} nil)))))))\n :dispose (fn [node] (reset! (:alive node) false) ((:unwire node)))}})\n"
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
"class": "midiout",
|
|
29
|
+
"license": "MPL-2.0",
|
|
30
|
+
"doc": "Notes and events to a MIDI port, while ▶ runs. On the left, what sounds as a player, a keyboard or a reader send it — the Hz of the notes (after their voice ids on the right, and [:gain amp] for the next ones) —, or an event from midiin, oscin or a room ({:type :note :freq :amp :gate}, :glide, :cc…). With mpe, each note gets a channel of its own (2…16) and its exact frequency as a key plus a pitch bend of that channel (range 48 semitones): microtones, just intervals and glides reach the synthesizer without rounding; at ▶ it announces the zone and the range (the MPE configuration message). Without it, one channel (channel, 1) and the nearest key. port (1) is which output of the page. :clear (or :stop) ends every note.",
|
|
31
|
+
"source": ";; midiout · Kairotic events and notes to a MIDI port, plain or MPE (microtones without rounding)\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [access (fn []\n (or (.-kairoticMidi js/window)\n (let [p (if (.-requestMIDIAccess js/navigator)\n (.requestMIDIAccess js/navigator #js {:sysex false})\n (js/Promise.reject (js/Error. \"this browser has no Web MIDI (Chrome, Edge or Firefox; not Safari)\")))]\n (set! (.-kairoticMidi js/window) p)\n (.catch p (fn [_] (set! (.-kairoticMidi js/window) nil)))\n p)))\n clamp (fn [x lo hi] (max lo (min hi x)))\n ;; ── messages → bytes ──\n encode (fn [{:keys [type ch note vel value cc]}]\n (let [c (dec (or ch 1)) b7 (fn [x] (clamp (js/Math.round x) 0 127))]\n (case type\n :note-on [(+ 0x90 c) (b7 note) (b7 vel)]\n :note-off [(+ 0x80 c) (b7 note) 0]\n :cc [(+ 0xB0 c) (b7 cc) (b7 value)]\n :pressure [(+ 0xD0 c) (b7 value)]\n :bend (let [v (+ 8192 (clamp (js/Math.round value) -8192 8191))] [(+ 0xE0 c) (bit-and v 127) (bit-shift-right v 7)])\n :clock [0xF8] :start [0xFA] :continue [0xFB] :stop [0xFC]\n nil)))\n ;; ── events → messages: plain (one channel, rounded) or MPE (a member channel per note) ──\n fresh (fn [mpe ch r] {:mode (if mpe :mpe :plain) :ch ch :range r :voices {} :free (vec (range 2 17)) :n 0})\n bend-of (fn [semis r] (clamp (js/Math.round (* (/ semis r) (if (neg? semis) 8192 8191))) -8192 8191))\n key-and-bend (fn [hz r]\n (let [m (api/hz->midi hz) k (clamp (js/Math.round m) 0 127)\n k (if (> (js/Math.abs (- m k)) r) (clamp (js/Math.round (- m (* (js/Math.sign (- m k)) r))) 0 127) k)]\n [k (bend-of (- m k) r)]))\n vel-of (fn [e] (clamp (js/Math.round (* 127 (or (:amp e) 0.8))) 1 127))\n off (fn [st id]\n (if-let [v (get-in st [:voices id])]\n [(-> st (update :voices dissoc id) (update :free #(if (= :mpe (:mode st)) (conj % (:ch v)) %)))\n [{:type :note-off :ch (:ch v) :note (:key v)}]]\n [st []]))\n on (fn [st e]\n (let [id (or (:id e) (js/Math.round (api/hz->midi (:freq e))))\n [st pre] (off st id)]\n (if (= :mpe (:mode st))\n (let [[st ch pre] (if (seq (:free st))\n [st (first (:free st)) pre]\n ;; every channel busy: the oldest voice gives its own\n (let [[oid v] (apply min-key (fn [[_ v]] (:n v)) (:voices st))]\n [(update st :voices dissoc oid) (:ch v) (conj pre {:type :note-off :ch (:ch v) :note (:key v)})]))\n [k b] (key-and-bend (:freq e) (:range st))]\n [(-> st (update :free #(vec (remove #{ch} %))) (assoc-in [:voices id] {:ch ch :key k :n (:n st)}) (update :n inc))\n (into pre [{:type :bend :ch ch :value b} {:type :note-on :ch ch :note k :vel (vel-of e)}])])\n (let [k (clamp (js/Math.round (api/hz->midi (:freq e))) 0 127)]\n [(-> st (assoc-in [:voices id] {:ch (:ch st) :key k :n (:n st)}) (update :n inc))\n (conj pre {:type :note-on :ch (:ch st) :note k :vel (vel-of e)})]))))\n out-step (fn [st e]\n (let [e (if (and (nil? (:freq e)) (number? (:note e))) (assoc e :freq (api/midi->hz (:note e))) e)]\n (case (:type e)\n (:note nil) (cond (false? (:gate e)) (off st (:id e))\n (and (number? (:freq e)) (pos? (:freq e))) (on st e)\n :else [st []])\n :glide (let [v (get-in st [:voices (:id e)])]\n (if (and v (= :mpe (:mode st)) (number? (:freq e)))\n [st [{:type :bend :ch (:ch v) :value (bend-of (- (api/hz->midi (:freq e)) (:key v)) (:range st))}]]\n [st []]))\n :cc [st [{:type :cc :ch (or (:ch e) (:ch st)) :cc (:cc e) :value (* 127 (:value e))}]]\n :pressure [st (if-let [v (get-in st [:voices (:id e)])] [{:type :pressure :ch (:ch v) :value (* 127 (:value e))}] [])]\n (:clock :start :stop :continue) [st [{:type (:type e)}]]\n [st []])))\n events (fn [st es] (reduce (fn [[st ms] e] (let [[st m] (out-step st e)] [st (into ms m)])) [st []] es))\n ;; a snapshot of what sounds (Hz and voice ids, as a player or a keyboard sends them) against the one before\n diff (fn [before after amp]\n (let [pairs (fn [{:keys [hz ids]}] (into {} (map vector (or (seq ids) (map #(js/Math.round (api/hz->midi %)) hz)) hz)))\n a (pairs before) b (pairs after)]\n (vec (concat (for [[id _] a :when (not (contains? b id))] {:type :note :id id :gate false})\n (for [[id f] b :when (and (contains? a id) (not= f (get a id)))] {:type :glide :id id :freq f})\n (for [[id f] (reverse (seq b)) :when (not (contains? a id))] {:type :note :id id :freq f :amp amp :gate true})))))\n setup (fn [r] (vec (concat [{:type :cc :ch 1 :cc 101 :value 0} {:type :cc :ch 1 :cc 100 :value 6} {:type :cc :ch 1 :cc 6 :value 15}]\n (mapcat (fn [ch] [{:type :cc :ch ch :cc 101 :value 0} {:type :cc :ch ch :cc 100 :value 0}\n {:type :cc :ch ch :cc 6 :value r} {:type :cc :ch ch :cc 101 :value 127} {:type :cc :ch ch :cc 100 :value 127}])\n (range 2 17)))))\n send (fn [st ms] (if (seq ms) {:state st :effects [[:send (vec (keep encode ms))]] :show {:n (count ms)}} {:state st}))]\n {;; ── about ──\n :class \"midiout\"\n :license \"MPL-2.0\"\n :doc \"Notes and events to a MIDI port, while ▶ runs. On the left, what sounds as a player, a keyboard or a reader send it — the Hz of the notes (after their voice ids on the right, and [:gain amp] for the next ones) —, or an event from midiin, oscin or a room ({:type :note :freq :amp :gate}, :glide, :cc…). With mpe, each note gets a channel of its own (2…16) and its exact frequency as a key plus a pitch bend of that channel (range 48 semitones): microtones, just intervals and glides reach the synthesizer without rounding; at ▶ it announces the zone and the range (the MPE configuration message). Without it, one channel (channel, 1) and the nearest key. port (1) is which output of the page. :clear (or :stop) ends every note.\"\n :usage \"midiout [mpe] [channel] [port] [range]\"\n :io [2 0]\n :size [96 30]\n :args [[:mpe false] [:channel 1] [:port 1] [:range 48]]\n :help {:inlets [\"the Hz of the notes sounding (a list), [:gain amp], an event map, or :clear (or :stop)\" \"the voice ids of the Hz that follow\"]\n :outlets []\n :example \"(box :b1 \\\"keyboard\\\" 40 30)\\n(box :b2 \\\"midiout mpe\\\" 40 120)\\n(connect :b1 0 :b2 0)\\n(connect :b1 1 :b2 1)\"\n :try \"Press ▶ and play the keyboard: the notes go to the first MIDI output of the page. With an MPE synthesizer, a freqt read by a reader~ glides there without steps.\"\n :see [\"midiin\" \"synth~\" \"player\" \"oscout\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args]}]\n (let [st (or state {:enc (fresh (:mpe args) (api/clamp (:channel args) 1 16) (api/clamp (:range args) 1 96)) :snap {:hz [] :ids []} :ids nil :amp 0.8})\n enc (:enc st)]\n (cond\n (and (= inlet :audio) (:error value)) {:state st :effects [[:print (:error value)]] :show {:label \"no MIDI\"}}\n (and (= inlet :audio) (contains? value :port)) {:state st :show {:label (or (:port value) \"no MIDI output\")}}\n (= inlet :audio) {:state st}\n (= inlet 1) {:state (assoc st :ids (when (sequential? value) (vec value)))}\n (and (vector? value) (= :gain (first value)) (number? (second value))) {:state (assoc st :amp (api/clamp (second value) 0 1))}\n (#{:clear :stop} value)\n (let [[e2 ms] (events enc (map (fn [id] {:type :note :id id :gate false}) (keys (:voices enc))))]\n (send (assoc st :enc e2 :snap {:hz [] :ids []}) ms))\n (map? value) (let [[e2 ms] (out-step enc value)] (send (assoc st :enc e2) ms))\n (or (number? value) (sequential? value))\n (let [hz (vec (filter number? (if (number? value) [value] value)))\n snap {:hz hz :ids (when (= (count (:ids st)) (count hz)) (:ids st))}\n [e2 ms] (events enc (diff (:snap st) snap (:amp st)))]\n (send (assoc st :enc e2 :snap snap) ms))\n :else {:state st})))\n\n ;; ── view ──\n :derive (fn [{:keys [shown args]}] {:label (or (:label shown) (str \"midiout\" (when (:mpe args) \" mpe\")))})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]\n\n ;; ── outside: the port, while ▶ runs ──\n :audio {:create (fn [ac b _]\n (let [words (rest (.split (.trim (str (:text b))) #\"\\s+\"))\n mpe (some #{\"mpe\"} words)\n nums (keep #(let [n (js/parseFloat %)] (when-not (js/isNaN n) n)) words)\n port-n (or (second nums) 1)\n r (or (nth nums 2 nil) 48)\n node {:ac ac :port (atom nil) :alive (atom true) :inlets [] :outlets []}]\n (-> (access)\n (.then (fn [m]\n (when @(:alive node)\n (let [outs (vec (js/Array.from (.values (.-outputs m))))\n p (get outs (dec port-n))]\n (reset! (:port node) p)\n (api/report! (:id b) {:port (when p (str \"→ \" (.-name p)))} nil)\n (when (and p mpe) (doseq [msg (setup r)] (.send p (clj->js (encode msg)))))))))\n (.catch (fn [e] (api/report! (:id b) {:error (str \"midiout: \" (.-message e))} nil))))\n node))\n :effects {:send (fn [node bytes at]\n (when-let [p @(:port node)]\n (let [ac (:ac node)\n ;; at the time of the message on the audio clock, as a time of the page\n ts (+ (js/performance.now) (* 1000 (max 0 (- (or at 0) (.-currentTime ac)))))]\n (doseq [b bytes] (.send p (clj->js b) ts)))))}\n :dispose (fn [node]\n (reset! (:alive node) false)\n ;; nothing left sounding on the synthesizer\n (when-let [p @(:port node)]\n (doseq [ch (range 16)] (.send p #js [(+ 0xB0 ch) 123 0]))))}})\n"
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
"class": "motion",
|
|
35
|
+
"license": "MPL-2.0",
|
|
36
|
+
"doc": "A phone's (or a tablet's) motion while ▶ runs: its tilt as x (left 0 … right 1) and y (towards you 0 … away 1), both 0.5 lying flat — smoothed, and sent only when it moves —; and a shake, when it is shaken harder than shake (14 m/s²), once with a pause after it. Out: [x y], the strength of each shake, and the events ({:type :tilt :x :y :alpha :beta :gamma}, {:type :shake :value}) for oscout or a room. smooth (0.3) is how much of the last value stays at each reading. iOS asks for permission at ▶. Open the work on the phone (Share/Export, Release/Perform) to play with it.",
|
|
37
|
+
"source": ";; motion · a phone's tilt and shake as Kairotic events\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [r (fn [x d] (let [k (js/Math.pow 10 d)] (/ (js/Math.round (* x k)) k)))\n clamp (fn [x lo hi] (max lo (min hi x)))\n ;; the tilt as x (left 0 … right 1) and y (towards you 0 … away 1), both 0.5 lying flat\n tilt-xy (fn [beta gamma] [(clamp (/ (+ gamma 90) 180) 0 1) (clamp (/ (+ (clamp beta -90 90) 90) 180) 0 1)])\n mag (fn [[x y z]] (js/Math.sqrt (+ (* x x) (* y y) (* z z))))\n ;; a reading: smoothed, and sent only when it moves (sensors read ~60 times a second, moving or not);\n ;; a shake is one event, with a pause after it\n step (fn [st t rd smooth shake]\n (cond\n (number? (:gamma rd))\n (let [[tx ty] (tilt-xy (or (:beta rd) 0) (:gamma rd))\n x (if (:x st) (+ (* smooth (:x st)) (* (- 1 smooth) tx)) tx)\n y (if (:y st) (+ (* smooth (:y st)) (* (- 1 smooth) ty)) ty)\n [sx sy] (:sent st) st (assoc st :x x :y y)]\n (if (and sx (< (js/Math.abs (- x sx)) 0.004) (< (js/Math.abs (- y sy)) 0.004))\n [st nil]\n [(assoc st :sent [x y])\n (cond-> {:src :motion :type :tilt :x (r x 3) :y (r y 3) :beta (r (or (:beta rd) 0) 1) :gamma (r (:gamma rd) 1)}\n (number? (:alpha rd)) (assoc :alpha (r (:alpha rd) 1)))]))\n (or (:acc rd) (:accg rd))\n (let [m (if (:acc rd) (mag (:acc rd)) (js/Math.abs (- (mag (:accg rd)) 9.81)))]\n (if (and (> m shake) (or (nil? (:last-shake st)) (>= (- t (:last-shake st)) 0.3)))\n [(assoc st :last-shake t) {:src :motion :type :shake :value (r m 1)}]\n [st nil]))\n :else [st nil]))]\n {;; ── about ──\n :class \"motion\"\n :license \"MPL-2.0\"\n :doc \"A phone's (or a tablet's) motion while ▶ runs: its tilt as x (left 0 … right 1) and y (towards you 0 … away 1), both 0.5 lying flat — smoothed, and sent only when it moves —; and a shake, when it is shaken harder than shake (14 m/s²), once with a pause after it. Out: [x y], the strength of each shake, and the events ({:type :tilt :x :y :alpha :beta :gamma}, {:type :shake :value}) for oscout or a room. smooth (0.3) is how much of the last value stays at each reading. iOS asks for permission at ▶. Open the work on the phone (Share/Export, Release/Perform) to play with it.\"\n :usage \"motion [smooth] [shake]\"\n :io [0 3]\n :size [96 30]\n :args [[:smooth 0.3] [:shake 14]]\n :help {:inlets []\n :outlets [\"[x y], 0…1 each, when the tilt moves\" \"the strength of a shake (m/s²)\" \"every event, as a map\"]\n :example \"(box :b1 \\\"motion\\\" 40 30)\\n(box :b2 \\\"print\\\" 40 80)\\n(connect :b1 0 :b2 0)\"\n :try \"Open this on a phone, press ▶, and tilt it.\"\n :see [\"gamepad\" \"oscout\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args at]}]\n (if (and (= inlet :audio) (map? value))\n (if (:error value)\n {:effects [[:print (:error value)]] :show {:label \"no motion\"}}\n (let [[st e] (step (or state {}) (or at 0) value (api/clamp (:smooth args) 0 0.95) (api/clamp (:shake args) 2 60))]\n (cond\n (nil? e) {:state st}\n (= :tilt (:type e)) {:state st :out [[0 [(:x e) (:y e)]] [2 e]] :show {:x (:x e) :y (:y e)}}\n :else {:state st :out [[1 (:value e)] [2 e]] :show (assoc (select-keys st [:x :y]) :shake true)})))\n {}))\n\n ;; ── view: where the tilt is ──\n :derive (fn [{:keys [shown]}] {:cx (+ 60 (* 30 (- (or (:x shown) 0.5) 0.5) 2)) :cy (+ 15 (* 10 (- 0.5 (or (:y shown) 0.5)) 2))\n :dot (if (:shake shown) :kairos :accent)})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 6 :y 19 :size 10 :fill :soft} \"motion\"]\n [:rect {:x 46 :y 4 :w 46 :h 22 :r 2 :stroke :grid :fill :bg}]\n [:circle {:cx :$cx :cy :$cy :r 4 :stroke :$dot :fill :$dot}]]\n\n ;; ── outside: the sensors, while ▶ runs ──\n :audio {:create (fn [_ b _]\n (let [node {:alive (atom true) :inlets [] :outlets []}\n report (fn [rd] (when @(:alive node) (api/report! (:id b) rd nil)))\n on-tilt (fn [e] (when (number? (.-gamma e)) (report {:alpha (.-alpha e) :beta (.-beta e) :gamma (.-gamma e)})))\n on-move (fn [e] (let [a (.-acceleration e) g (.-accelerationIncludingGravity e)]\n (cond (and a (number? (.-x a))) (report {:acc [(.-x a) (.-y a) (.-z a)]})\n (and g (number? (.-x g))) (report {:accg [(.-x g) (.-y g) (.-z g)]}))))\n listen! (fn [] (.addEventListener js/window \"deviceorientation\" on-tilt)\n (.addEventListener js/window \"devicemotion\" on-move))\n ask (some-> (.-DeviceOrientationEvent js/window) .-requestPermission)]\n ;; iOS asks first, and only from a gesture: ▶ is one\n (if (fn? ask)\n (-> (ask) (.then (fn [r] (if (= r \"granted\") (listen!) (report {:error \"motion: refused\"}))))\n (.catch (fn [e] (report {:error (str \"motion: \" (.-message e))}))))\n (listen!))\n (assoc node :off (fn [] (.removeEventListener js/window \"deviceorientation\" on-tilt)\n (.removeEventListener js/window \"devicemotion\" on-move)))))\n :dispose (fn [node] (reset! (:alive node) false) ((:off node)))}})\n"
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
"class": "oscin",
|
|
41
|
+
"license": "MPL-2.0",
|
|
42
|
+
"doc": "OSC in, through a relay's OSC bridge (npx @kairotic/relay --osc, on this machine), while ▶ runs: what SuperCollider, Max, Pd or TouchOSC send to the relay's port (57121) arrives here. The addresses oscout writes are events again (/kairotic/note id freq amp gate is {:type :note …}, /kairotic/glide, /kairotic/cc, /kairotic/tilt…); any other one is {:type :osc :address \"/x\" :args […] :from \"host:port\"}. pattern takes only the addresses that match it (OSC patterns: ? * [a-z] [!a] {note,glide}): oscin /synth/*/cutoff. Out: the event, and its values alone (the args of an OSC message; the Hz of a note) for a number box. [:relay \"ws://…\"] changes the bridge for the whole page.",
|
|
43
|
+
"source": ";; oscin · OSC in, through a relay's bridge: from SuperCollider, Max, Pd, TouchOSC… as Kairotic events\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [default-url \"ws://localhost:8765/osc\"\n relay-url (fn [] (or (try (.getItem js/localStorage \"kairotic-osc-relay\") (catch :default _ nil)) default-url))\n ;; the same shared sockets as oscout (one per address, for every osc box of the page)\n socket (fn [url]\n (let [all (or (.-kairoticOsc js/window) (set! (.-kairoticOsc js/window) #js {}))\n s (aget all url)]\n (if (and s (< (.. s -ws -readyState) 2))\n s\n (let [ws (js/WebSocket. url)\n s #js {:ws ws :listeners #js [] :queue #js []}]\n (set! (.-onopen ws) (fn [_] (doseq [m (js/Array.from (.-queue s))] (.send ws m)) (set! (.-queue s) #js [])))\n (set! (.-onmessage ws) (fn [e] (let [f (try (js/JSON.parse (.-data e)) (catch :default _ nil))]\n (when f (doseq [l (js/Array.from (.-listeners s))] (l f))))))\n (aset all url s)\n s))))\n r4 (fn [x] (if (number? x) (/ (js/Math.round (* x 10000)) 10000) x))\n ;; ── the /kairotic/… addresses are events again; any other address arrives as it is ──\n osc->event (fn [{:keys [address args from]}]\n (let [a (vec args)]\n (merge (cond-> {:src :osc} from (assoc :from from))\n (case address\n \"/kairotic/note\" (cond-> {:type :note :id (nth a 0 0) :gate (not= 0 (nth a 3 1))}\n (number? (get a 1)) (assoc :freq (r4 (get a 1)))\n (and (number? (get a 2)) (not= 0 (nth a 3 1))) (assoc :amp (r4 (get a 2))))\n \"/kairotic/glide\" {:type :glide :id (nth a 0 0) :freq (r4 (nth a 1 0))}\n \"/kairotic/cc\" {:type :cc :ch (nth a 0 1) :cc (nth a 1 0) :value (r4 (nth a 2 0))}\n \"/kairotic/pressure\" {:type :pressure :id (nth a 0 0) :value (r4 (nth a 1 0))}\n \"/kairotic/tilt\" {:type :tilt :x (r4 (nth a 0 0.5)) :y (r4 (nth a 1 0.5))}\n \"/kairotic/shake\" {:type :shake :value (r4 (nth a 0 0))}\n (\"/kairotic/clock\" \"/kairotic/start\" \"/kairotic/stop\" \"/kairotic/continue\") {:type (keyword (subs address 10))}\n {:type :osc :address address :args (mapv r4 a)}))))\n ;; ── OSC address patterns (OSC 1.0): ? * [a-z] [!a] {foo,bar}, none of them across a / ──\n re-esc (fn [s] (.replace s (js/RegExp. \"[.*+?^${}()|[\\\\]\\\\\\\\]\" \"g\") \"\\\\$&\"))\n pattern-re (fn [p]\n (loop [cs (seq p) out \"^\"]\n (if-not cs\n (js/RegExp. (str out \"$\"))\n (let [c (first cs)]\n (case c\n \"?\" (recur (next cs) (str out \"[^/]\"))\n \"*\" (recur (next cs) (str out \"[^/]*\"))\n \"[\" (let [body (take-while #(not= \"]\" %) (next cs)) neg (= \"!\" (first body))\n body (apply str (if neg (rest body) body))]\n (recur (next (drop-while #(not= \"]\" %) (next cs)))\n (str out \"[\" (when neg \"^\") (.replace body (js/RegExp. \"[\\\\\\\\^]\" \"g\") \"\\\\$&\") \"]\")))\n \"{\" (let [body (apply str (take-while #(not= \"}\" %) (next cs)))]\n (recur (next (drop-while #(not= \"}\" %) (next cs)))\n (str out \"(?:\" (apply str (interpose \"|\" (map re-esc (.split body \",\")))) \")\")))\n (recur (next cs) (str out (re-esc c))))))))\n matches? (fn [p address] (or (empty? p) (boolean (.test (pattern-re p) address))))]\n {;; ── about ──\n :class \"oscin\"\n :license \"MPL-2.0\"\n :doc \"OSC in, through a relay's OSC bridge (npx @kairotic/relay --osc, on this machine), while ▶ runs: what SuperCollider, Max, Pd or TouchOSC send to the relay's port (57121) arrives here. The addresses oscout writes are events again (/kairotic/note id freq amp gate is {:type :note …}, /kairotic/glide, /kairotic/cc, /kairotic/tilt…); any other one is {:type :osc :address \\\"/x\\\" :args […] :from \\\"host:port\\\"}. pattern takes only the addresses that match it (OSC patterns: ? * [a-z] [!a] {note,glide}): oscin /synth/*/cutoff. Out: the event, and its values alone (the args of an OSC message; the Hz of a note) for a number box. [:relay \\\"ws://…\\\"] changes the bridge for the whole page.\"\n :usage \"oscin [pattern]\"\n :io [1 2]\n :size [110 30]\n :help {:inlets [\"[:relay \\\"ws://…/osc\\\"]\"]\n :outlets [\"every message that matches, as an event\" \"its values: the args of an OSC message, or the Hz of a note\"]\n :example \"(box :b1 \\\"oscin /kairotic/*\\\" 40 30)\\n(box :b2 \\\"print\\\" 40 80)\\n(connect :b1 0 :b2 0)\"\n :try \"Run npx @kairotic/relay --osc, press ▶, and from SuperCollider: NetAddr(\\\"127.0.0.1\\\", 57121).sendMsg(\\\"/kairotic/note\\\", 1, 440, 0.5, 1).\"\n :see [\"oscout\" \"midiin\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value]}]\n (cond\n (and (= inlet :audio) (:event value))\n (let [e (:event value)]\n {:out [[1 (if (= :osc (:type e)) (:args e) (or (:freq e) (:value e) (:x e)))] [0 e]]\n :show {:label (or (:address e) (str \"/kairotic/\" (name (:type e))))}})\n (and (= inlet :audio) (:status value)) {:show {:label (:status value)}}\n (and (vector? value) (= :relay (first value)) (string? (second value)))\n {:effects [[:relay (second value)]] :show {:label \"relay set: ▶ again\"}}\n :else {}))\n :tasks {:relay (fn [url _] (try (.setItem js/localStorage \"kairotic-osc-relay\" url) (catch :default _ nil)) (js/Promise.resolve url))}\n\n ;; ── view ──\n :derive (fn [{:keys [shown]}] {:label (or (:label shown) \"oscin\")})\n :view [[:rect {:x 1 :y 1 :w 108 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]\n\n ;; ── outside: the bridge, while ▶ runs ──\n :audio {:create (fn [_ b _]\n (let [pattern (or (second (.split (.trim (str (:text b))) #\"\\s+\")) \"\")\n node {:alive (atom true) :inlets [] :outlets []}\n s (socket (relay-url))\n l (fn [f] (when (and @(:alive node) (.-address f) (matches? pattern (.-address f)))\n (api/report! (:id b) {:event (osc->event (js->clj f :keywordize-keys true))} nil)))]\n (.push (.-listeners s) l)\n (set! (.. s -ws -onerror)\n (fn [_] (api/report! (:id b) {:status \"no relay: npx @kairotic/relay --osc\"} nil)))\n (assoc node :off (fn [] (set! (.-listeners s) (.filter (.-listeners s) (fn [x & _] (not= x l))))))))\n :dispose (fn [node] (reset! (:alive node) false) ((:off node)))}})\n"
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
"class": "oscout",
|
|
47
|
+
"license": "MPL-2.0",
|
|
48
|
+
"doc": "OSC out, through a relay's OSC bridge (npx @kairotic/relay --osc, on this machine): an event (from midiin, motion, gamepad, a room…) goes as /kairotic/note id freq amp gate, /kairotic/glide id freq, /kairotic/cc ch cc value, /kairotic/tilt x y, /kairotic/pad/<name> value [gate]…; a list that starts with an address goes as it is (/synth/freq 440, a message box). target is the name the relay was given for a destination (--osc-out sc=127.0.0.1:57120: sc), its first one if none. [:relay \"ws://…\"] changes the bridge for the whole page (ws://localhost:8765/osc). It sends with or without ▶.",
|
|
49
|
+
"source": ";; oscout · Kairotic events and messages as OSC, through a relay's bridge (SuperCollider, Max, Pd, TouchOSC…)\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [;; ── the bridge: one socket per address, shared by every osc box of the page ──\n ;; A page cannot send UDP: the relay started with --osc does it (npx @kairotic/relay --osc).\n default-url \"ws://localhost:8765/osc\"\n relay-url (fn [] (or (try (.getItem js/localStorage \"kairotic-osc-relay\") (catch :default _ nil)) default-url))\n socket (fn [url]\n (let [all (or (.-kairoticOsc js/window) (set! (.-kairoticOsc js/window) #js {}))\n s (aget all url)]\n (if (and s (< (.. s -ws -readyState) 2))\n s\n (let [ws (js/WebSocket. url)\n s #js {:ws ws :listeners #js [] :queue #js []}]\n (set! (.-onopen ws) (fn [_] (doseq [m (js/Array.from (.-queue s))] (.send ws m)) (set! (.-queue s) #js [])))\n (set! (.-onmessage ws) (fn [e] (let [f (try (js/JSON.parse (.-data e)) (catch :default _ nil))]\n (when f (doseq [l (js/Array.from (.-listeners s))] (l f))))))\n (aset all url s)\n s))))\n send! (fn [url m] (let [s (socket url) ws (.-ws s) j (js/JSON.stringify (clj->js m))]\n (if (= 1 (.-readyState ws)) (.send ws j) (.push (.-queue s) j))))\n num (fn [x] (if (number? x) x 0))\n ;; ── an event as OSC: /kairotic/<type> with its values in a fixed order, for a SynthDef or a Max patch ──\n event->osc (fn [e]\n (case (:type e)\n :note {:address \"/kairotic/note\" :types \"iffi\" :args [(num (:id e)) (num (:freq e)) (num (or (:amp e) (when (:gate e) 0.8))) (if (:gate e) 1 0)]}\n :glide {:address \"/kairotic/glide\" :types \"if\" :args [(num (:id e)) (num (:freq e))]}\n :cc {:address \"/kairotic/cc\" :types \"iif\" :args [(num (:ch e)) (num (:cc e)) (num (:value e))]}\n :pressure {:address \"/kairotic/pressure\" :types \"if\" :args [(num (:id e)) (num (:value e))]}\n :tilt {:address \"/kairotic/tilt\" :types \"ff\" :args [(:x e) (:y e)]}\n :shake {:address \"/kairotic/shake\" :types \"f\" :args [(:value e)]}\n (:button :axis) {:address (str \"/kairotic/pad/\" (if (:name e) (name (:name e)) (str (if (= :axis (:type e)) \"a\" \"b\") (or (:axis e) (:button e)))))\n :args (if (some? (:gate e)) [(:value e) (if (:gate e) 1 0)] [(:value e)])}\n :serial (cond (:values e) {:address \"/kairotic/serial\" :args (vec (:values e))}\n (number? (:value e)) {:address (str \"/kairotic/serial/\" (:key e)) :args [(:value e)]}\n :else {:address \"/kairotic/serial\" :types \"s\" :args [(str (:text e))]})\n (:clock :start :stop :continue) {:address (str \"/kairotic/\" (name (:type e))) :args []}\n nil))\n ;; a list that starts with an address: (/synth/freq 440) → /synth/freq 440\n address? (fn [x] (let [s (cond (string? x) x (keyword? x) (str (when (namespace x) (str (namespace x) \"/\")) (name x)) (symbol? x) (str x))]\n (when (and s (= \"/\" (subs s 0 1))) s)))\n clean (fn [x] (cond (keyword? x) (name x) (or (number? x) (string? x) (boolean? x)) x :else (str x)))]\n {;; ── about ──\n :class \"oscout\"\n :license \"MPL-2.0\"\n :doc \"OSC out, through a relay's OSC bridge (npx @kairotic/relay --osc, on this machine): an event (from midiin, motion, gamepad, a room…) goes as /kairotic/note id freq amp gate, /kairotic/glide id freq, /kairotic/cc ch cc value, /kairotic/tilt x y, /kairotic/pad/<name> value [gate]…; a list that starts with an address goes as it is (/synth/freq 440, a message box). target is the name the relay was given for a destination (--osc-out sc=127.0.0.1:57120: sc), its first one if none. [:relay \\\"ws://…\\\"] changes the bridge for the whole page (ws://localhost:8765/osc). It sends with or without ▶.\"\n :usage \"oscout [target]\"\n :io [1 0]\n :size [96 30]\n :args [[:target nil]]\n :help {:inlets [\"an event map, a list (address args…), or [:relay \\\"ws://…/osc\\\"]\"]\n :outlets []\n :example \"(box :b1 \\\"msg /kairotic/hello 1 2.5\\\" 40 30)\\n(box :b2 \\\"oscout\\\" 40 80)\\n(connect :b1 0 :b2 0)\"\n :try \"Run npx @kairotic/relay --osc on this machine and click the message: SuperCollider (sclang, port 57120) receives /kairotic/hello 1 2.5.\"\n :see [\"oscin\" \"midiout\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [value args]}]\n (cond\n (and (vector? value) (= :relay (first value)) (string? (second value)))\n {:effects [[:relay (second value)]] :show {:label \"relay set\"}}\n (and (map? value) (not= :osc (:src value)))\n (if-let [m (event->osc value)]\n {:effects [[:osc (cond-> m (:target args) (assoc :to (name (:target args))))]] :show {:label (:address m)}}\n {})\n (and (sequential? value) (address? (first value)))\n (let [m {:address (address? (first value)) :args (mapv clean (rest value))}]\n {:effects [[:osc (cond-> m (:target args) (assoc :to (name (:target args))))]] :show {:label (:address m)}})\n :else {}))\n ;; with or without ▶: OSC is a message, not a sound\n :tasks {:osc (fn [m _] (send! (relay-url) m) (js/Promise.resolve true))\n :relay (fn [url _] (try (.setItem js/localStorage \"kairotic-osc-relay\" url) (catch :default _ nil)) (js/Promise.resolve url))}\n\n ;; ── view ──\n :derive (fn [{:keys [shown args]}] {:label (or (:label shown) (str \"oscout\" (when (:target args) (str \" \" (name (:target args))))))})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]})\n"
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
"class": "serial",
|
|
53
|
+
"license": "MPL-2.0",
|
|
54
|
+
"doc": "A board on a serial port — an Arduino's Serial.println, an ESP32… — while ▶ runs. open (a click: the browser asks which port) at baud (115200); close lets it go. Each line it sends: numbers (\"512 300 1\", or with commas) go out as a list on the left; key:value pairs (\"pot:512 light=300\") as [key value] each; anything else as text; and every line as events on the right ({:type :serial :values […]}, {:type :serial :key \"pot\" :value 512}, {:type :serial :text …}). A text or a list on the left goes to the board as a line — a text is always a line, even \"open\"; the orders are :open and :close. Web Serial: Chrome, Edge and Firefox 151+; not Safari.",
|
|
55
|
+
"source": ";; serial · a board on a serial port (an Arduino, an ESP32…): its lines of text as values and events\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [number-of (fn [s] (when (re-matches #\"[-+]?(\\d+\\.?\\d*|\\.\\d+)([eE][-+]?\\d+)?\" s) (js/parseFloat s)))\n ;; a line: \"512 300 1\" (or with commas) → values; \"pot:512 light=300\" → one event per key; else text\n line-events (fn [line]\n (let [line (.trim line) ev (fn [m] (merge {:src :serial :type :serial} m))\n words (remove empty? (.split line (js/RegExp. \"[\\\\s,;]+\")))]\n (cond\n (empty? line) []\n (every? number-of words) [(ev {:values (mapv number-of words)})]\n (every? #(re-matches #\"[^:=]+[:=][^:=]+\" %) words)\n (vec (for [w words :let [[k v] (.split w (js/RegExp. \"[:=]\"))]]\n (ev (if-let [n (number-of v)] {:key k :value n} {:key k :text v}))))\n :else [(ev {:text line})])))\n ;; text comes in pieces that do not respect lines: what follows the last newline waits for the next\n chunk (fn [buf text]\n (let [lines (.split (str buf text) (js/RegExp. \"\\\\r?\\\\n\"))\n rest-buf (last lines)]\n [(if (> (count rest-buf) 512) \"\" rest-buf) (vec (mapcat line-events (butlast lines)))]))]\n {;; ── about ──\n :class \"serial\"\n :license \"MPL-2.0\"\n :doc \"A board on a serial port — an Arduino's Serial.println, an ESP32… — while ▶ runs. open (a click: the browser asks which port) at baud (115200); close lets it go. Each line it sends: numbers (\\\"512 300 1\\\", or with commas) go out as a list on the left; key:value pairs (\\\"pot:512 light=300\\\") as [key value] each; anything else as text; and every line as events on the right ({:type :serial :values […]}, {:type :serial :key \\\"pot\\\" :value 512}, {:type :serial :text …}). A text or a list on the left goes to the board as a line — a text is always a line, even \\\"open\\\"; the orders are :open and :close. Web Serial: Chrome, Edge and Firefox 151+; not Safari.\"\n :usage \"serial [baud]\"\n :io [1 2]\n :size [96 30]\n :args [[:baud 115200]]\n :help {:inlets [\":open (asks for the port), :close, or a line to send to the board\"]\n :outlets [\"the numbers of a line (a list), or [key value] for each key:value\" \"every line, as events\"]\n :example \"(box :b1 \\\"msg :open\\\" 40 30)\\n(box :b2 \\\"serial 9600\\\" 40 70)\\n(box :b3 \\\"print\\\" 40 120)\\n(connect :b1 0 :b2 0)\\n(connect :b2 0 :b3 0)\"\n :try \"Press ▶, click open and choose the board's port: what it prints arrives as numbers.\"\n :see [\"motion\" \"gamepad\" \"oscout\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args]}]\n (let [buf (or (:buf state) \"\")]\n (cond\n (and (= inlet :audio) (:error value)) {:state state :effects [[:print (:error value)]] :show {:label \"no port\"}}\n (and (= inlet :audio) (:status value)) {:state state :show {:label (:status value)}}\n (and (= inlet :audio) (string? (:text value)))\n (let [[b2 es] (chunk buf (:text value))]\n (cond-> {:state (assoc state :buf b2)\n :out (vec (mapcat (fn [e] [(cond (:values e) [0 (:values e)]\n (contains? e :value) [0 [(:key e) (:value e)]]\n :else [0 (or (:text e) \"\")])\n [1 e]])\n es))\n }\n (seq es) (assoc :show {:label (let [e (last es)] (cond (:values e) (str (:values e)) (:key e) (str (:key e) \" \" (or (:value e) (:text e))) :else (:text e)))})))\n (#{:open} value) {:effects [[:open (api/clamp (:baud args) 300 4000000)]]}\n (#{:close} value) {:effects [[:close true]]}\n (string? value) {:effects [[:write value]]}\n (sequential? value) {:effects [[:write (apply str (interpose \" \" (map #(if (keyword? %) (name %) (str %)) value)))]]}\n :else {})))\n\n ;; ── view ──\n :derive (fn [{:keys [shown]}] {:label (or (:label shown) \"serial\")})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]\n\n ;; ── outside: the port, while ▶ runs ──\n :audio {:create (fn [_ b _] {:id (:id b) :port (atom nil) :writer (atom nil) :reader (atom nil) :alive (atom true) :inlets [] :outlets []})\n :effects {:open (fn [node baud _]\n (let [report (fn [v] (when @(:alive node) (api/report! (:id node) v nil)))]\n (if-not (.-serial js/navigator)\n (report {:error \"serial: this browser has no Web Serial (Chrome, Edge or Firefox 151+)\"})\n (-> (.requestPort (.-serial js/navigator))\n (.then (fn [port] (.then (.open port #js {:baudRate baud}) (fn [_] port))))\n (.then (fn [port]\n (reset! (:port node) port)\n (reset! (:writer node) (.getWriter (.-writable port)))\n (report {:status (str \"open · \" baud)})\n (let [dec (js/TextDecoderStream.)\n _ (.catch (.pipeTo (.-readable port) (.-writable dec)) (fn [_] nil))\n reader (.getReader (.-readable dec))]\n (reset! (:reader node) reader)\n ((fn step []\n (-> (.read reader)\n (.then (fn [r] (if (.-done r)\n (report {:status \"closed\"})\n (do (report {:text (.-value r)}) (step)))))\n (.catch (fn [_] (report {:status \"closed\"})))))))))\n (.catch (fn [e] (report {:error (str \"serial: \" (.-message e))})))))))\n :write (fn [node line _]\n (when-let [w @(:writer node)] (.write w (.encode (js/TextEncoder.) (str line \"\\n\")))))\n :close (fn [node _ _]\n (when-let [r @(:reader node)] (.catch (.cancel r) (fn [_] nil)))\n (when-let [w @(:writer node)] (.releaseLock w))\n (when-let [p @(:port node)] (js/setTimeout (fn [] (.catch (.close p) (fn [_] nil))) 50))\n (reset! (:port node) nil) (reset! (:writer node) nil))}\n :dispose (fn [node]\n (reset! (:alive node) false)\n (when-let [r @(:reader node)] (.catch (.cancel r) (fn [_] nil)))\n (when-let [w @(:writer node)] (try (.releaseLock w) (catch :default _ nil)))\n (when-let [p @(:port node)] (js/setTimeout (fn [] (.catch (.close p) (fn [_] nil))) 50)))}})\n"
|
|
56
|
+
}
|
|
57
|
+
]
|
|
58
|
+
};
|
package/dist/midiin.mjs
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Generated by packages/build.mjs from src/midiin.cljs
|
|
2
|
+
export default {
|
|
3
|
+
"class": "midiin",
|
|
4
|
+
"version": "0.2.5",
|
|
5
|
+
"author": "bonuoq",
|
|
6
|
+
"license": "MPL-2.0",
|
|
7
|
+
"doc": "MIDI from every input of the page (a keyboard, a controller, another program) as Kairotic events, while ▶ runs: a note is {:type :note :id :ch :note :freq :amp :gate}, a pitch bend moves the notes of its channel ({:type :glide :id :freq}), and controllers, pressure, program changes and the clock come as {:type :cc :ch :cc :value 0…1}, {:type :pressure …}, {:type :clock}…. Pitch travels as :freq in Hz: a bend, or an MPE controller (a channel per note; its bend range, RPN 0, is read), is only a different :freq. Out: the Hz of the notes sounding (with [:gain amp] just before a note starts) and their voice ids, as a keyboard or a player sends them, for synth~ or a polyphonic faust~; and every event. channel (0, all) keeps one; range (2) is the bend range of a controller that does not say its own. :clear (or :stop) lets every held note go. Chrome, Edge and Firefox ask once to use MIDI; Safari has no MIDI.",
|
|
8
|
+
"source": ";; midiin · MIDI from a keyboard, a controller or another program, as Kairotic events\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [;; ── the page's MIDI, asked once and shared by every midi box (Chrome, Edge, Firefox; not Safari) ──\n access (fn []\n (or (.-kairoticMidi js/window)\n (let [p (if (.-requestMIDIAccess js/navigator)\n (.requestMIDIAccess js/navigator #js {:sysex false})\n (js/Promise.reject (js/Error. \"this browser has no Web MIDI (Chrome, Edge or Firefox; not Safari)\")))]\n (set! (.-kairoticMidi js/window) p)\n ;; refused: ask again next time\n (.catch p (fn [_] (set! (.-kairoticMidi js/window) nil)))\n p)))\n r3 (fn [x] (/ (js/Math.round (* x 1000)) 1000))\n r4 (fn [x] (/ (js/Math.round (* x 10000)) 10000))\n ;; ── bytes → messages ──\n decode (fn [[s a b]]\n (let [hi (bit-and (or s 0) 0xF0) ch (inc (bit-and (or s 0) 0x0F))]\n (case hi\n 0x80 {:type :note-off :ch ch :note a}\n 0x90 (if (zero? b) {:type :note-off :ch ch :note a} {:type :note-on :ch ch :note a :vel b})\n 0xA0 {:type :poly :ch ch :note a :value b}\n 0xB0 {:type :cc :ch ch :cc a :value b}\n 0xC0 {:type :program :ch ch :value a}\n 0xD0 {:type :pressure :ch ch :value a}\n 0xE0 {:type :bend :ch ch :value (- (+ a (* 128 b)) 8192)}\n 0xF0 (case s 0xF8 {:type :clock} 0xFA {:type :start} 0xFB {:type :continue} 0xFC {:type :stop} nil)\n nil)))\n ;; ── messages → events, with the state of what is held ──\n ;; a voice id names a note on a channel: the same key on two MPE channels is two voices\n voice-id (fn [ch note] (+ note (* 128 (dec ch))))\n fresh (fn [range0] {:range0 range0 :ranges {} :bends {} :rpn {} :held {} :order []})\n freq-of (fn [st ch note] (api/midi->hz (+ note (* (get (:bends st) ch 0) (get (:ranges st) ch (:range0 st))))))\n ev (fn [m] (assoc m :src :midi))\n step (fn [st m]\n (let [ch (:ch m)]\n (case (:type m)\n :note-on (let [id (voice-id ch (:note m)) f (r3 (freq-of st ch (:note m))) a (r3 (/ (:vel m) 127))\n offs (when (get (:held st) id) [(ev {:type :note :id id :ch ch :note (:note m) :freq f :gate false})])]\n [(-> st (assoc-in [:held id] {:ch ch :note (:note m) :freq f})\n (update :order (fn [o] (vec (cons id (remove #(= % id) o))))))\n (conj (vec offs) (ev {:type :note :id id :ch ch :note (:note m) :freq f :amp a :gate true}))])\n :note-off (let [id (voice-id ch (:note m)) h (get (:held st) id)]\n (if h\n [(-> st (update :held dissoc id) (update :order (fn [o] (vec (remove #(= % id) o)))))\n [(ev {:type :note :id id :ch ch :note (:note m) :freq (:freq h) :gate false})]]\n [st []]))\n :bend (let [st (assoc-in st [:bends ch] (/ (:value m) (if (neg? (:value m)) 8192 8191)))]\n (reduce (fn [[st out] id]\n (let [{:keys [note]} (get (:held st) id) f (r3 (freq-of st ch note))]\n [(assoc-in st [:held id :freq] f) (conj out (ev {:type :glide :id id :ch ch :note note :freq f}))]))\n [st []] (filter #(= ch (:ch (get (:held st) %))) (:order st))))\n ;; RPN 0 (CC 101 = 0, CC 100 = 0, then CC 6) is the bend range an MPE controller announces: read, not sent\n :cc (let [n (:cc m) rpn (get (:rpn st) ch {})]\n (cond (= n 101) [(assoc-in st [:rpn ch :msb] (:value m)) []]\n (= n 100) [(assoc-in st [:rpn ch :lsb] (:value m)) []]\n (and (= n 6) (= 0 (:msb rpn)) (= 0 (:lsb rpn))) [(assoc-in st [:ranges ch] (:value m)) []]\n (= n 38) [st []]\n :else [st [(ev {:type :cc :ch ch :cc n :value (r4 (/ (:value m) 127))})]]))\n :pressure (let [id (first (filter #(= ch (:ch (get (:held st) %))) (:order st)))]\n [st [(ev (cond-> {:type :pressure :ch ch :value (r4 (/ (:value m) 127))} id (assoc :id id)))]])\n :poly [st [(ev {:type :pressure :ch ch :id (voice-id ch (:note m)) :value (r4 (/ (:value m) 127))})]]\n :program [st [(ev {:type :program :ch ch :value (:value m)})]]\n (:clock :start :stop :continue) [st [(ev {:type (:type m)})]]\n [st []])))\n sounding (fn [st] [(:order st) (mapv #(:freq (get (:held st) %)) (:order st))])\n label (fn [e] (case (:type e)\n :note (str (api/midi-name (:note e)) (if (:gate e) (str \" \" (js/Math.round (* 127 (or (:amp e) 0)))) \" off\"))\n :glide (str (api/nice (:freq e)) \" Hz\")\n :cc (str \"cc \" (:cc e) \" \" (api/nice (:value e)))\n (name (:type e))))]\n {;; ── about ──\n :class \"midiin\"\n :license \"MPL-2.0\"\n :doc \"MIDI from every input of the page (a keyboard, a controller, another program) as Kairotic events, while ▶ runs: a note is {:type :note :id :ch :note :freq :amp :gate}, a pitch bend moves the notes of its channel ({:type :glide :id :freq}), and controllers, pressure, program changes and the clock come as {:type :cc :ch :cc :value 0…1}, {:type :pressure …}, {:type :clock}…. Pitch travels as :freq in Hz: a bend, or an MPE controller (a channel per note; its bend range, RPN 0, is read), is only a different :freq. Out: the Hz of the notes sounding (with [:gain amp] just before a note starts) and their voice ids, as a keyboard or a player sends them, for synth~ or a polyphonic faust~; and every event. channel (0, all) keeps one; range (2) is the bend range of a controller that does not say its own. :clear (or :stop) lets every held note go. Chrome, Edge and Firefox ask once to use MIDI; Safari has no MIDI.\"\n :usage \"midiin [channel] [range]\"\n :io [1 3]\n :size [96 30]\n :args [[:channel 0] [:range 2]]\n :help {:inlets [\":clear (or :stop): every held note goes\"]\n :outlets [\"the Hz of the notes sounding, most recent first ([:gain amp] before a note starts)\" \"their voice ids (note + 128 per channel above the first)\" \"every event, as a map\"]\n :example \"(box :b1 \\\"midiin\\\" 40 30)\\n(box :b2 \\\"synth~\\\" 40 90)\\n(box :b3 \\\"dac~\\\" 40 140)\\n(box :b4 \\\"print\\\" 160 90)\\n(connect :b1 0 :b2 0)\\n(connect :b1 1 :b2 1)\\n(connect :b2 0 :b3 0)\\n(connect :b2 0 :b3 1)\\n(connect :b1 2 :b4 0)\"\n :try \"Press ▶ and play a MIDI keyboard: synth~ plays it and print shows every event. Bend a note: it glides.\"\n :see [\"midiout\" \"keyboard\" \"synth~\" \"oscin\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args]}]\n (let [st (or state (fresh (api/clamp (:range args) 1 96)))]\n (cond\n (and (= inlet :audio) (:error value)) {:effects [[:print (:error value)]] :show {:label \"no MIDI\"}}\n (and (= inlet :audio) (:ports value)) {:state st :show {:label (if (pos? (:ports value)) (str \"midi · \" (:ports value) \" in\") \"no MIDI input\")}}\n (and (= inlet :audio) (:bytes value))\n (let [m (decode (:bytes value))\n ch (:channel args)]\n (if (or (nil? m) (and (pos? ch) (:ch m) (not= ch (:ch m))))\n {:state st}\n (let [[st2 es] (step st m)]\n (if (empty? es)\n {:state st2}\n (let [[ids hz] (sounding st2)\n notes? (some #(#{:note :glide} (:type %)) es)\n on (first (filter #(and (= :note (:type %)) (:gate %)) es))]\n {:state st2\n :show {:label (label (last es))}\n :out (vec (concat (when notes? [[1 ids]])\n (when on [[0 [:gain (:amp on)]]])\n (when notes? [[0 hz]])\n (map (fn [e] [2 e]) es)))})))))\n (#{:clear :stop} value)\n (let [offs (for [id (:order st) :let [h (get (:held st) id)]]\n {:src :midi :type :note :id id :ch (:ch h) :note (:note h) :freq (:freq h) :gate false})]\n {:state (fresh (:range0 st)) :out (vec (concat [[1 []] [0 []]] (map (fn [e] [2 e]) offs)))})\n :else {:state st})))\n\n ;; ── view ──\n :derive (fn [{:keys [shown]}] {:label (or (:label shown) \"midiin\")})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]\n\n ;; ── outside: the inputs, while ▶ runs ──\n :audio {:create (fn [_ b _]\n (let [node {:alive (atom true) :ins (atom []) :inlets [] :outlets []}\n on-msg (fn [e] (when @(:alive node) (api/report! (:id b) {:bytes (vec (js/Array.from (.-data e)))} nil)))\n wire! (fn [m]\n (doseq [i @(:ins node)] (.removeEventListener i \"midimessage\" on-msg))\n (let [ins (vec (js/Array.from (.values (.-inputs m))))]\n (doseq [i ins] (.addEventListener i \"midimessage\" on-msg))\n (reset! (:ins node) ins)\n (api/report! (:id b) {:ports (count ins)} nil)))]\n (assoc node :unwire (fn [] (doseq [i @(:ins node)] (.removeEventListener i \"midimessage\" on-msg)))\n :ready (-> (access)\n (.then (fn [m] (when @(:alive node)\n (wire! m)\n (.addEventListener m \"statechange\" (fn [_] (when @(:alive node) (wire! m)))))))\n (.catch (fn [e] (api/report! (:id b) {:error (str \"midiin: \" (.-message e))} nil)))))))\n :dispose (fn [node] (reset! (:alive node) false) ((:unwire node)))}})\n"
|
|
9
|
+
};
|
package/dist/midiout.mjs
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Generated by packages/build.mjs from src/midiout.cljs
|
|
2
|
+
export default {
|
|
3
|
+
"class": "midiout",
|
|
4
|
+
"version": "0.2.5",
|
|
5
|
+
"author": "bonuoq",
|
|
6
|
+
"license": "MPL-2.0",
|
|
7
|
+
"doc": "Notes and events to a MIDI port, while ▶ runs. On the left, what sounds as a player, a keyboard or a reader send it — the Hz of the notes (after their voice ids on the right, and [:gain amp] for the next ones) —, or an event from midiin, oscin or a room ({:type :note :freq :amp :gate}, :glide, :cc…). With mpe, each note gets a channel of its own (2…16) and its exact frequency as a key plus a pitch bend of that channel (range 48 semitones): microtones, just intervals and glides reach the synthesizer without rounding; at ▶ it announces the zone and the range (the MPE configuration message). Without it, one channel (channel, 1) and the nearest key. port (1) is which output of the page. :clear (or :stop) ends every note.",
|
|
8
|
+
"source": ";; midiout · Kairotic events and notes to a MIDI port, plain or MPE (microtones without rounding)\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [access (fn []\n (or (.-kairoticMidi js/window)\n (let [p (if (.-requestMIDIAccess js/navigator)\n (.requestMIDIAccess js/navigator #js {:sysex false})\n (js/Promise.reject (js/Error. \"this browser has no Web MIDI (Chrome, Edge or Firefox; not Safari)\")))]\n (set! (.-kairoticMidi js/window) p)\n (.catch p (fn [_] (set! (.-kairoticMidi js/window) nil)))\n p)))\n clamp (fn [x lo hi] (max lo (min hi x)))\n ;; ── messages → bytes ──\n encode (fn [{:keys [type ch note vel value cc]}]\n (let [c (dec (or ch 1)) b7 (fn [x] (clamp (js/Math.round x) 0 127))]\n (case type\n :note-on [(+ 0x90 c) (b7 note) (b7 vel)]\n :note-off [(+ 0x80 c) (b7 note) 0]\n :cc [(+ 0xB0 c) (b7 cc) (b7 value)]\n :pressure [(+ 0xD0 c) (b7 value)]\n :bend (let [v (+ 8192 (clamp (js/Math.round value) -8192 8191))] [(+ 0xE0 c) (bit-and v 127) (bit-shift-right v 7)])\n :clock [0xF8] :start [0xFA] :continue [0xFB] :stop [0xFC]\n nil)))\n ;; ── events → messages: plain (one channel, rounded) or MPE (a member channel per note) ──\n fresh (fn [mpe ch r] {:mode (if mpe :mpe :plain) :ch ch :range r :voices {} :free (vec (range 2 17)) :n 0})\n bend-of (fn [semis r] (clamp (js/Math.round (* (/ semis r) (if (neg? semis) 8192 8191))) -8192 8191))\n key-and-bend (fn [hz r]\n (let [m (api/hz->midi hz) k (clamp (js/Math.round m) 0 127)\n k (if (> (js/Math.abs (- m k)) r) (clamp (js/Math.round (- m (* (js/Math.sign (- m k)) r))) 0 127) k)]\n [k (bend-of (- m k) r)]))\n vel-of (fn [e] (clamp (js/Math.round (* 127 (or (:amp e) 0.8))) 1 127))\n off (fn [st id]\n (if-let [v (get-in st [:voices id])]\n [(-> st (update :voices dissoc id) (update :free #(if (= :mpe (:mode st)) (conj % (:ch v)) %)))\n [{:type :note-off :ch (:ch v) :note (:key v)}]]\n [st []]))\n on (fn [st e]\n (let [id (or (:id e) (js/Math.round (api/hz->midi (:freq e))))\n [st pre] (off st id)]\n (if (= :mpe (:mode st))\n (let [[st ch pre] (if (seq (:free st))\n [st (first (:free st)) pre]\n ;; every channel busy: the oldest voice gives its own\n (let [[oid v] (apply min-key (fn [[_ v]] (:n v)) (:voices st))]\n [(update st :voices dissoc oid) (:ch v) (conj pre {:type :note-off :ch (:ch v) :note (:key v)})]))\n [k b] (key-and-bend (:freq e) (:range st))]\n [(-> st (update :free #(vec (remove #{ch} %))) (assoc-in [:voices id] {:ch ch :key k :n (:n st)}) (update :n inc))\n (into pre [{:type :bend :ch ch :value b} {:type :note-on :ch ch :note k :vel (vel-of e)}])])\n (let [k (clamp (js/Math.round (api/hz->midi (:freq e))) 0 127)]\n [(-> st (assoc-in [:voices id] {:ch (:ch st) :key k :n (:n st)}) (update :n inc))\n (conj pre {:type :note-on :ch (:ch st) :note k :vel (vel-of e)})]))))\n out-step (fn [st e]\n (let [e (if (and (nil? (:freq e)) (number? (:note e))) (assoc e :freq (api/midi->hz (:note e))) e)]\n (case (:type e)\n (:note nil) (cond (false? (:gate e)) (off st (:id e))\n (and (number? (:freq e)) (pos? (:freq e))) (on st e)\n :else [st []])\n :glide (let [v (get-in st [:voices (:id e)])]\n (if (and v (= :mpe (:mode st)) (number? (:freq e)))\n [st [{:type :bend :ch (:ch v) :value (bend-of (- (api/hz->midi (:freq e)) (:key v)) (:range st))}]]\n [st []]))\n :cc [st [{:type :cc :ch (or (:ch e) (:ch st)) :cc (:cc e) :value (* 127 (:value e))}]]\n :pressure [st (if-let [v (get-in st [:voices (:id e)])] [{:type :pressure :ch (:ch v) :value (* 127 (:value e))}] [])]\n (:clock :start :stop :continue) [st [{:type (:type e)}]]\n [st []])))\n events (fn [st es] (reduce (fn [[st ms] e] (let [[st m] (out-step st e)] [st (into ms m)])) [st []] es))\n ;; a snapshot of what sounds (Hz and voice ids, as a player or a keyboard sends them) against the one before\n diff (fn [before after amp]\n (let [pairs (fn [{:keys [hz ids]}] (into {} (map vector (or (seq ids) (map #(js/Math.round (api/hz->midi %)) hz)) hz)))\n a (pairs before) b (pairs after)]\n (vec (concat (for [[id _] a :when (not (contains? b id))] {:type :note :id id :gate false})\n (for [[id f] b :when (and (contains? a id) (not= f (get a id)))] {:type :glide :id id :freq f})\n (for [[id f] (reverse (seq b)) :when (not (contains? a id))] {:type :note :id id :freq f :amp amp :gate true})))))\n setup (fn [r] (vec (concat [{:type :cc :ch 1 :cc 101 :value 0} {:type :cc :ch 1 :cc 100 :value 6} {:type :cc :ch 1 :cc 6 :value 15}]\n (mapcat (fn [ch] [{:type :cc :ch ch :cc 101 :value 0} {:type :cc :ch ch :cc 100 :value 0}\n {:type :cc :ch ch :cc 6 :value r} {:type :cc :ch ch :cc 101 :value 127} {:type :cc :ch ch :cc 100 :value 127}])\n (range 2 17)))))\n send (fn [st ms] (if (seq ms) {:state st :effects [[:send (vec (keep encode ms))]] :show {:n (count ms)}} {:state st}))]\n {;; ── about ──\n :class \"midiout\"\n :license \"MPL-2.0\"\n :doc \"Notes and events to a MIDI port, while ▶ runs. On the left, what sounds as a player, a keyboard or a reader send it — the Hz of the notes (after their voice ids on the right, and [:gain amp] for the next ones) —, or an event from midiin, oscin or a room ({:type :note :freq :amp :gate}, :glide, :cc…). With mpe, each note gets a channel of its own (2…16) and its exact frequency as a key plus a pitch bend of that channel (range 48 semitones): microtones, just intervals and glides reach the synthesizer without rounding; at ▶ it announces the zone and the range (the MPE configuration message). Without it, one channel (channel, 1) and the nearest key. port (1) is which output of the page. :clear (or :stop) ends every note.\"\n :usage \"midiout [mpe] [channel] [port] [range]\"\n :io [2 0]\n :size [96 30]\n :args [[:mpe false] [:channel 1] [:port 1] [:range 48]]\n :help {:inlets [\"the Hz of the notes sounding (a list), [:gain amp], an event map, or :clear (or :stop)\" \"the voice ids of the Hz that follow\"]\n :outlets []\n :example \"(box :b1 \\\"keyboard\\\" 40 30)\\n(box :b2 \\\"midiout mpe\\\" 40 120)\\n(connect :b1 0 :b2 0)\\n(connect :b1 1 :b2 1)\"\n :try \"Press ▶ and play the keyboard: the notes go to the first MIDI output of the page. With an MPE synthesizer, a freqt read by a reader~ glides there without steps.\"\n :see [\"midiin\" \"synth~\" \"player\" \"oscout\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args]}]\n (let [st (or state {:enc (fresh (:mpe args) (api/clamp (:channel args) 1 16) (api/clamp (:range args) 1 96)) :snap {:hz [] :ids []} :ids nil :amp 0.8})\n enc (:enc st)]\n (cond\n (and (= inlet :audio) (:error value)) {:state st :effects [[:print (:error value)]] :show {:label \"no MIDI\"}}\n (and (= inlet :audio) (contains? value :port)) {:state st :show {:label (or (:port value) \"no MIDI output\")}}\n (= inlet :audio) {:state st}\n (= inlet 1) {:state (assoc st :ids (when (sequential? value) (vec value)))}\n (and (vector? value) (= :gain (first value)) (number? (second value))) {:state (assoc st :amp (api/clamp (second value) 0 1))}\n (#{:clear :stop} value)\n (let [[e2 ms] (events enc (map (fn [id] {:type :note :id id :gate false}) (keys (:voices enc))))]\n (send (assoc st :enc e2 :snap {:hz [] :ids []}) ms))\n (map? value) (let [[e2 ms] (out-step enc value)] (send (assoc st :enc e2) ms))\n (or (number? value) (sequential? value))\n (let [hz (vec (filter number? (if (number? value) [value] value)))\n snap {:hz hz :ids (when (= (count (:ids st)) (count hz)) (:ids st))}\n [e2 ms] (events enc (diff (:snap st) snap (:amp st)))]\n (send (assoc st :enc e2 :snap snap) ms))\n :else {:state st})))\n\n ;; ── view ──\n :derive (fn [{:keys [shown args]}] {:label (or (:label shown) (str \"midiout\" (when (:mpe args) \" mpe\")))})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]\n\n ;; ── outside: the port, while ▶ runs ──\n :audio {:create (fn [ac b _]\n (let [words (rest (.split (.trim (str (:text b))) #\"\\s+\"))\n mpe (some #{\"mpe\"} words)\n nums (keep #(let [n (js/parseFloat %)] (when-not (js/isNaN n) n)) words)\n port-n (or (second nums) 1)\n r (or (nth nums 2 nil) 48)\n node {:ac ac :port (atom nil) :alive (atom true) :inlets [] :outlets []}]\n (-> (access)\n (.then (fn [m]\n (when @(:alive node)\n (let [outs (vec (js/Array.from (.values (.-outputs m))))\n p (get outs (dec port-n))]\n (reset! (:port node) p)\n (api/report! (:id b) {:port (when p (str \"→ \" (.-name p)))} nil)\n (when (and p mpe) (doseq [msg (setup r)] (.send p (clj->js (encode msg)))))))))\n (.catch (fn [e] (api/report! (:id b) {:error (str \"midiout: \" (.-message e))} nil))))\n node))\n :effects {:send (fn [node bytes at]\n (when-let [p @(:port node)]\n (let [ac (:ac node)\n ;; at the time of the message on the audio clock, as a time of the page\n ts (+ (js/performance.now) (* 1000 (max 0 (- (or at 0) (.-currentTime ac)))))]\n (doseq [b bytes] (.send p (clj->js b) ts)))))}\n :dispose (fn [node]\n (reset! (:alive node) false)\n ;; nothing left sounding on the synthesizer\n (when-let [p @(:port node)]\n (doseq [ch (range 16)] (.send p #js [(+ 0xB0 ch) 123 0]))))}})\n"
|
|
9
|
+
};
|
package/dist/motion.mjs
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Generated by packages/build.mjs from src/motion.cljs
|
|
2
|
+
export default {
|
|
3
|
+
"class": "motion",
|
|
4
|
+
"version": "0.2.5",
|
|
5
|
+
"author": "bonuoq",
|
|
6
|
+
"license": "MPL-2.0",
|
|
7
|
+
"doc": "A phone's (or a tablet's) motion while ▶ runs: its tilt as x (left 0 … right 1) and y (towards you 0 … away 1), both 0.5 lying flat — smoothed, and sent only when it moves —; and a shake, when it is shaken harder than shake (14 m/s²), once with a pause after it. Out: [x y], the strength of each shake, and the events ({:type :tilt :x :y :alpha :beta :gamma}, {:type :shake :value}) for oscout or a room. smooth (0.3) is how much of the last value stays at each reading. iOS asks for permission at ▶. Open the work on the phone (Share/Export, Release/Perform) to play with it.",
|
|
8
|
+
"source": ";; motion · a phone's tilt and shake as Kairotic events\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [r (fn [x d] (let [k (js/Math.pow 10 d)] (/ (js/Math.round (* x k)) k)))\n clamp (fn [x lo hi] (max lo (min hi x)))\n ;; the tilt as x (left 0 … right 1) and y (towards you 0 … away 1), both 0.5 lying flat\n tilt-xy (fn [beta gamma] [(clamp (/ (+ gamma 90) 180) 0 1) (clamp (/ (+ (clamp beta -90 90) 90) 180) 0 1)])\n mag (fn [[x y z]] (js/Math.sqrt (+ (* x x) (* y y) (* z z))))\n ;; a reading: smoothed, and sent only when it moves (sensors read ~60 times a second, moving or not);\n ;; a shake is one event, with a pause after it\n step (fn [st t rd smooth shake]\n (cond\n (number? (:gamma rd))\n (let [[tx ty] (tilt-xy (or (:beta rd) 0) (:gamma rd))\n x (if (:x st) (+ (* smooth (:x st)) (* (- 1 smooth) tx)) tx)\n y (if (:y st) (+ (* smooth (:y st)) (* (- 1 smooth) ty)) ty)\n [sx sy] (:sent st) st (assoc st :x x :y y)]\n (if (and sx (< (js/Math.abs (- x sx)) 0.004) (< (js/Math.abs (- y sy)) 0.004))\n [st nil]\n [(assoc st :sent [x y])\n (cond-> {:src :motion :type :tilt :x (r x 3) :y (r y 3) :beta (r (or (:beta rd) 0) 1) :gamma (r (:gamma rd) 1)}\n (number? (:alpha rd)) (assoc :alpha (r (:alpha rd) 1)))]))\n (or (:acc rd) (:accg rd))\n (let [m (if (:acc rd) (mag (:acc rd)) (js/Math.abs (- (mag (:accg rd)) 9.81)))]\n (if (and (> m shake) (or (nil? (:last-shake st)) (>= (- t (:last-shake st)) 0.3)))\n [(assoc st :last-shake t) {:src :motion :type :shake :value (r m 1)}]\n [st nil]))\n :else [st nil]))]\n {;; ── about ──\n :class \"motion\"\n :license \"MPL-2.0\"\n :doc \"A phone's (or a tablet's) motion while ▶ runs: its tilt as x (left 0 … right 1) and y (towards you 0 … away 1), both 0.5 lying flat — smoothed, and sent only when it moves —; and a shake, when it is shaken harder than shake (14 m/s²), once with a pause after it. Out: [x y], the strength of each shake, and the events ({:type :tilt :x :y :alpha :beta :gamma}, {:type :shake :value}) for oscout or a room. smooth (0.3) is how much of the last value stays at each reading. iOS asks for permission at ▶. Open the work on the phone (Share/Export, Release/Perform) to play with it.\"\n :usage \"motion [smooth] [shake]\"\n :io [0 3]\n :size [96 30]\n :args [[:smooth 0.3] [:shake 14]]\n :help {:inlets []\n :outlets [\"[x y], 0…1 each, when the tilt moves\" \"the strength of a shake (m/s²)\" \"every event, as a map\"]\n :example \"(box :b1 \\\"motion\\\" 40 30)\\n(box :b2 \\\"print\\\" 40 80)\\n(connect :b1 0 :b2 0)\"\n :try \"Open this on a phone, press ▶, and tilt it.\"\n :see [\"gamepad\" \"oscout\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args at]}]\n (if (and (= inlet :audio) (map? value))\n (if (:error value)\n {:effects [[:print (:error value)]] :show {:label \"no motion\"}}\n (let [[st e] (step (or state {}) (or at 0) value (api/clamp (:smooth args) 0 0.95) (api/clamp (:shake args) 2 60))]\n (cond\n (nil? e) {:state st}\n (= :tilt (:type e)) {:state st :out [[0 [(:x e) (:y e)]] [2 e]] :show {:x (:x e) :y (:y e)}}\n :else {:state st :out [[1 (:value e)] [2 e]] :show (assoc (select-keys st [:x :y]) :shake true)})))\n {}))\n\n ;; ── view: where the tilt is ──\n :derive (fn [{:keys [shown]}] {:cx (+ 60 (* 30 (- (or (:x shown) 0.5) 0.5) 2)) :cy (+ 15 (* 10 (- 0.5 (or (:y shown) 0.5)) 2))\n :dot (if (:shake shown) :kairos :accent)})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 6 :y 19 :size 10 :fill :soft} \"motion\"]\n [:rect {:x 46 :y 4 :w 46 :h 22 :r 2 :stroke :grid :fill :bg}]\n [:circle {:cx :$cx :cy :$cy :r 4 :stroke :$dot :fill :$dot}]]\n\n ;; ── outside: the sensors, while ▶ runs ──\n :audio {:create (fn [_ b _]\n (let [node {:alive (atom true) :inlets [] :outlets []}\n report (fn [rd] (when @(:alive node) (api/report! (:id b) rd nil)))\n on-tilt (fn [e] (when (number? (.-gamma e)) (report {:alpha (.-alpha e) :beta (.-beta e) :gamma (.-gamma e)})))\n on-move (fn [e] (let [a (.-acceleration e) g (.-accelerationIncludingGravity e)]\n (cond (and a (number? (.-x a))) (report {:acc [(.-x a) (.-y a) (.-z a)]})\n (and g (number? (.-x g))) (report {:accg [(.-x g) (.-y g) (.-z g)]}))))\n listen! (fn [] (.addEventListener js/window \"deviceorientation\" on-tilt)\n (.addEventListener js/window \"devicemotion\" on-move))\n ask (some-> (.-DeviceOrientationEvent js/window) .-requestPermission)]\n ;; iOS asks first, and only from a gesture: ▶ is one\n (if (fn? ask)\n (-> (ask) (.then (fn [r] (if (= r \"granted\") (listen!) (report {:error \"motion: refused\"}))))\n (.catch (fn [e] (report {:error (str \"motion: \" (.-message e))}))))\n (listen!))\n (assoc node :off (fn [] (.removeEventListener js/window \"deviceorientation\" on-tilt)\n (.removeEventListener js/window \"devicemotion\" on-move)))))\n :dispose (fn [node] (reset! (:alive node) false) ((:off node)))}})\n"
|
|
9
|
+
};
|
package/dist/oscin.mjs
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Generated by packages/build.mjs from src/oscin.cljs
|
|
2
|
+
export default {
|
|
3
|
+
"class": "oscin",
|
|
4
|
+
"version": "0.2.5",
|
|
5
|
+
"author": "bonuoq",
|
|
6
|
+
"license": "MPL-2.0",
|
|
7
|
+
"doc": "OSC in, through a relay's OSC bridge (npx @kairotic/relay --osc, on this machine), while ▶ runs: what SuperCollider, Max, Pd or TouchOSC send to the relay's port (57121) arrives here. The addresses oscout writes are events again (/kairotic/note id freq amp gate is {:type :note …}, /kairotic/glide, /kairotic/cc, /kairotic/tilt…); any other one is {:type :osc :address \"/x\" :args […] :from \"host:port\"}. pattern takes only the addresses that match it (OSC patterns: ? * [a-z] [!a] {note,glide}): oscin /synth/*/cutoff. Out: the event, and its values alone (the args of an OSC message; the Hz of a note) for a number box. [:relay \"ws://…\"] changes the bridge for the whole page.",
|
|
8
|
+
"source": ";; oscin · OSC in, through a relay's bridge: from SuperCollider, Max, Pd, TouchOSC… as Kairotic events\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [default-url \"ws://localhost:8765/osc\"\n relay-url (fn [] (or (try (.getItem js/localStorage \"kairotic-osc-relay\") (catch :default _ nil)) default-url))\n ;; the same shared sockets as oscout (one per address, for every osc box of the page)\n socket (fn [url]\n (let [all (or (.-kairoticOsc js/window) (set! (.-kairoticOsc js/window) #js {}))\n s (aget all url)]\n (if (and s (< (.. s -ws -readyState) 2))\n s\n (let [ws (js/WebSocket. url)\n s #js {:ws ws :listeners #js [] :queue #js []}]\n (set! (.-onopen ws) (fn [_] (doseq [m (js/Array.from (.-queue s))] (.send ws m)) (set! (.-queue s) #js [])))\n (set! (.-onmessage ws) (fn [e] (let [f (try (js/JSON.parse (.-data e)) (catch :default _ nil))]\n (when f (doseq [l (js/Array.from (.-listeners s))] (l f))))))\n (aset all url s)\n s))))\n r4 (fn [x] (if (number? x) (/ (js/Math.round (* x 10000)) 10000) x))\n ;; ── the /kairotic/… addresses are events again; any other address arrives as it is ──\n osc->event (fn [{:keys [address args from]}]\n (let [a (vec args)]\n (merge (cond-> {:src :osc} from (assoc :from from))\n (case address\n \"/kairotic/note\" (cond-> {:type :note :id (nth a 0 0) :gate (not= 0 (nth a 3 1))}\n (number? (get a 1)) (assoc :freq (r4 (get a 1)))\n (and (number? (get a 2)) (not= 0 (nth a 3 1))) (assoc :amp (r4 (get a 2))))\n \"/kairotic/glide\" {:type :glide :id (nth a 0 0) :freq (r4 (nth a 1 0))}\n \"/kairotic/cc\" {:type :cc :ch (nth a 0 1) :cc (nth a 1 0) :value (r4 (nth a 2 0))}\n \"/kairotic/pressure\" {:type :pressure :id (nth a 0 0) :value (r4 (nth a 1 0))}\n \"/kairotic/tilt\" {:type :tilt :x (r4 (nth a 0 0.5)) :y (r4 (nth a 1 0.5))}\n \"/kairotic/shake\" {:type :shake :value (r4 (nth a 0 0))}\n (\"/kairotic/clock\" \"/kairotic/start\" \"/kairotic/stop\" \"/kairotic/continue\") {:type (keyword (subs address 10))}\n {:type :osc :address address :args (mapv r4 a)}))))\n ;; ── OSC address patterns (OSC 1.0): ? * [a-z] [!a] {foo,bar}, none of them across a / ──\n re-esc (fn [s] (.replace s (js/RegExp. \"[.*+?^${}()|[\\\\]\\\\\\\\]\" \"g\") \"\\\\$&\"))\n pattern-re (fn [p]\n (loop [cs (seq p) out \"^\"]\n (if-not cs\n (js/RegExp. (str out \"$\"))\n (let [c (first cs)]\n (case c\n \"?\" (recur (next cs) (str out \"[^/]\"))\n \"*\" (recur (next cs) (str out \"[^/]*\"))\n \"[\" (let [body (take-while #(not= \"]\" %) (next cs)) neg (= \"!\" (first body))\n body (apply str (if neg (rest body) body))]\n (recur (next (drop-while #(not= \"]\" %) (next cs)))\n (str out \"[\" (when neg \"^\") (.replace body (js/RegExp. \"[\\\\\\\\^]\" \"g\") \"\\\\$&\") \"]\")))\n \"{\" (let [body (apply str (take-while #(not= \"}\" %) (next cs)))]\n (recur (next (drop-while #(not= \"}\" %) (next cs)))\n (str out \"(?:\" (apply str (interpose \"|\" (map re-esc (.split body \",\")))) \")\")))\n (recur (next cs) (str out (re-esc c))))))))\n matches? (fn [p address] (or (empty? p) (boolean (.test (pattern-re p) address))))]\n {;; ── about ──\n :class \"oscin\"\n :license \"MPL-2.0\"\n :doc \"OSC in, through a relay's OSC bridge (npx @kairotic/relay --osc, on this machine), while ▶ runs: what SuperCollider, Max, Pd or TouchOSC send to the relay's port (57121) arrives here. The addresses oscout writes are events again (/kairotic/note id freq amp gate is {:type :note …}, /kairotic/glide, /kairotic/cc, /kairotic/tilt…); any other one is {:type :osc :address \\\"/x\\\" :args […] :from \\\"host:port\\\"}. pattern takes only the addresses that match it (OSC patterns: ? * [a-z] [!a] {note,glide}): oscin /synth/*/cutoff. Out: the event, and its values alone (the args of an OSC message; the Hz of a note) for a number box. [:relay \\\"ws://…\\\"] changes the bridge for the whole page.\"\n :usage \"oscin [pattern]\"\n :io [1 2]\n :size [110 30]\n :help {:inlets [\"[:relay \\\"ws://…/osc\\\"]\"]\n :outlets [\"every message that matches, as an event\" \"its values: the args of an OSC message, or the Hz of a note\"]\n :example \"(box :b1 \\\"oscin /kairotic/*\\\" 40 30)\\n(box :b2 \\\"print\\\" 40 80)\\n(connect :b1 0 :b2 0)\"\n :try \"Run npx @kairotic/relay --osc, press ▶, and from SuperCollider: NetAddr(\\\"127.0.0.1\\\", 57121).sendMsg(\\\"/kairotic/note\\\", 1, 440, 0.5, 1).\"\n :see [\"oscout\" \"midiin\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value]}]\n (cond\n (and (= inlet :audio) (:event value))\n (let [e (:event value)]\n {:out [[1 (if (= :osc (:type e)) (:args e) (or (:freq e) (:value e) (:x e)))] [0 e]]\n :show {:label (or (:address e) (str \"/kairotic/\" (name (:type e))))}})\n (and (= inlet :audio) (:status value)) {:show {:label (:status value)}}\n (and (vector? value) (= :relay (first value)) (string? (second value)))\n {:effects [[:relay (second value)]] :show {:label \"relay set: ▶ again\"}}\n :else {}))\n :tasks {:relay (fn [url _] (try (.setItem js/localStorage \"kairotic-osc-relay\" url) (catch :default _ nil)) (js/Promise.resolve url))}\n\n ;; ── view ──\n :derive (fn [{:keys [shown]}] {:label (or (:label shown) \"oscin\")})\n :view [[:rect {:x 1 :y 1 :w 108 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]\n\n ;; ── outside: the bridge, while ▶ runs ──\n :audio {:create (fn [_ b _]\n (let [pattern (or (second (.split (.trim (str (:text b))) #\"\\s+\")) \"\")\n node {:alive (atom true) :inlets [] :outlets []}\n s (socket (relay-url))\n l (fn [f] (when (and @(:alive node) (.-address f) (matches? pattern (.-address f)))\n (api/report! (:id b) {:event (osc->event (js->clj f :keywordize-keys true))} nil)))]\n (.push (.-listeners s) l)\n (set! (.. s -ws -onerror)\n (fn [_] (api/report! (:id b) {:status \"no relay: npx @kairotic/relay --osc\"} nil)))\n (assoc node :off (fn [] (set! (.-listeners s) (.filter (.-listeners s) (fn [x & _] (not= x l))))))))\n :dispose (fn [node] (reset! (:alive node) false) ((:off node)))}})\n"
|
|
9
|
+
};
|
package/dist/oscout.mjs
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Generated by packages/build.mjs from src/oscout.cljs
|
|
2
|
+
export default {
|
|
3
|
+
"class": "oscout",
|
|
4
|
+
"version": "0.2.5",
|
|
5
|
+
"author": "bonuoq",
|
|
6
|
+
"license": "MPL-2.0",
|
|
7
|
+
"doc": "OSC out, through a relay's OSC bridge (npx @kairotic/relay --osc, on this machine): an event (from midiin, motion, gamepad, a room…) goes as /kairotic/note id freq amp gate, /kairotic/glide id freq, /kairotic/cc ch cc value, /kairotic/tilt x y, /kairotic/pad/<name> value [gate]…; a list that starts with an address goes as it is (/synth/freq 440, a message box). target is the name the relay was given for a destination (--osc-out sc=127.0.0.1:57120: sc), its first one if none. [:relay \"ws://…\"] changes the bridge for the whole page (ws://localhost:8765/osc). It sends with or without ▶.",
|
|
8
|
+
"source": ";; oscout · Kairotic events and messages as OSC, through a relay's bridge (SuperCollider, Max, Pd, TouchOSC…)\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [;; ── the bridge: one socket per address, shared by every osc box of the page ──\n ;; A page cannot send UDP: the relay started with --osc does it (npx @kairotic/relay --osc).\n default-url \"ws://localhost:8765/osc\"\n relay-url (fn [] (or (try (.getItem js/localStorage \"kairotic-osc-relay\") (catch :default _ nil)) default-url))\n socket (fn [url]\n (let [all (or (.-kairoticOsc js/window) (set! (.-kairoticOsc js/window) #js {}))\n s (aget all url)]\n (if (and s (< (.. s -ws -readyState) 2))\n s\n (let [ws (js/WebSocket. url)\n s #js {:ws ws :listeners #js [] :queue #js []}]\n (set! (.-onopen ws) (fn [_] (doseq [m (js/Array.from (.-queue s))] (.send ws m)) (set! (.-queue s) #js [])))\n (set! (.-onmessage ws) (fn [e] (let [f (try (js/JSON.parse (.-data e)) (catch :default _ nil))]\n (when f (doseq [l (js/Array.from (.-listeners s))] (l f))))))\n (aset all url s)\n s))))\n send! (fn [url m] (let [s (socket url) ws (.-ws s) j (js/JSON.stringify (clj->js m))]\n (if (= 1 (.-readyState ws)) (.send ws j) (.push (.-queue s) j))))\n num (fn [x] (if (number? x) x 0))\n ;; ── an event as OSC: /kairotic/<type> with its values in a fixed order, for a SynthDef or a Max patch ──\n event->osc (fn [e]\n (case (:type e)\n :note {:address \"/kairotic/note\" :types \"iffi\" :args [(num (:id e)) (num (:freq e)) (num (or (:amp e) (when (:gate e) 0.8))) (if (:gate e) 1 0)]}\n :glide {:address \"/kairotic/glide\" :types \"if\" :args [(num (:id e)) (num (:freq e))]}\n :cc {:address \"/kairotic/cc\" :types \"iif\" :args [(num (:ch e)) (num (:cc e)) (num (:value e))]}\n :pressure {:address \"/kairotic/pressure\" :types \"if\" :args [(num (:id e)) (num (:value e))]}\n :tilt {:address \"/kairotic/tilt\" :types \"ff\" :args [(:x e) (:y e)]}\n :shake {:address \"/kairotic/shake\" :types \"f\" :args [(:value e)]}\n (:button :axis) {:address (str \"/kairotic/pad/\" (if (:name e) (name (:name e)) (str (if (= :axis (:type e)) \"a\" \"b\") (or (:axis e) (:button e)))))\n :args (if (some? (:gate e)) [(:value e) (if (:gate e) 1 0)] [(:value e)])}\n :serial (cond (:values e) {:address \"/kairotic/serial\" :args (vec (:values e))}\n (number? (:value e)) {:address (str \"/kairotic/serial/\" (:key e)) :args [(:value e)]}\n :else {:address \"/kairotic/serial\" :types \"s\" :args [(str (:text e))]})\n (:clock :start :stop :continue) {:address (str \"/kairotic/\" (name (:type e))) :args []}\n nil))\n ;; a list that starts with an address: (/synth/freq 440) → /synth/freq 440\n address? (fn [x] (let [s (cond (string? x) x (keyword? x) (str (when (namespace x) (str (namespace x) \"/\")) (name x)) (symbol? x) (str x))]\n (when (and s (= \"/\" (subs s 0 1))) s)))\n clean (fn [x] (cond (keyword? x) (name x) (or (number? x) (string? x) (boolean? x)) x :else (str x)))]\n {;; ── about ──\n :class \"oscout\"\n :license \"MPL-2.0\"\n :doc \"OSC out, through a relay's OSC bridge (npx @kairotic/relay --osc, on this machine): an event (from midiin, motion, gamepad, a room…) goes as /kairotic/note id freq amp gate, /kairotic/glide id freq, /kairotic/cc ch cc value, /kairotic/tilt x y, /kairotic/pad/<name> value [gate]…; a list that starts with an address goes as it is (/synth/freq 440, a message box). target is the name the relay was given for a destination (--osc-out sc=127.0.0.1:57120: sc), its first one if none. [:relay \\\"ws://…\\\"] changes the bridge for the whole page (ws://localhost:8765/osc). It sends with or without ▶.\"\n :usage \"oscout [target]\"\n :io [1 0]\n :size [96 30]\n :args [[:target nil]]\n :help {:inlets [\"an event map, a list (address args…), or [:relay \\\"ws://…/osc\\\"]\"]\n :outlets []\n :example \"(box :b1 \\\"msg /kairotic/hello 1 2.5\\\" 40 30)\\n(box :b2 \\\"oscout\\\" 40 80)\\n(connect :b1 0 :b2 0)\"\n :try \"Run npx @kairotic/relay --osc on this machine and click the message: SuperCollider (sclang, port 57120) receives /kairotic/hello 1 2.5.\"\n :see [\"oscin\" \"midiout\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [value args]}]\n (cond\n (and (vector? value) (= :relay (first value)) (string? (second value)))\n {:effects [[:relay (second value)]] :show {:label \"relay set\"}}\n (and (map? value) (not= :osc (:src value)))\n (if-let [m (event->osc value)]\n {:effects [[:osc (cond-> m (:target args) (assoc :to (name (:target args))))]] :show {:label (:address m)}}\n {})\n (and (sequential? value) (address? (first value)))\n (let [m {:address (address? (first value)) :args (mapv clean (rest value))}]\n {:effects [[:osc (cond-> m (:target args) (assoc :to (name (:target args))))]] :show {:label (:address m)}})\n :else {}))\n ;; with or without ▶: OSC is a message, not a sound\n :tasks {:osc (fn [m _] (send! (relay-url) m) (js/Promise.resolve true))\n :relay (fn [url _] (try (.setItem js/localStorage \"kairotic-osc-relay\" url) (catch :default _ nil)) (js/Promise.resolve url))}\n\n ;; ── view ──\n :derive (fn [{:keys [shown args]}] {:label (or (:label shown) (str \"oscout\" (when (:target args) (str \" \" (name (:target args))))))})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]})\n"
|
|
9
|
+
};
|
package/dist/serial.mjs
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Generated by packages/build.mjs from src/serial.cljs
|
|
2
|
+
export default {
|
|
3
|
+
"class": "serial",
|
|
4
|
+
"version": "0.2.5",
|
|
5
|
+
"author": "bonuoq",
|
|
6
|
+
"license": "MPL-2.0",
|
|
7
|
+
"doc": "A board on a serial port — an Arduino's Serial.println, an ESP32… — while ▶ runs. open (a click: the browser asks which port) at baud (115200); close lets it go. Each line it sends: numbers (\"512 300 1\", or with commas) go out as a list on the left; key:value pairs (\"pot:512 light=300\") as [key value] each; anything else as text; and every line as events on the right ({:type :serial :values […]}, {:type :serial :key \"pot\" :value 512}, {:type :serial :text …}). A text or a list on the left goes to the board as a line — a text is always a line, even \"open\"; the orders are :open and :close. Web Serial: Chrome, Edge and Firefox 151+; not Safari.",
|
|
8
|
+
"source": ";; serial · a board on a serial port (an Arduino, an ESP32…): its lines of text as values and events\n;; Part of @kairotic/io. Written against the Kairotic API (api/…). Discussion #135, Study 34 · io.\n(let [number-of (fn [s] (when (re-matches #\"[-+]?(\\d+\\.?\\d*|\\.\\d+)([eE][-+]?\\d+)?\" s) (js/parseFloat s)))\n ;; a line: \"512 300 1\" (or with commas) → values; \"pot:512 light=300\" → one event per key; else text\n line-events (fn [line]\n (let [line (.trim line) ev (fn [m] (merge {:src :serial :type :serial} m))\n words (remove empty? (.split line (js/RegExp. \"[\\\\s,;]+\")))]\n (cond\n (empty? line) []\n (every? number-of words) [(ev {:values (mapv number-of words)})]\n (every? #(re-matches #\"[^:=]+[:=][^:=]+\" %) words)\n (vec (for [w words :let [[k v] (.split w (js/RegExp. \"[:=]\"))]]\n (ev (if-let [n (number-of v)] {:key k :value n} {:key k :text v}))))\n :else [(ev {:text line})])))\n ;; text comes in pieces that do not respect lines: what follows the last newline waits for the next\n chunk (fn [buf text]\n (let [lines (.split (str buf text) (js/RegExp. \"\\\\r?\\\\n\"))\n rest-buf (last lines)]\n [(if (> (count rest-buf) 512) \"\" rest-buf) (vec (mapcat line-events (butlast lines)))]))]\n {;; ── about ──\n :class \"serial\"\n :license \"MPL-2.0\"\n :doc \"A board on a serial port — an Arduino's Serial.println, an ESP32… — while ▶ runs. open (a click: the browser asks which port) at baud (115200); close lets it go. Each line it sends: numbers (\\\"512 300 1\\\", or with commas) go out as a list on the left; key:value pairs (\\\"pot:512 light=300\\\") as [key value] each; anything else as text; and every line as events on the right ({:type :serial :values […]}, {:type :serial :key \\\"pot\\\" :value 512}, {:type :serial :text …}). A text or a list on the left goes to the board as a line — a text is always a line, even \\\"open\\\"; the orders are :open and :close. Web Serial: Chrome, Edge and Firefox 151+; not Safari.\"\n :usage \"serial [baud]\"\n :io [1 2]\n :size [96 30]\n :args [[:baud 115200]]\n :help {:inlets [\":open (asks for the port), :close, or a line to send to the board\"]\n :outlets [\"the numbers of a line (a list), or [key value] for each key:value\" \"every line, as events\"]\n :example \"(box :b1 \\\"msg :open\\\" 40 30)\\n(box :b2 \\\"serial 9600\\\" 40 70)\\n(box :b3 \\\"print\\\" 40 120)\\n(connect :b1 0 :b2 0)\\n(connect :b2 0 :b3 0)\"\n :try \"Press ▶, click open and choose the board's port: what it prints arrives as numbers.\"\n :see [\"motion\" \"gamepad\" \"oscout\"]}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args]}]\n (let [buf (or (:buf state) \"\")]\n (cond\n (and (= inlet :audio) (:error value)) {:state state :effects [[:print (:error value)]] :show {:label \"no port\"}}\n (and (= inlet :audio) (:status value)) {:state state :show {:label (:status value)}}\n (and (= inlet :audio) (string? (:text value)))\n (let [[b2 es] (chunk buf (:text value))]\n (cond-> {:state (assoc state :buf b2)\n :out (vec (mapcat (fn [e] [(cond (:values e) [0 (:values e)]\n (contains? e :value) [0 [(:key e) (:value e)]]\n :else [0 (or (:text e) \"\")])\n [1 e]])\n es))\n }\n (seq es) (assoc :show {:label (let [e (last es)] (cond (:values e) (str (:values e)) (:key e) (str (:key e) \" \" (or (:value e) (:text e))) :else (:text e)))})))\n (#{:open} value) {:effects [[:open (api/clamp (:baud args) 300 4000000)]]}\n (#{:close} value) {:effects [[:close true]]}\n (string? value) {:effects [[:write value]]}\n (sequential? value) {:effects [[:write (apply str (interpose \" \" (map #(if (keyword? %) (name %) (str %)) value)))]]}\n :else {})))\n\n ;; ── view ──\n :derive (fn [{:keys [shown]}] {:label (or (:label shown) \"serial\")})\n :view [[:rect {:x 1 :y 1 :w 94 :h 28 :r 3 :stroke :accent :fill :bg}]\n [:text {:x 8 :y 19 :size 11} :$label]]\n\n ;; ── outside: the port, while ▶ runs ──\n :audio {:create (fn [_ b _] {:id (:id b) :port (atom nil) :writer (atom nil) :reader (atom nil) :alive (atom true) :inlets [] :outlets []})\n :effects {:open (fn [node baud _]\n (let [report (fn [v] (when @(:alive node) (api/report! (:id node) v nil)))]\n (if-not (.-serial js/navigator)\n (report {:error \"serial: this browser has no Web Serial (Chrome, Edge or Firefox 151+)\"})\n (-> (.requestPort (.-serial js/navigator))\n (.then (fn [port] (.then (.open port #js {:baudRate baud}) (fn [_] port))))\n (.then (fn [port]\n (reset! (:port node) port)\n (reset! (:writer node) (.getWriter (.-writable port)))\n (report {:status (str \"open · \" baud)})\n (let [dec (js/TextDecoderStream.)\n _ (.catch (.pipeTo (.-readable port) (.-writable dec)) (fn [_] nil))\n reader (.getReader (.-readable dec))]\n (reset! (:reader node) reader)\n ((fn step []\n (-> (.read reader)\n (.then (fn [r] (if (.-done r)\n (report {:status \"closed\"})\n (do (report {:text (.-value r)}) (step)))))\n (.catch (fn [_] (report {:status \"closed\"})))))))))\n (.catch (fn [e] (report {:error (str \"serial: \" (.-message e))})))))))\n :write (fn [node line _]\n (when-let [w @(:writer node)] (.write w (.encode (js/TextEncoder.) (str line \"\\n\")))))\n :close (fn [node _ _]\n (when-let [r @(:reader node)] (.catch (.cancel r) (fn [_] nil)))\n (when-let [w @(:writer node)] (.releaseLock w))\n (when-let [p @(:port node)] (js/setTimeout (fn [] (.catch (.close p) (fn [_] nil))) 50))\n (reset! (:port node) nil) (reset! (:writer node) nil))}\n :dispose (fn [node]\n (reset! (:alive node) false)\n (when-let [r @(:reader node)] (.catch (.cancel r) (fn [_] nil)))\n (when-let [w @(:writer node)] (try (.releaseLock w) (catch :default _ nil)))\n (when-let [p @(:port node)] (js/setTimeout (fn [] (.catch (.close p) (fn [_] nil))) 50)))}})\n"
|
|
9
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kairotic/io",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.5",
|
|
4
|
+
"description": "Kairotic talking to the outside: MIDI in and out (with MPE), OSC through a relay's bridge, a phone's motion, gamepads and boards on a serial port, as one kind of event",
|
|
5
|
+
"author": "bonuoq",
|
|
6
|
+
"license": "MPL-2.0",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/bonuoq/kairotic.git",
|
|
10
|
+
"directory": "packages/io"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/bonuoq/kairotic/tree/main/packages#readme",
|
|
13
|
+
"type": "module",
|
|
14
|
+
"main": "dist/index.mjs",
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"src",
|
|
18
|
+
"README.md"
|
|
19
|
+
],
|
|
20
|
+
"publishConfig": {
|
|
21
|
+
"access": "public"
|
|
22
|
+
},
|
|
23
|
+
"kairotic": {
|
|
24
|
+
"api": 1
|
|
25
|
+
},
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "node ../build.mjs io",
|
|
28
|
+
"prepublishOnly": "node ../build.mjs io"
|
|
29
|
+
},
|
|
30
|
+
"keywords": [
|
|
31
|
+
"kairotic",
|
|
32
|
+
"music",
|
|
33
|
+
"midi",
|
|
34
|
+
"mpe",
|
|
35
|
+
"osc",
|
|
36
|
+
"gamepad",
|
|
37
|
+
"web-serial",
|
|
38
|
+
"patcher"
|
|
39
|
+
]
|
|
40
|
+
}
|