omnipython-apps 0.1.4.dev8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. apps/__init__.py +5 -0
  2. apps/about/__init__.py +257 -0
  3. apps/about/app.json +1 -0
  4. apps/about/credits.py +12 -0
  5. apps/about/facts.py +398 -0
  6. apps/about/fonts/OFL.txt +93 -0
  7. apps/about/fonts/latin1_14.bin +0 -0
  8. apps/about/fonts/latin1_16.bin +0 -0
  9. apps/about/fonts/latin1_24.bin +0 -0
  10. apps/about/fonts/latin1_32.bin +0 -0
  11. apps/about/fonts/latin1_40.bin +0 -0
  12. apps/backline/__init__.py +58 -0
  13. apps/backline/app.json +1 -0
  14. apps/backline/app.py +475 -0
  15. apps/backline/art.py +717 -0
  16. apps/backline/ask.py +781 -0
  17. apps/backline/box.py +502 -0
  18. apps/backline/cast.py +137 -0
  19. apps/backline/desk/__init__.py +329 -0
  20. apps/backline/desk/editor.py +331 -0
  21. apps/backline/desk/grid.py +154 -0
  22. apps/backline/desk/look.py +169 -0
  23. apps/backline/desk/pedals.py +102 -0
  24. apps/backline/desk/perform.py +157 -0
  25. apps/backline/desk/prompt.py +210 -0
  26. apps/backline/desk/strip.py +159 -0
  27. apps/backline/desk_main.py +226 -0
  28. apps/backline/engine.py +622 -0
  29. apps/backline/floor.py +509 -0
  30. apps/backline/footswitch.py +119 -0
  31. apps/backline/glyphs.py +82 -0
  32. apps/backline/kits.py +428 -0
  33. apps/backline/midipedal.py +362 -0
  34. apps/backline/page_data.py +413 -0
  35. apps/backline/parts.py +145 -0
  36. apps/backline/pedal.py +107 -0
  37. apps/backline/remote.py +134 -0
  38. apps/backline/songs/ballad_68.json +1 -0
  39. apps/backline/songs/bossa.json +1 -0
  40. apps/backline/songs/country_train.json +1 -0
  41. apps/backline/songs/funk.json +1 -0
  42. apps/backline/songs/metal.json +1 -0
  43. apps/backline/songs/pop.json +1 -0
  44. apps/backline/songs/rock.json +1 -0
  45. apps/backline/songs/shuffle.json +1 -0
  46. apps/battery/__init__.py +101 -0
  47. apps/battery/app.json +1 -0
  48. apps/bit_world/act_deck.py +683 -0
  49. apps/bit_world/act_game.py +762 -0
  50. apps/bit_world/act_pet.py +1032 -0
  51. apps/bit_world/app.json +1 -0
  52. apps/bit_world/bit_output.py +45 -0
  53. apps/bit_world/bit_palette.py +503 -0
  54. apps/bit_world/bit_sound.py +431 -0
  55. apps/bit_world/bit_sprites.py +632 -0
  56. apps/bit_world/bit_world.py +534 -0
  57. apps/btreceiver/__init__.py +690 -0
  58. apps/btreceiver/app.json +1 -0
  59. apps/btreceiver/chime.py +155 -0
  60. apps/btreceiver/demo.py +529 -0
  61. apps/btreceiver/screen.py +633 -0
  62. apps/camera/__init__.py +316 -0
  63. apps/camera/app.json +1 -0
  64. apps/card/__init__.py +113 -0
  65. apps/card/app.json +1 -0
  66. apps/cast/__init__.py +631 -0
  67. apps/cast/app.json +1 -0
  68. apps/cast/receivers.py +193 -0
  69. apps/chess/__init__.py +18 -0
  70. apps/chess/app.json +1 -0
  71. apps/chess/app.py +922 -0
  72. apps/chess/art.py +323 -0
  73. apps/chess/ble.py +411 -0
  74. apps/chess/engine.py +925 -0
  75. apps/chess/game.py +327 -0
  76. apps/chess/net.py +261 -0
  77. apps/clock/__init__.py +38 -0
  78. apps/clock/app.json +1 -0
  79. apps/detect/__init__.py +214 -0
  80. apps/detect/app.json +1 -0
  81. apps/fmsynth/__init__.py +41 -0
  82. apps/fmsynth/algorithms.py +61 -0
  83. apps/fmsynth/app.json +1 -0
  84. apps/fmsynth/app.py +355 -0
  85. apps/fmsynth/editor.py +206 -0
  86. apps/fmsynth/engine.py +257 -0
  87. apps/fmsynth/meters.py +262 -0
  88. apps/fmsynth/midi.py +375 -0
  89. apps/fmsynth/panel_view.py +1071 -0
  90. apps/fmsynth/patches/fmsynth-01.syx +0 -0
  91. apps/fmsynth/settings.py +138 -0
  92. apps/fmsynth/voice.py +398 -0
  93. apps/gamepad/__init__.py +685 -0
  94. apps/gamepad/app.json +1 -0
  95. apps/gamepad/pad.py +94 -0
  96. apps/gamepad/watch.py +352 -0
  97. apps/hidden/__init__.py +72 -0
  98. apps/hidden/app.json +1 -0
  99. apps/home/__init__.py +483 -0
  100. apps/home/app.json +1 -0
  101. apps/home/main.py +36 -0
  102. apps/homeassistant/__init__.py +213 -0
  103. apps/homeassistant/api.py +104 -0
  104. apps/homeassistant/app.json +1 -0
  105. apps/huey/__init__.py +287 -0
  106. apps/huey/acting.py +184 -0
  107. apps/huey/actor.py +194 -0
  108. apps/huey/app.json +1 -0
  109. apps/huey/client.py +125 -0
  110. apps/huey/servers.py +121 -0
  111. apps/huey/settings.example.json +8 -0
  112. apps/huey/settings.py +97 -0
  113. apps/huey/turn.py +504 -0
  114. apps/huey/voice.py +217 -0
  115. apps/info/__init__.py +810 -0
  116. apps/info/app.json +1 -0
  117. apps/lora/__init__.py +62 -0
  118. apps/lora/app.json +1 -0
  119. apps/manifest.py +71 -0
  120. apps/medialink_baby_monitor/__init__.py +222 -0
  121. apps/medialink_baby_monitor/app.json +1 -0
  122. apps/medialink_doorbell/__init__.py +251 -0
  123. apps/medialink_doorbell/app.json +1 -0
  124. apps/medialink_hands_free/__init__.py +217 -0
  125. apps/medialink_hands_free/app.json +1 -0
  126. apps/medialink_surveillance_camera/__init__.py +258 -0
  127. apps/medialink_surveillance_camera/app.json +1 -0
  128. apps/medialink_video_doorbell/__init__.py +289 -0
  129. apps/medialink_video_doorbell/app.json +1 -0
  130. apps/medialink_videophone/__init__.py +273 -0
  131. apps/medialink_videophone/app.json +1 -0
  132. apps/medialink_walkie_talkie/__init__.py +228 -0
  133. apps/medialink_walkie_talkie/app.json +1 -0
  134. apps/midicontroller/__init__.py +774 -0
  135. apps/midicontroller/app.json +1 -0
  136. apps/midicontroller/links.py +421 -0
  137. apps/midicontroller/surface.py +343 -0
  138. apps/midiengine/__init__.py +977 -0
  139. apps/midiengine/app.json +1 -0
  140. apps/midiengine/banks.py +85 -0
  141. apps/midiengine/midiin.py +165 -0
  142. apps/midiengine/player.py +392 -0
  143. apps/midiengine/umidiparser.py +1413 -0
  144. apps/mp3/__init__.py +240 -0
  145. apps/mp3/app.json +1 -0
  146. apps/perch/__init__.py +119 -0
  147. apps/perch/app.json +1 -0
  148. apps/perch/huey.py +481 -0
  149. apps/perch/huey_props.py +386 -0
  150. apps/perch/huey_shift.py +42 -0
  151. apps/perch/huey_views.py +296 -0
  152. apps/perch/scene_bench.py +680 -0
  153. apps/perch/scene_coast.py +479 -0
  154. apps/perch/scene_desk.py +492 -0
  155. apps/perch/stage.py +1274 -0
  156. apps/perch/vec.py +366 -0
  157. apps/repl/__init__.py +325 -0
  158. apps/repl/app.json +1 -0
  159. apps/roku/__init__.py +156 -0
  160. apps/roku/app.json +1 -0
  161. apps/rokucam/__init__.py +362 -0
  162. apps/rokucam/app.json +1 -0
  163. apps/security/__init__.py +261 -0
  164. apps/security/app.json +1 -0
  165. apps/settings/__init__.py +221 -0
  166. apps/settings/app.json +1 -0
  167. apps/shell/__init__.py +33 -0
  168. apps/shell/app.json +1 -0
  169. apps/spotify/__init__.py +669 -0
  170. apps/spotify/app.json +1 -0
  171. apps/spotify/screen.py +82 -0
  172. apps/steps/__init__.py +58 -0
  173. apps/steps/app.json +1 -0
  174. apps/stompbox/__init__.py +31 -0
  175. apps/stompbox/app.json +1 -0
  176. apps/stompbox/app.py +668 -0
  177. apps/stompbox/boards.json +20 -0
  178. apps/stompbox/effects.py +241 -0
  179. apps/stompbox/engine.py +340 -0
  180. apps/stompbox/footswitch.py +331 -0
  181. apps/stompbox/inputs.py +449 -0
  182. apps/stompbox/meter.py +72 -0
  183. apps/stompbox/outputs.py +135 -0
  184. apps/stompbox/pedals.txt +45 -0
  185. apps/stompbox/presets.py +106 -0
  186. apps/stompbox/styles.py +135 -0
  187. apps/stompbox/ui.py +817 -0
  188. apps/stompbox/wavfile.py +73 -0
  189. apps/synthstation/__init__.py +20 -0
  190. apps/synthstation/app.json +1 -0
  191. apps/synthstation/audio.py +397 -0
  192. apps/synthstation/catalog.py +50 -0
  193. apps/synthstation/meters.py +136 -0
  194. apps/synthstation/midi.py +380 -0
  195. apps/synthstation/pads.py +177 -0
  196. apps/synthstation/parts.py +128 -0
  197. apps/synthstation/station.py +1069 -0
  198. apps/system/__init__.py +11 -0
  199. apps/system/app.json +1 -0
  200. apps/touchcal/__init__.py +324 -0
  201. apps/touchcal/app.json +1 -0
  202. apps/touchcal/fit.py +262 -0
  203. apps/wake/__init__.py +268 -0
  204. apps/wake/app.json +1 -0
  205. apps/wake/feed.py +155 -0
  206. apps/watch/__init__.py +355 -0
  207. apps/watch/app.json +1 -0
  208. apps/watch/faces.py +35 -0
  209. apps/watch/wheel.py +157 -0
  210. apps/weather/__init__.py +278 -0
  211. apps/weather/app.json +1 -0
  212. apps/weather/icons.py +172 -0
  213. apps/weather/sizing.py +71 -0
  214. apps/weather/zippad.py +172 -0
  215. omnipython_apps-0.1.4.dev8.dist-info/METADATA +33 -0
  216. omnipython_apps-0.1.4.dev8.dist-info/RECORD +218 -0
  217. omnipython_apps-0.1.4.dev8.dist-info/WHEEL +5 -0
  218. omnipython_apps-0.1.4.dev8.dist-info/top_level.txt +1 -0
@@ -0,0 +1,241 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Pedals: one audioeffects effect each, behind the small shape the screen
6
+ and the engine use.
7
+
8
+ A pedal knows its effect's name, its knobs and patches, and whether it is on.
9
+ Its knobs are the effect's macros on the 0 to 127 scale, and each describes
10
+ itself for the screen::
11
+
12
+ {"key": 0, "label": "Drive", "min": 0, "max": 127, "default": 64,
13
+ "mode": "UNIPOLAR", "unit": ""}
14
+
15
+ The chain is wired when an effect is built, so the engine builds a pedal's
16
+ effect again whenever what feeds it changes, and the pedal carries its patch
17
+ and knob values across.
18
+ """
19
+
20
+ import array
21
+ import time
22
+
23
+ import audiocore
24
+
25
+ from . import CHANNELS, SAMPLE_RATE
26
+
27
+ try:
28
+ import audioeffects
29
+ except ImportError: # main() says so; this module still imports
30
+ audioeffects = None
31
+
32
+
33
+ # Units as a knob's face has room for them.
34
+ _SHORT = {"cents": "ct", "degrees": "deg", "semitones": "st", "dBFS": "dB"}
35
+
36
+
37
+ def names():
38
+ """Every effect this build carries, by name."""
39
+ if audioeffects is None:
40
+ return []
41
+ return sorted(audioeffects.ALL, key=lambda n: n.lower())
42
+
43
+
44
+ def effect_class(name):
45
+ return getattr(audioeffects, name)
46
+
47
+
48
+ def category(name):
49
+ """The effect's own category: "Distortion", "Delay", "Reverb"."""
50
+ cats = getattr(effect_class(name), "CATEGORIES", ()) or ("",)
51
+ if cats[0] == "Effect Rack" and len(cats) > 1:
52
+ return cats[1]
53
+ return cats[0]
54
+
55
+
56
+ def display_name(name):
57
+ cls = effect_class(name)
58
+ return getattr(cls, "DISPLAY_NAME", None) or name
59
+
60
+
61
+ class Pedal:
62
+ """One effect in one slot. ``on`` False is bypass: the engine leaves it
63
+ out of the chain, and it keeps its knobs for when it comes back."""
64
+
65
+ def __init__(self, name, on=True, patch=0, macros=None):
66
+ cls = effect_class(name)
67
+ self.name = name
68
+ self.title = getattr(cls, "DISPLAY_NAME", None) or name
69
+ self.on = bool(on)
70
+ self.effect = None
71
+ #: The share of real time it took when measured, or None.
72
+ self.load = None
73
+ labels = tuple(cls.MACRO_LABELS)
74
+ modes = getattr(cls, "MACRO_MODES", {})
75
+ units = getattr(cls, "_MACRO_UNITS", {})
76
+ patches = getattr(cls, "PATCHES", None) or {}
77
+ self.patch_names = [patches[i][0] for i in sorted(patches)]
78
+ first = patches[0][1] if 0 in patches else (64,) * len(labels)
79
+ self._params = [
80
+ {"key": i, "label": labels[i], "min": 0, "max": 127,
81
+ "default": first[i] if i < len(first) else 64,
82
+ "mode": modes.get(i, "UNIPOLAR"), "unit": units.get(i, "")}
83
+ for i in range(len(labels))]
84
+ self.patch = patch if patch in patches else (0 if patches else None)
85
+ if macros is None:
86
+ macros = patches[self.patch][1] if self.patch is not None else first
87
+ self.macros = [float(v) for v in macros][:len(labels)]
88
+ while len(self.macros) < len(labels):
89
+ self.macros.append(64.0)
90
+
91
+ # -- the effect --------------------------------------------------------
92
+
93
+ def build(self, source):
94
+ """Build the effect on *source* with this pedal's patch and knobs,
95
+ and return its output. An effect built before is let go first."""
96
+ self.release()
97
+ fx = audioeffects.create(self.name, source, SAMPLE_RATE)
98
+ if self.patch:
99
+ fx.program_change(self.patch)
100
+ for i, v in enumerate(self.macros):
101
+ if abs(fx.get_macro(i) - v) > 1e-6:
102
+ fx.set_macro(i, v)
103
+ self.effect = fx
104
+ return fx.output
105
+
106
+ def release(self):
107
+ if self.effect is not None:
108
+ fx, self.effect = self.effect, None
109
+ fx.deinit()
110
+
111
+ # -- knobs and patches ---------------------------------------------------
112
+
113
+ def parameters(self):
114
+ return self._params
115
+
116
+ def set(self, key, value):
117
+ value = max(0.0, min(127.0, float(value)))
118
+ self.macros[key] = value
119
+ if self.effect is not None:
120
+ self.effect.set_macro(key, value)
121
+
122
+ def get(self, key):
123
+ return self.macros[key]
124
+
125
+ def text(self, key):
126
+ """What knob *key* stands for, in its own units: "720 Hz", "0.35"."""
127
+ p = self._params[key]
128
+ if p["mode"] == "TOGGLE":
129
+ return "on" if self.macros[key] >= 64 else "off"
130
+ if self.effect is None:
131
+ return "%d" % int(self.macros[key])
132
+ v = self.effect.macro(key)
133
+ unit = _SHORT.get(p["unit"], p["unit"])
134
+ a = abs(v)
135
+ if unit == "Hz" and a >= 1000:
136
+ return "%.1f kHz" % (v / 1000)
137
+ if unit == "ms" and a >= 1000:
138
+ return "%.2f s" % (v / 1000)
139
+ if a >= 100 or (unit == "dB" and a >= 10):
140
+ s = "%d" % int(round(v))
141
+ elif a >= 10:
142
+ s = "%.1f" % v
143
+ else:
144
+ s = "%.2f" % v
145
+ return s + (" " + unit if unit else "")
146
+
147
+ def set_patch(self, index):
148
+ """Choose a patch: every knob moves to it."""
149
+ if not (0 <= index < len(self.patch_names)):
150
+ return
151
+ self.patch = index
152
+ self.macros = [float(v) for v in effect_class(self.name).PATCHES[index][1]]
153
+ if self.effect is not None:
154
+ self.effect.program_change(index)
155
+
156
+ # -- saving --------------------------------------------------------------
157
+
158
+ def state(self):
159
+ return {"name": self.name, "on": self.on, "patch": self.patch,
160
+ "macros": [round(v, 2) for v in self.macros]}
161
+
162
+ @classmethod
163
+ def from_state(cls, d):
164
+ return cls(d["name"], on=d.get("on", True), patch=d.get("patch", 0),
165
+ macros=d.get("macros"))
166
+
167
+
168
+ def _test_tone(frames):
169
+ """A 110 Hz saw at about -9 dBFS: loud enough that drives drive and gates
170
+ open."""
171
+ tone = array.array("h", bytes(frames * CHANNELS * 2))
172
+ period = SAMPLE_RATE // 110
173
+ for i in range(frames):
174
+ v = (i % period) * 24000 // period - 12000
175
+ tone[i * CHANNELS] = v
176
+ tone[i * CHANNELS + 1] = v
177
+ return audiocore.RawSample(tone, sample_rate=SAMPLE_RATE,
178
+ channel_count=CHANNELS)
179
+
180
+
181
+ def _now_s():
182
+ if hasattr(time, "ticks_us"):
183
+ return time.ticks_us()
184
+ return time.perf_counter()
185
+
186
+
187
+ def _since_s(t0):
188
+ if hasattr(time, "ticks_us"):
189
+ return time.ticks_diff(time.ticks_us(), t0) / 1e6
190
+ return time.perf_counter() - t0
191
+
192
+
193
+ def measure(name, blocks=24):
194
+ """The share of real time *name* takes here: a copy of it renders
195
+ *blocks* blocks of a test tone, timed. 0.3 is a third of each block's
196
+ time; above 1.0 it can't keep up. None where the build can't pull a
197
+ source by hand."""
198
+ if not hasattr(audiocore, "get_buffer"):
199
+ return None
200
+ fx = audioeffects.create(name, _test_tone(4096), SAMPLE_RATE)
201
+ try:
202
+ audiocore.get_buffer(fx.output) # a lazy effect builds on its first pull
203
+ got = 0
204
+ t0 = _now_s()
205
+ for _ in range(blocks):
206
+ _, buf = audiocore.get_buffer(fx.output)
207
+ got += len(buf) // (2 * CHANNELS)
208
+ spent = _since_s(t0)
209
+ finally:
210
+ fx.deinit()
211
+ if not got:
212
+ return None
213
+ return spent * SAMPLE_RATE / got
214
+
215
+
216
+ def _app_file(name):
217
+ here = __file__.replace("\\", "/")
218
+ return here[:here.rfind("/") + 1] + name
219
+
220
+
221
+ def guitar_set(path=None):
222
+ """The curated pedals from pedals.txt, in its order, as (group, name)
223
+ pairs. Names this build doesn't carry are left out."""
224
+ # Imported here: appkit brings the screen with it, and the engine that
225
+ # imports this module runs without one in the audio checks.
226
+ from appkit import assets
227
+
228
+ carried = set(names())
229
+ found = []
230
+ group = ""
231
+ try:
232
+ text = assets.read(path or _app_file("pedals.txt"))
233
+ except OSError:
234
+ return found
235
+ for line in text.split("\n"):
236
+ line = line.strip()
237
+ if line.startswith("##"):
238
+ group = line[2:].strip()
239
+ elif line and not line.startswith("#") and line in carried:
240
+ found.append((group, line))
241
+ return found
@@ -0,0 +1,340 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """The engine: input -> up to four pedals -> master -> output.
6
+
7
+ clip or live --> input mixer (loop) --> pedal 1 --> ... --> pedal 4
8
+ --> master mixer --> DC blocker --> output
9
+
10
+ Every node is an audiodsp node; Python builds the graph and moves knobs. A
11
+ pedal that is off is left out of the graph, as a true-bypass switch takes it
12
+ out of the circuit. An audioeffects effect is wired to its source when it is
13
+ built, so adding, removing, moving or switching a pedal builds every pedal
14
+ after that point again, and the master voice moves to the new end of the
15
+ chain before the old effects are let go.
16
+
17
+ Where the pump plays the output, a tap copies what it sends. `Engine.service`
18
+ reads the tap once and hands the audio to the level meter, and to the recorder
19
+ while there is one.
20
+ """
21
+
22
+ from array import array
23
+
24
+ import audiomixer
25
+
26
+ try:
27
+ import audiobiquad
28
+ except ImportError:
29
+ audiobiquad = None
30
+
31
+ from . import BLOCK_FRAMES, CHANNELS, SAMPLE_RATE
32
+ from .meter import Level
33
+
34
+ try:
35
+ import audiopump
36
+ except ImportError:
37
+ audiopump = None
38
+
39
+ _BUF = BLOCK_FRAMES * CHANNELS * 2
40
+
41
+ #: The most pedals a board holds.
42
+ MAX_PEDALS = 4
43
+
44
+ # A high-pass this low is inaudible on a guitar (its lowest string is 82 Hz)
45
+ # and takes out any offset an effect leaves at an extreme setting, which a
46
+ # speaker can only heat.
47
+ DC_BLOCK_HZ = 5
48
+
49
+ # The tap holds 85 ms for the meter, which is read every 10 ms, and a second
50
+ # while recording, so a slow moment on the screen loses none of the take.
51
+ METER_FRAMES = 4096
52
+ RECORD_FRAMES = SAMPLE_RATE
53
+
54
+
55
+ def _mixer():
56
+ return audiomixer.Mixer(voice_count=1, sample_rate=SAMPLE_RATE,
57
+ channel_count=CHANNELS, bits_per_sample=16,
58
+ samples_signed=True, buffer_size=_BUF)
59
+
60
+
61
+ class Engine:
62
+ def __init__(self, output):
63
+ self.output = output
64
+ self.input = None
65
+ #: The pedals in signal order, `effects.Pedal` each.
66
+ self.pedals = []
67
+ self.loop = True
68
+ self.playing = False
69
+ self.master = 0.8
70
+ self._in = _mixer()
71
+ self._out = _mixer()
72
+ self._out.voice[0].level = self.master
73
+ self._tail = self._out
74
+ if audiobiquad is not None:
75
+ self._dc = audiobiquad.Biquad(
76
+ mode=audiobiquad.HIGH_PASS, frequency=DC_BLOCK_HZ, Q=0.707,
77
+ sample_rate=SAMPLE_RATE, channel_count=CHANNELS)
78
+ self._dc.play(self._out)
79
+ self._tail = self._dc
80
+ self._recorder = None
81
+ self._started = False
82
+ self._level = Level()
83
+ self._tap = None
84
+ if audiopump is not None and hasattr(audiopump, "Tap"):
85
+ self._open_tap(METER_FRAMES)
86
+
87
+ # -- what plays --------------------------------------------------------
88
+
89
+ def set_input(self, inp):
90
+ was = self.playing
91
+ self.stop()
92
+ old, self.input = self.input, inp
93
+ if old is not None and old is not inp and hasattr(old, "close"):
94
+ # A live input holds a device, and between two clocks a thread.
95
+ old.close()
96
+ if was:
97
+ self.play()
98
+
99
+ # -- the pedals --------------------------------------------------------
100
+
101
+ def add(self, pedal, at=None):
102
+ """Put *pedal* in the chain at *at* (the end if None). Refused with
103
+ ValueError when the board is full."""
104
+ if len(self.pedals) >= MAX_PEDALS:
105
+ raise ValueError("the board holds %d pedals" % MAX_PEDALS)
106
+ at = len(self.pedals) if at is None else max(0, min(at, len(self.pedals)))
107
+ self.pedals.insert(at, pedal)
108
+ self._rewire(at)
109
+ return at
110
+
111
+ def replace(self, index, pedal):
112
+ """Swap the pedal at *index* for *pedal*."""
113
+ old = self.pedals[index]
114
+ self.pedals[index] = pedal
115
+ self._rewire(index, [old])
116
+
117
+ def remove(self, index):
118
+ old = self.pedals.pop(index)
119
+ self._rewire(index, [old])
120
+ return old
121
+
122
+ def move(self, index, to):
123
+ """Move the pedal at *index* to position *to*."""
124
+ to = max(0, min(to, len(self.pedals) - 1))
125
+ if to == index:
126
+ return index
127
+ p = self.pedals.pop(index)
128
+ self.pedals.insert(to, p)
129
+ self._rewire(min(index, to))
130
+ return to
131
+
132
+ def set_on(self, index, on):
133
+ """Switch the pedal at *index* on, or out of the chain."""
134
+ p = self.pedals[index]
135
+ if p.on == bool(on):
136
+ return
137
+ p.on = bool(on)
138
+ self._rewire(index)
139
+
140
+ def set_board(self, pedals):
141
+ """Replace the whole chain with *pedals*."""
142
+ old = self.pedals
143
+ self.pedals = list(pedals[:MAX_PEDALS])
144
+ self._rewire(0, old)
145
+
146
+ def load(self):
147
+ """The measured share of real time the pedals that are on take
148
+ together, or None where nothing was measured."""
149
+ loads = [p.load for p in self.pedals if p.on and p.load is not None]
150
+ return sum(loads) if loads else None
151
+
152
+ def _rewire(self, start, gone=()):
153
+ """Build every pedal from *start* on again, on whatever now feeds
154
+ it, move the master voice to the new end, and only then let the old
155
+ effects go: the pump may be pulling them until the voice moves."""
156
+ old = [p.effect for p in gone if p.effect is not None]
157
+ for p in gone:
158
+ p.effect = None
159
+ tail = self._in
160
+ for i, p in enumerate(self.pedals):
161
+ if not p.on:
162
+ if p.effect is not None:
163
+ old.append(p.effect)
164
+ p.effect = None
165
+ continue
166
+ if i < start and p.effect is not None:
167
+ tail = p.effect.output
168
+ continue
169
+ if p.effect is not None:
170
+ old.append(p.effect)
171
+ p.effect = None
172
+ tail = p.build(tail)
173
+ self._out.voice[0].play(tail)
174
+ for fx in old:
175
+ fx.deinit()
176
+ self._start_output()
177
+
178
+ def set_output(self, output):
179
+ """Play through *output* from now on: the old one is closed, and what
180
+ was playing carries on there."""
181
+ old, self.output = self.output, output
182
+ started, self._started = self._started, False
183
+ if old is not output:
184
+ old.close()
185
+ if started:
186
+ self._start_output()
187
+
188
+ def _start_output(self):
189
+ if not self._started:
190
+ self.output.play(self._tail)
191
+ self._started = True
192
+
193
+ # -- transport ---------------------------------------------------------
194
+
195
+ def play(self):
196
+ if self.input is None:
197
+ return
198
+ self._in.voice[0].play(self.input.source(), loop=self.loop)
199
+ self.playing = True
200
+ self._start_output()
201
+
202
+ def stop(self):
203
+ self._in.voice[0].stop()
204
+ self.playing = False
205
+
206
+ def set_loop(self, on):
207
+ self.loop = bool(on)
208
+ if self.playing:
209
+ self.play()
210
+
211
+ def set_master(self, level):
212
+ self.master = max(0.0, min(1.0, float(level)))
213
+ self._out.voice[0].level = self.master
214
+
215
+ def service(self):
216
+ """Call from the app's loop: keeps the output fed where Python feeds
217
+ it, the meter reading and the recorder writing."""
218
+ if self.input is not None and hasattr(self.input, "service"):
219
+ self.input.service() # a browser's microphone, before it's played
220
+ self.output.service()
221
+ if self.playing and not self._in.voice[0].playing:
222
+ self.playing = False
223
+ self._hear()
224
+
225
+ # -- what went out: the meter, and a recording for checking --------------
226
+
227
+ def _open_tap(self, frames):
228
+ self._tap = audiopump.Tap(frames=frames, channel_count=CHANNELS)
229
+ audiopump.tap(self._tap)
230
+ stats = self._tap.stats()
231
+ self._seen = stats[0]
232
+ self._heard = array("h", bytes(stats[4]))
233
+
234
+ def _hear(self):
235
+ """Read what the pump has sent since the last call, once, for the
236
+ meter and the recorder."""
237
+ tap = self._tap
238
+ if tap is None:
239
+ return
240
+ # The tap hands back its newest audio, and the pump can add a block
241
+ # between asking how much there is and reading it. A read counts only
242
+ # if the count is the same on both sides of it, so it ends where the
243
+ # count says and joins on to the last one.
244
+ for _ in range(4):
245
+ written = tap.stats()[0]
246
+ new = (written - self._seen) & 0xFFFFFFFF
247
+ if not new:
248
+ return
249
+ room = len(self._heard) * 2
250
+ lost = 0
251
+ if new > room:
252
+ lost = new - room
253
+ new = room
254
+ n = tap.readinto(memoryview(self._heard)[:new // 2])
255
+ if tap.stats()[0] == written:
256
+ break
257
+ else:
258
+ return # the next call picks up from the same place
259
+ if not n: # already read at this count: the next block brings more
260
+ return
261
+ self._seen = written
262
+ samples = memoryview(self._heard)[:n // 2]
263
+ self._level.feed(samples)
264
+ if self._recorder is not None:
265
+ self._recorder.take(samples, lost)
266
+
267
+ def level(self):
268
+ """``(level, clipped)`` for what has played since the last call.
269
+
270
+ The level is the peak at the effect's output as a share of full
271
+ scale, 0.0 to 1.0, whatever the master is set to, and ``clipped`` is
272
+ True when it came within half a decibel of full scale. Both are
273
+ zero where no pump plays the output, as there is nothing to tap.
274
+ """
275
+ return self._level.read(self.master)
276
+
277
+ def record(self, path):
278
+ if self._tap is None:
279
+ raise RuntimeError("recording needs audiopump")
280
+ self._open_tap(RECORD_FRAMES)
281
+ self._recorder = Recorder(path)
282
+
283
+ def stop_recording(self):
284
+ if self._recorder is None:
285
+ return None
286
+ self._hear()
287
+ r, self._recorder = self._recorder, None
288
+ self._open_tap(METER_FRAMES)
289
+ return r.close()
290
+
291
+ def close(self):
292
+ self.stop_recording()
293
+ if self._tap is not None:
294
+ self._tap = None
295
+ audiopump.tap(None)
296
+ self.stop()
297
+ self.output.close()
298
+ if self.input is not None and hasattr(self.input, "close"):
299
+ self.input.close()
300
+ # The master voice lets go of the chain before the effects go.
301
+ self._out.voice[0].stop()
302
+ for p in self.pedals:
303
+ p.release()
304
+
305
+ def latency(self):
306
+ """(total ms, held ms, device periods ms) for a live input on a
307
+ speaker the pump writes, or None where there is nothing to measure.
308
+
309
+ Held is what the software path holds at this moment: the
310
+ microphone's backlog, the ring between two clocks, and the speaker's
311
+ queue. The periods are the device engine's, one each side."""
312
+ inp, out = self.input, self.output
313
+ if inp is None or not hasattr(inp, "held_frames") \
314
+ or not hasattr(out, "held_frames"):
315
+ return None
316
+ held = inp.held_frames() + out.held_frames()
317
+ periods = inp.period_frames() + out.period_frames()
318
+ ms = 1000 / SAMPLE_RATE
319
+ return (held + periods) * ms, held * ms, periods * ms
320
+
321
+
322
+ class Recorder:
323
+ """Writes what the pump plays, from the audio the engine reads off its tap."""
324
+
325
+ def __init__(self, path):
326
+ self.path = path
327
+ self._chunks = []
328
+ self.lost = 0
329
+
330
+ def take(self, samples, lost=0):
331
+ """Keep a stretch of samples; *lost* bytes before it were overwritten."""
332
+ self._chunks.append(bytes(samples))
333
+ self.lost += lost
334
+
335
+ def close(self):
336
+ from . import wavfile
337
+
338
+ pcm = b"".join(self._chunks)
339
+ wavfile.write(self.path, SAMPLE_RATE, CHANNELS, pcm)
340
+ return len(pcm) // (2 * CHANNELS)