@kairotic/io 0.2.0 → 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/dist/control.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // Generated by packages/build.mjs from src/control.cljs
2
2
  export default {
3
3
  "class": "control",
4
- "version": "0.2.0",
4
+ "version": "0.2.5",
5
5
  "author": "bonuoq",
6
6
  "license": "MPL-2.0",
7
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.",
package/dist/gamepad.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // Generated by packages/build.mjs from src/gamepad.cljs
2
2
  export default {
3
3
  "class": "gamepad",
4
- "version": "0.2.0",
4
+ "version": "0.2.5",
5
5
  "author": "bonuoq",
6
6
  "license": "MPL-2.0",
7
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.",
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // Generated by packages/build.mjs
2
2
  export default {
3
3
  "package": "@kairotic/io",
4
- "version": "0.2.0",
4
+ "version": "0.2.5",
5
5
  "api": 1,
6
6
  "author": "bonuoq",
7
7
  "license": "MPL-2.0",
@@ -21,14 +21,14 @@ export default {
21
21
  {
22
22
  "class": "midiin",
23
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 \"clear\"} 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"
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
26
  },
27
27
  {
28
28
  "class": "midiout",
29
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\" \"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 \"clear\"} 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"
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
32
  },
33
33
  {
34
34
  "class": "motion",
@@ -51,8 +51,8 @@ export default {
51
51
  {
52
52
  "class": "serial",
53
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 (other than open/close) goes to the board as a line. 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 (other than open/close) goes to the board as a line. 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 \"open\"} value) {:effects [[:open (api/clamp (:baud args) 300 4000000)]]}\n (#{:close \"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"
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
56
  }
57
57
  ]
58
58
  };
package/dist/midiin.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  // Generated by packages/build.mjs from src/midiin.cljs
2
2
  export default {
3
3
  "class": "midiin",
4
- "version": "0.2.0",
4
+ "version": "0.2.5",
5
5
  "author": "bonuoq",
6
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 \"clear\"} 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"
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
9
  };
package/dist/midiout.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  // Generated by packages/build.mjs from src/midiout.cljs
2
2
  export default {
3
3
  "class": "midiout",
4
- "version": "0.2.0",
4
+ "version": "0.2.5",
5
5
  "author": "bonuoq",
6
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\" \"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 \"clear\"} 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"
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
9
  };
package/dist/motion.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // Generated by packages/build.mjs from src/motion.cljs
2
2
  export default {
3
3
  "class": "motion",
4
- "version": "0.2.0",
4
+ "version": "0.2.5",
5
5
  "author": "bonuoq",
6
6
  "license": "MPL-2.0",
7
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.",
package/dist/oscin.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // Generated by packages/build.mjs from src/oscin.cljs
2
2
  export default {
3
3
  "class": "oscin",
4
- "version": "0.2.0",
4
+ "version": "0.2.5",
5
5
  "author": "bonuoq",
6
6
  "license": "MPL-2.0",
7
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.",
package/dist/oscout.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // Generated by packages/build.mjs from src/oscout.cljs
2
2
  export default {
3
3
  "class": "oscout",
4
- "version": "0.2.0",
4
+ "version": "0.2.5",
5
5
  "author": "bonuoq",
6
6
  "license": "MPL-2.0",
7
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 ▶.",
package/dist/serial.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  // Generated by packages/build.mjs from src/serial.cljs
2
2
  export default {
3
3
  "class": "serial",
4
- "version": "0.2.0",
4
+ "version": "0.2.5",
5
5
  "author": "bonuoq",
6
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 (other than open/close) goes to the board as a line. 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 (other than open/close) goes to the board as a line. 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 \"open\"} value) {:effects [[:open (api/clamp (:baud args) 300 4000000)]]}\n (#{:close \"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"
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
9
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kairotic/io",
3
- "version": "0.2.0",
3
+ "version": "0.2.5",
4
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
5
  "author": "bonuoq",
6
6
  "license": "MPL-2.0",
package/src/midiin.cljs CHANGED
@@ -71,12 +71,12 @@
71
71
  {;; ── about ──
72
72
  :class "midiin"
73
73
  :license "MPL-2.0"
74
- :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."
74
+ :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."
75
75
  :usage "midiin [channel] [range]"
76
76
  :io [1 3]
77
77
  :size [96 30]
78
78
  :args [[:channel 0] [:range 2]]
79
- :help {:inlets ["clear (or :stop): every held note goes"]
79
+ :help {:inlets [":clear (or :stop): every held note goes"]
80
80
  :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"]
81
81
  :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)"
82
82
  :try "Press ▶ and play a MIDI keyboard: synth~ plays it and print shows every event. Bend a note: it glides."
@@ -105,7 +105,7 @@
105
105
  (when on [[0 [:gain (:amp on)]]])
106
106
  (when notes? [[0 hz]])
107
107
  (map (fn [e] [2 e]) es)))})))))
108
- (#{:clear :stop "clear"} value)
108
+ (#{:clear :stop} value)
109
109
  (let [offs (for [id (:order st) :let [h (get (:held st) id)]]
110
110
  {:src :midi :type :note :id id :ch (:ch h) :note (:note h) :freq (:freq h) :gate false})]
111
111
  {:state (fresh (:range0 st)) :out (vec (concat [[1 []] [0 []]] (map (fn [e] [2 e]) offs)))})
package/src/midiout.cljs CHANGED
@@ -78,12 +78,12 @@
78
78
  {;; ── about ──
79
79
  :class "midiout"
80
80
  :license "MPL-2.0"
81
- :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."
81
+ :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."
82
82
  :usage "midiout [mpe] [channel] [port] [range]"
83
83
  :io [2 0]
84
84
  :size [96 30]
85
85
  :args [[:mpe false] [:channel 1] [:port 1] [:range 48]]
86
- :help {:inlets ["the Hz of the notes sounding (a list), [:gain amp], an event map, or clear" "the voice ids of the Hz that follow"]
86
+ :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"]
87
87
  :outlets []
88
88
  :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)"
89
89
  :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."
@@ -99,7 +99,7 @@
99
99
  (= inlet :audio) {:state st}
100
100
  (= inlet 1) {:state (assoc st :ids (when (sequential? value) (vec value)))}
101
101
  (and (vector? value) (= :gain (first value)) (number? (second value))) {:state (assoc st :amp (api/clamp (second value) 0 1))}
102
- (#{:clear :stop "clear"} value)
102
+ (#{:clear :stop} value)
103
103
  (let [[e2 ms] (events enc (map (fn [id] {:type :note :id id :gate false}) (keys (:voices enc))))]
104
104
  (send (assoc st :enc e2 :snap {:hz [] :ids []}) ms))
105
105
  (map? value) (let [[e2 ms] (out-step enc value)] (send (assoc st :enc e2) ms))
package/src/serial.cljs CHANGED
@@ -20,14 +20,14 @@
20
20
  {;; ── about ──
21
21
  :class "serial"
22
22
  :license "MPL-2.0"
23
- :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 (other than open/close) goes to the board as a line. Web Serial: Chrome, Edge and Firefox 151+; not Safari."
23
+ :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."
24
24
  :usage "serial [baud]"
25
25
  :io [1 2]
26
26
  :size [96 30]
27
27
  :args [[:baud 115200]]
28
- :help {:inlets ["open (asks for the port), close, or a line to send to the board"]
28
+ :help {:inlets [":open (asks for the port), :close, or a line to send to the board"]
29
29
  :outlets ["the numbers of a line (a list), or [key value] for each key:value" "every line, as events"]
30
- :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)"
30
+ :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)"
31
31
  :try "Press ▶, click open and choose the board's port: what it prints arrives as numbers."
32
32
  :see ["motion" "gamepad" "oscout"]}
33
33
 
@@ -47,8 +47,8 @@
47
47
  es))
48
48
  }
49
49
  (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)))})))
50
- (#{:open "open"} value) {:effects [[:open (api/clamp (:baud args) 300 4000000)]]}
51
- (#{:close "close"} value) {:effects [[:close true]]}
50
+ (#{:open} value) {:effects [[:open (api/clamp (:baud args) 300 4000000)]]}
51
+ (#{:close} value) {:effects [[:close true]]}
52
52
  (string? value) {:effects [[:write value]]}
53
53
  (sequential? value) {:effects [[:write (apply str (interpose " " (map #(if (keyword? %) (name %) (str %)) value)))]]}
54
54
  :else {})))