omnipython-applibs 0.1.2__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.
- appkit/__init__.py +52 -0
- appkit/__init__.pyi +17 -0
- appkit/data.py +149 -0
- appkit/data.pyi +25 -0
- appkit/foreground.py +357 -0
- appkit/foreground.pyi +45 -0
- appkit/home.py +19 -0
- appkit/home.pyi +8 -0
- appkit/hover.py +59 -0
- appkit/hover.pyi +13 -0
- appkit/index.py +199 -0
- appkit/index.pyi +30 -0
- appkit/launcher.py +1075 -0
- appkit/launcher.pyi +96 -0
- appkit/manifest.py +75 -0
- appkit/manifest.pyi +8 -0
- appkit/net.py +167 -0
- appkit/net.pyi +34 -0
- appkit/places.py +202 -0
- appkit/places.pyi +39 -0
- appkit/py.typed +0 -0
- appkit/scope.py +636 -0
- appkit/scope.pyi +110 -0
- appkit/shell.py +121 -0
- appkit/shell.pyi +32 -0
- appkit/worker.py +409 -0
- appkit/worker.pyi +83 -0
- controlkit/__init__.py +19 -0
- controlkit/__init__.pyi +10 -0
- controlkit/_draw.py +88 -0
- controlkit/_safe.py +29 -0
- controlkit/dotmatrix.py +101 -0
- controlkit/dotmatrix.pyi +23 -0
- controlkit/encoder.py +297 -0
- controlkit/encoder.pyi +55 -0
- controlkit/font5x7.py +22 -0
- controlkit/font5x7.pyi +11 -0
- controlkit/lamp_button.py +92 -0
- controlkit/lamp_button.pyi +40 -0
- controlkit/meter.py +86 -0
- controlkit/meter.pyi +30 -0
- controlkit/mock.py +116 -0
- controlkit/mock.pyi +35 -0
- controlkit/pad_grid.py +113 -0
- controlkit/pad_grid.pyi +41 -0
- controlkit/py.typed +0 -0
- controlkit/slider.py +185 -0
- controlkit/slider.pyi +49 -0
- controlkit/sprites.py +279 -0
- controlkit/sprites.pyi +22 -0
- controlkit/theme.py +120 -0
- controlkit/theme.pyi +15 -0
- deskkit/__init__.py +74 -0
- deskkit/__init__.pyi +18 -0
- deskkit/forecast.py +261 -0
- deskkit/forecast.pyi +40 -0
- deskkit/localtime.py +215 -0
- deskkit/localtime.pyi +33 -0
- deskkit/py.typed +0 -0
- deskkit/shell.py +113 -0
- deskkit/shell.pyi +33 -0
- omnipython_applibs-0.1.2.dist-info/METADATA +90 -0
- omnipython_applibs-0.1.2.dist-info/RECORD +143 -0
- omnipython_applibs-0.1.2.dist-info/WHEEL +5 -0
- omnipython_applibs-0.1.2.dist-info/licenses/LICENSE +21 -0
- omnipython_applibs-0.1.2.dist-info/top_level.txt +9 -0
- programkit/__init__.py +27 -0
- programkit/__init__.pyi +8 -0
- programkit/board.py +56 -0
- programkit/board.pyi +20 -0
- programkit/press.py +63 -0
- programkit/press.pyi +17 -0
- programkit/py.typed +0 -0
- programkit/rows.py +149 -0
- programkit/rows.pyi +34 -0
- sayso/__init__.py +109 -0
- sayso/__init__.pyi +124 -0
- sayso/auth.py +811 -0
- sayso/auth.pyi +102 -0
- sayso/client.py +1286 -0
- sayso/client.pyi +138 -0
- sayso/keepalive.py +371 -0
- sayso/keepalive.pyi +53 -0
- sayso/local.py +85 -0
- sayso/local.pyi +28 -0
- sayso/object_specs.py +706 -0
- sayso/object_specs.pyi +8 -0
- sayso/objects.py +411 -0
- sayso/objects.pyi +854 -0
- sayso/py.typed +0 -0
- sayso/schema_coverage.py +210 -0
- sayso/schema_coverage.pyi +13 -0
- sayso/transport.py +426 -0
- sayso/transport.pyi +47 -0
- songmodel/__init__.py +30 -0
- songmodel/__init__.pyi +9 -0
- songmodel/link.py +189 -0
- songmodel/link.pyi +53 -0
- songmodel/model.py +238 -0
- songmodel/model.pyi +40 -0
- songmodel/page.html +225 -0
- songmodel/page_data.py +236 -0
- songmodel/page_data.pyi +6 -0
- songmodel/py.typed +0 -0
- soundmodule/__init__.py +7 -0
- soundmodule/__init__.pyi +6 -0
- soundmodule/engine.py +1001 -0
- soundmodule/engine.pyi +196 -0
- soundmodule/names.py +298 -0
- soundmodule/names.pyi +30 -0
- soundmodule/pipes.py +105 -0
- soundmodule/pipes.pyi +31 -0
- soundmodule/py.typed +0 -0
- soundmodule/run.py +249 -0
- soundmodule/run.pyi +49 -0
- spectrum/__init__.py +72 -0
- spectrum/__init__.pyi +30 -0
- spectrum/analyzer.py +231 -0
- spectrum/analyzer.pyi +67 -0
- spectrum/fake_music.py +201 -0
- spectrum/fake_music.pyi +36 -0
- spectrum/pump_levels.py +126 -0
- spectrum/pump_levels.pyi +46 -0
- spectrum/py.typed +0 -0
- spectrum/spectrum_view.py +403 -0
- spectrum/spectrum_view.pyi +80 -0
- touchkit/__init__.py +4 -0
- touchkit/__init__.pyi +4 -0
- touchkit/cam.py +146 -0
- touchkit/cam.pyi +35 -0
- touchkit/clock.py +18 -0
- touchkit/clock.pyi +6 -0
- touchkit/ecp.py +134 -0
- touchkit/ecp.pyi +28 -0
- touchkit/net.py +347 -0
- touchkit/net.pyi +27 -0
- touchkit/py.typed +0 -0
- touchkit/settings.py +85 -0
- touchkit/settings.pyi +17 -0
- touchkit/shell.py +268 -0
- touchkit/shell.pyi +42 -0
- touchkit/ui.py +167 -0
- touchkit/ui.pyi +53 -0
soundmodule/run.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 PyDevices
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
"""Run the sound module headless: MIDI in from a port, sound out to a WAV
|
|
5
|
+
file (and the sound card, where the interpreter has ``audiodev``).
|
|
6
|
+
|
|
7
|
+
python -m soundmodule.run --port "Sound module device side" --wav song.wav
|
|
8
|
+
micropython -m soundmodule.run --pipe /tmp/sm --wav song.wav --idle 4
|
|
9
|
+
|
|
10
|
+
``--port NAME`` opens the first MIDI input and output whose names contain
|
|
11
|
+
NAME, through ``midiports`` (Windows' own ports, or ALSA raw MIDI on
|
|
12
|
+
Linux). ``--pipe FOLDER`` reads and writes the two files
|
|
13
|
+
``tools/bridge.py`` keeps in step with a Windows port, for an interpreter
|
|
14
|
+
under WSL (``soundmodule.pipes``). Nothing is set up on the module: what
|
|
15
|
+
plays is whatever the MIDI asks for.
|
|
16
|
+
|
|
17
|
+
The sound is rendered as it is due, by the clock, so what reaches the WAV
|
|
18
|
+
is what a sound card would have played. ``--play`` plays it through
|
|
19
|
+
``audiodev`` instead, where there is one. It stops after ``--seconds`` (default
|
|
20
|
+
600), or ``--idle`` seconds after the last MIDI byte once some has come,
|
|
21
|
+
or ``--wait`` seconds after starting if none ever does; then it renders
|
|
22
|
+
``--tail`` seconds more, so the reverb dies away in the file.
|
|
23
|
+
|
|
24
|
+
At the end it prints what each part played and how far the renderer ever
|
|
25
|
+
fell behind the clock, and exits non-zero if no MIDI arrived.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
import sys
|
|
29
|
+
import time
|
|
30
|
+
|
|
31
|
+
from . import engine
|
|
32
|
+
|
|
33
|
+
RATE = 48000
|
|
34
|
+
CHANNELS = 2
|
|
35
|
+
|
|
36
|
+
if hasattr(time, "ticks_ms"):
|
|
37
|
+
ticks_ms, ticks_diff = time.ticks_ms, time.ticks_diff
|
|
38
|
+
else:
|
|
39
|
+
def ticks_ms():
|
|
40
|
+
return int(time.monotonic() * 1000)
|
|
41
|
+
|
|
42
|
+
def ticks_diff(a, b):
|
|
43
|
+
return a - b
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _sleep_ms(ms):
|
|
47
|
+
fn = getattr(time, "sleep_ms", None)
|
|
48
|
+
if fn is not None:
|
|
49
|
+
fn(ms)
|
|
50
|
+
else:
|
|
51
|
+
time.sleep(ms / 1000.0)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _interpreter():
|
|
55
|
+
impl = sys.implementation.name
|
|
56
|
+
return "%s %s (%s)" % (impl, ".".join(str(v) for v in sys.implementation.version[:3]), sys.platform)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Wav:
|
|
60
|
+
"""A 16-bit PCM WAV file written as it goes; ``close`` fixes the sizes."""
|
|
61
|
+
|
|
62
|
+
def __init__(self, path, rate=RATE, channels=CHANNELS):
|
|
63
|
+
self.f = open(path, "wb")
|
|
64
|
+
self.rate = rate
|
|
65
|
+
self.channels = channels
|
|
66
|
+
self.bytes = 0
|
|
67
|
+
self.f.write(self._header())
|
|
68
|
+
|
|
69
|
+
def _header(self):
|
|
70
|
+
import struct
|
|
71
|
+
|
|
72
|
+
block = self.channels * 2
|
|
73
|
+
return (b"RIFF" + struct.pack("<I", 36 + self.bytes) + b"WAVEfmt " +
|
|
74
|
+
struct.pack("<IHHIIHH", 16, 1, self.channels, self.rate, self.rate * block, block, 16) +
|
|
75
|
+
b"data" + struct.pack("<I", self.bytes))
|
|
76
|
+
|
|
77
|
+
def write(self, data):
|
|
78
|
+
self.f.write(data)
|
|
79
|
+
self.bytes += len(data)
|
|
80
|
+
|
|
81
|
+
def close(self):
|
|
82
|
+
self.f.seek(0)
|
|
83
|
+
self.f.write(self._header())
|
|
84
|
+
self.f.close()
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _open_ports(port, pipe):
|
|
88
|
+
if pipe:
|
|
89
|
+
from . import pipes
|
|
90
|
+
|
|
91
|
+
return pipes.ports(pipe)
|
|
92
|
+
if sys.platform.startswith("win"):
|
|
93
|
+
from midiports import windows as backend
|
|
94
|
+
else:
|
|
95
|
+
from midiports import linux as backend
|
|
96
|
+
return backend.ports(port)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _audio_out(module):
|
|
100
|
+
"""``audiodev``'s output playing the module, or None where there isn't one."""
|
|
101
|
+
try:
|
|
102
|
+
from audiodev import AudioFormat, AudioOut
|
|
103
|
+
except ImportError:
|
|
104
|
+
return None
|
|
105
|
+
out = AudioOut(AudioFormat(RATE, CHANNELS, 16))
|
|
106
|
+
out.play(module.output)
|
|
107
|
+
return out
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _frames(data):
|
|
111
|
+
"""Frames in a block of 16-bit samples, from its bytes: CircuitPython's
|
|
112
|
+
buffer counts samples, not bytes, so count ``bytes(buffer)``."""
|
|
113
|
+
return len(data) // (2 * CHANNELS)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def serve(module, midi_in, wav=None, seconds=600, idle=None, wait=None, tail=2.0, out=None, log=print):
|
|
117
|
+
"""Feed ``midi_in`` to ``module`` and render its output by the clock
|
|
118
|
+
into ``wav`` until one of the stops in the module's docstring. Returns
|
|
119
|
+
``(bytes of MIDI, [the most the render fell behind in ms before the
|
|
120
|
+
first note, and after it])``."""
|
|
121
|
+
import audiocore
|
|
122
|
+
|
|
123
|
+
buf = bytearray(256)
|
|
124
|
+
start = ticks_ms()
|
|
125
|
+
last = None # when MIDI last arrived
|
|
126
|
+
total = 0
|
|
127
|
+
frames = 0
|
|
128
|
+
worst = [0, 0] # behind the clock most, before the first note and after it
|
|
129
|
+
playing = 0
|
|
130
|
+
ending = None # frames to stop at, once a stop is due
|
|
131
|
+
while True:
|
|
132
|
+
n = midi_in.readinto(buf) if midi_in is not None else None
|
|
133
|
+
now = ticks_ms()
|
|
134
|
+
if n:
|
|
135
|
+
with engine.deferred(module):
|
|
136
|
+
module.feed(buf, n)
|
|
137
|
+
total += n
|
|
138
|
+
last = now
|
|
139
|
+
elapsed = ticks_diff(now, start)
|
|
140
|
+
if ending is None:
|
|
141
|
+
if elapsed >= seconds * 1000 or (
|
|
142
|
+
last is not None and idle is not None and ticks_diff(now, last) >= idle * 1000) or (
|
|
143
|
+
last is None and wait is not None and elapsed >= wait * 1000):
|
|
144
|
+
ending = frames + int(tail * RATE)
|
|
145
|
+
due = elapsed * RATE // 1000
|
|
146
|
+
if ending is not None and frames >= ending:
|
|
147
|
+
break
|
|
148
|
+
if wav is not None and frames < due:
|
|
149
|
+
module.fill()
|
|
150
|
+
data = bytes(audiocore.get_buffer(module.output)[1])
|
|
151
|
+
wav.write(data)
|
|
152
|
+
frames += _frames(data)
|
|
153
|
+
behind = (due - frames) * 1000 // RATE
|
|
154
|
+
if not playing:
|
|
155
|
+
for part in module.parts:
|
|
156
|
+
if part.notes:
|
|
157
|
+
playing = 1
|
|
158
|
+
break
|
|
159
|
+
if behind > worst[playing]:
|
|
160
|
+
worst[playing] = behind
|
|
161
|
+
continue # the port again before the next block
|
|
162
|
+
if wav is None:
|
|
163
|
+
frames = due
|
|
164
|
+
if out is not None:
|
|
165
|
+
module.fill()
|
|
166
|
+
service = getattr(out, "service", None)
|
|
167
|
+
if service is not None:
|
|
168
|
+
service()
|
|
169
|
+
_sleep_ms(1)
|
|
170
|
+
return total, worst
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def report(module, total, worst, log=print):
|
|
174
|
+
"""What came in and what played. ``worst`` is how far the render fell
|
|
175
|
+
behind the clock at most, before the first note and after it: behind
|
|
176
|
+
while notes play is what a listener would hear as a gap."""
|
|
177
|
+
log("soundmodule: %s: %d bytes of MIDI, %d Identity Requests answered, render behind by at most %d ms"
|
|
178
|
+
" while playing (%d ms before the first note)"
|
|
179
|
+
% (_interpreter(), total, module.identities, worst[1], worst[0]))
|
|
180
|
+
for part in module.parts:
|
|
181
|
+
for key in sorted(part.played):
|
|
182
|
+
notes, name = part.played[key]
|
|
183
|
+
log(" channel %2d: %4d notes, bank %d:%d program %d, %s"
|
|
184
|
+
% (part.channel + 1, notes, key[0], key[1], key[2], name))
|
|
185
|
+
if module.error is not None:
|
|
186
|
+
log(" last error: %s" % (module.error,))
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _args(argv):
|
|
190
|
+
opts = {"port": "Sound module device side", "pipe": None, "wav": None, "seconds": 600.0, "idle": None,
|
|
191
|
+
"wait": None, "tail": 2.0, "play": False, "bank": None}
|
|
192
|
+
i = 0
|
|
193
|
+
while i < len(argv):
|
|
194
|
+
a = argv[i]
|
|
195
|
+
if a == "--play":
|
|
196
|
+
opts["play"] = True
|
|
197
|
+
i += 1
|
|
198
|
+
continue
|
|
199
|
+
if not a.startswith("--") or a[2:] not in opts or i + 1 >= len(argv):
|
|
200
|
+
raise SystemExit("usage: run.py [--port NAME | --pipe FOLDER] [--wav PATH] [--seconds S] "
|
|
201
|
+
"[--idle S] [--wait S] [--tail S] [--bank SF2] [--play]")
|
|
202
|
+
key, value = a[2:], argv[i + 1]
|
|
203
|
+
opts[key] = float(value) if key in ("seconds", "idle", "wait", "tail") else value
|
|
204
|
+
i += 2
|
|
205
|
+
return opts
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def main(argv=None):
|
|
209
|
+
opts = _args(sys.argv[1:] if argv is None else argv)
|
|
210
|
+
if opts["play"] and opts["wav"]:
|
|
211
|
+
raise SystemExit("run.py: --play or --wav, not both: each would take every other block of sound")
|
|
212
|
+
midi_in, midi_out = _open_ports(opts["port"], opts["pipe"])
|
|
213
|
+
replies = [0, 0] # sent, refused by the port
|
|
214
|
+
|
|
215
|
+
def send(data):
|
|
216
|
+
if midi_out is None:
|
|
217
|
+
return
|
|
218
|
+
try:
|
|
219
|
+
midi_out.write(data)
|
|
220
|
+
replies[0] += 1
|
|
221
|
+
except NotImplementedError: # a port that can't send SysEx
|
|
222
|
+
replies[1] += 1
|
|
223
|
+
|
|
224
|
+
module = engine.Module(RATE, CHANNELS, bank=opts["bank"], send=send)
|
|
225
|
+
module.prepare() # the SoundFont, if there is one, opened before anything plays
|
|
226
|
+
wav = Wav(opts["wav"]) if opts["wav"] else None
|
|
227
|
+
out = _audio_out(module) if opts["play"] else None
|
|
228
|
+
print("soundmodule: listening on %s, %s" % (opts["pipe"] or opts["port"], _interpreter()))
|
|
229
|
+
try:
|
|
230
|
+
total, worst = serve(module, midi_in, wav, opts["seconds"], opts["idle"], opts["wait"], opts["tail"], out)
|
|
231
|
+
finally:
|
|
232
|
+
if wav is not None:
|
|
233
|
+
wav.close()
|
|
234
|
+
if out is not None:
|
|
235
|
+
out.stop()
|
|
236
|
+
report(module, total, worst)
|
|
237
|
+
if replies[0] or replies[1]:
|
|
238
|
+
print(" replies sent: %d, refused by the port: %d" % (replies[0], replies[1]))
|
|
239
|
+
module.close()
|
|
240
|
+
for p in (midi_in, midi_out):
|
|
241
|
+
if p is not None:
|
|
242
|
+
p.close()
|
|
243
|
+
if not total:
|
|
244
|
+
print("soundmodule: no MIDI arrived")
|
|
245
|
+
sys.exit(1)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
if __name__ == "__main__":
|
|
249
|
+
main()
|
soundmodule/run.pyi
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 PyDevices
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
"""Run the sound module headless: MIDI in from a port, sound out to a WAV file."""
|
|
5
|
+
|
|
6
|
+
from typing import Any, Callable, Protocol
|
|
7
|
+
|
|
8
|
+
from .engine import Module
|
|
9
|
+
|
|
10
|
+
class _MidiIn(Protocol):
|
|
11
|
+
def readinto(self, buf: bytearray, nbytes: int | None = None) -> int | None: ...
|
|
12
|
+
|
|
13
|
+
_Buf = bytes | bytearray | memoryview
|
|
14
|
+
|
|
15
|
+
RATE: int
|
|
16
|
+
CHANNELS: int
|
|
17
|
+
|
|
18
|
+
def ticks_ms() -> int: ...
|
|
19
|
+
def ticks_diff(a: int, b: int) -> int: ...
|
|
20
|
+
|
|
21
|
+
class Wav:
|
|
22
|
+
"""A 16-bit PCM WAV file written as it goes; `close` fixes the sizes."""
|
|
23
|
+
|
|
24
|
+
f: Any
|
|
25
|
+
rate: int
|
|
26
|
+
channels: int
|
|
27
|
+
bytes: int
|
|
28
|
+
def __init__(self, path: str, rate: int = 48000, channels: int = 2) -> None: ...
|
|
29
|
+
def write(self, data: _Buf) -> None: ...
|
|
30
|
+
def close(self) -> None: ...
|
|
31
|
+
|
|
32
|
+
def serve(
|
|
33
|
+
module: Module,
|
|
34
|
+
midi_in: _MidiIn | None,
|
|
35
|
+
wav: Wav | None = None,
|
|
36
|
+
seconds: float = 600,
|
|
37
|
+
idle: float | None = None,
|
|
38
|
+
wait: float | None = None,
|
|
39
|
+
tail: float = 2.0,
|
|
40
|
+
out: Any = None,
|
|
41
|
+
log: Callable[[str], Any] = ...,
|
|
42
|
+
) -> tuple[int, list[int]]:
|
|
43
|
+
"""Feed `midi_in` to `module` and render its output by the clock into `wav`.
|
|
44
|
+
|
|
45
|
+
Returns the bytes of MIDI and the most the render fell behind in ms, before the first note and after it.
|
|
46
|
+
"""
|
|
47
|
+
def report(module: Module, total: int, worst: list[int], log: Callable[[str], Any] = ...) -> None:
|
|
48
|
+
"""Say what came in and what played."""
|
|
49
|
+
def main(argv: list[str] | None = None) -> None: ...
|
spectrum/__init__.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Brad Barnett
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
"""spectrum -- the spectrum analyzer in an app's area,
|
|
5
|
+
sharing the panel with LVGL.
|
|
6
|
+
|
|
7
|
+
The analyzer draws straight into the panel's framebuffer, so it gets the
|
|
8
|
+
rows LVGL leaves alone: an app puts nothing on ``scope.root`` where the
|
|
9
|
+
meter is. The analyzer's modules are in this package beside this file.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
def meter(scope, source, top, x=0, width=None, height=None, bands=None, report=False):
|
|
13
|
+
"""A ``Spectrum`` (not started) in *scope*'s area, from its row *top* to
|
|
14
|
+
the bottom, or the rectangle *x*, *top*, *width*, *height* there."""
|
|
15
|
+
from .analyzer import Spectrum
|
|
16
|
+
from board_config import display_drv
|
|
17
|
+
|
|
18
|
+
rx, ry, rw, rh = scope.rect
|
|
19
|
+
return Spectrum(
|
|
20
|
+
display_drv,
|
|
21
|
+
source,
|
|
22
|
+
height=height or rh - top,
|
|
23
|
+
y=ry + top,
|
|
24
|
+
x=rx + x,
|
|
25
|
+
width=width,
|
|
26
|
+
bands=bands,
|
|
27
|
+
report=report,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def pump_tap(rate, channels):
|
|
32
|
+
"""A level source for whatever the audio pump plays (a push stream too)."""
|
|
33
|
+
|
|
34
|
+
def source(bands):
|
|
35
|
+
from .pump_levels import TapLevels
|
|
36
|
+
|
|
37
|
+
return TapLevels(bands, rate=rate, channels=channels)
|
|
38
|
+
|
|
39
|
+
return source
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def start(m, scope, above=()):
|
|
43
|
+
"""Start *m* on *scope*'s timer without clearing the rest of the panel.
|
|
44
|
+
|
|
45
|
+
``Spectrum.start`` clears the whole panel when the meter is shorter than
|
|
46
|
+
it, which wipes LVGL's widgets above the meter (and LVGL doesn't know to
|
|
47
|
+
redraw them). Hiding ``fill_rect`` for that one call keeps them; the meter
|
|
48
|
+
paints its own rows. *above* are objects to have LVGL redraw anyway.
|
|
49
|
+
"""
|
|
50
|
+
from touchkit import shell
|
|
51
|
+
|
|
52
|
+
d = m.display_drv
|
|
53
|
+
d.fill_rect = None # an instance attribute shadowing the method
|
|
54
|
+
try:
|
|
55
|
+
m.start(scope)
|
|
56
|
+
finally:
|
|
57
|
+
try:
|
|
58
|
+
del d.fill_rect
|
|
59
|
+
except AttributeError:
|
|
60
|
+
pass
|
|
61
|
+
for obj in above:
|
|
62
|
+
obj.invalidate()
|
|
63
|
+
shell.redraw_home_button()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def stop(m):
|
|
67
|
+
if m is None:
|
|
68
|
+
return
|
|
69
|
+
m.stop()
|
|
70
|
+
close = getattr(m.source, "close", None)
|
|
71
|
+
if close is not None:
|
|
72
|
+
close()
|
spectrum/__init__.pyi
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Brad Barnett
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
"""The spectrum analyzer in an app's area, sharing the panel with LVGL."""
|
|
5
|
+
|
|
6
|
+
from typing import Any, Callable, Iterable, Protocol
|
|
7
|
+
|
|
8
|
+
from appkit.scope import AppScope
|
|
9
|
+
|
|
10
|
+
from .analyzer import _LevelSource, Spectrum
|
|
11
|
+
|
|
12
|
+
class _Redrawable(Protocol):
|
|
13
|
+
def invalidate(self) -> Any: ...
|
|
14
|
+
|
|
15
|
+
def meter(
|
|
16
|
+
scope: AppScope,
|
|
17
|
+
source: _LevelSource | Callable[[int], _LevelSource],
|
|
18
|
+
top: int,
|
|
19
|
+
x: int = 0,
|
|
20
|
+
width: int | None = None,
|
|
21
|
+
height: int | None = None,
|
|
22
|
+
bands: int | None = None,
|
|
23
|
+
report: bool = False,
|
|
24
|
+
) -> Spectrum:
|
|
25
|
+
"""A `Spectrum` (not started) in `scope`'s area, from its row `top` to the bottom, or the given rectangle there."""
|
|
26
|
+
def pump_tap(rate: int, channels: int) -> Callable[[int], _LevelSource]:
|
|
27
|
+
"""A level source for whatever the audio pump plays, push streams too."""
|
|
28
|
+
def start(m: Spectrum, scope: AppScope, above: Iterable[_Redrawable] = ()) -> None:
|
|
29
|
+
"""Start `m` on `scope`'s timer without clearing the rest of the panel."""
|
|
30
|
+
def stop(m: Spectrum | None) -> None: ...
|
spectrum/analyzer.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Brad Barnett
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
"""
|
|
6
|
+
analyzer.py -- the spectrum analyzer as a widget any app can put on its screen.
|
|
7
|
+
|
|
8
|
+
``spectrum.py`` is the demo that runs it on fake music. This file is the part
|
|
9
|
+
an app imports to show its own sound::
|
|
10
|
+
|
|
11
|
+
from spectrum.analyzer import Spectrum, levels_for
|
|
12
|
+
|
|
13
|
+
out.play(song) # an audiodev AudioOut
|
|
14
|
+
meter = Spectrum(display_drv, levels_for(out))
|
|
15
|
+
meter.start(app)
|
|
16
|
+
|
|
17
|
+
Importing it opens nothing and starts nothing. ``Spectrum`` takes a display
|
|
18
|
+
driver and a source of levels: any object with ``levels(t)`` and ``bands``,
|
|
19
|
+
or a factory that builds one for a band count (``FakeMusic`` is one, and so
|
|
20
|
+
is what ``levels_for`` returns). It draws on a timer from the app it's
|
|
21
|
+
started on, and only the rows that moved reach the panel.
|
|
22
|
+
|
|
23
|
+
A USB sound card that plays through the pump (usbhost's ``examples/usb_soundcard.py``)
|
|
24
|
+
is metered the same way, by ``pump_levels.TapLevels`` on the pump's tap.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from multimer import ticks_diff, ticks_ms
|
|
28
|
+
from pygraphics import RGB565, FrameBuffer
|
|
29
|
+
from .spectrum_view import SpectrumView, band_count_for
|
|
30
|
+
|
|
31
|
+
try:
|
|
32
|
+
from time import ticks_us
|
|
33
|
+
except ImportError: # CPython
|
|
34
|
+
|
|
35
|
+
def ticks_us():
|
|
36
|
+
return ticks_ms() * 1000
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
FRAME_MS = 16
|
|
40
|
+
REPORT_S = 5
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def levels_for(audio_out):
|
|
44
|
+
"""Levels of whatever an audiodev ``AudioOut`` is playing, for ``Spectrum``.
|
|
45
|
+
|
|
46
|
+
Call it after ``play()``. The meter reads the audio pump's tap and does
|
|
47
|
+
its analysis in C, so Python never touches a sample; that needs the
|
|
48
|
+
output to be playing through the pump (``audio_out.pumped``) on a
|
|
49
|
+
firmware with audiodsp's ``audiometer``. An output playing on the
|
|
50
|
+
interpreter thread raises ``ValueError`` instead.
|
|
51
|
+
"""
|
|
52
|
+
if not getattr(audio_out, "pumped", False):
|
|
53
|
+
raise ValueError(
|
|
54
|
+
"levels_for() needs an AudioOut playing through the audio pump "
|
|
55
|
+
"(audio_out.pumped is False): play() first, on a firmware with "
|
|
56
|
+
"audiodsp's audiopump and audiometer"
|
|
57
|
+
)
|
|
58
|
+
fmt = audio_out.format
|
|
59
|
+
|
|
60
|
+
def tap_levels(bands):
|
|
61
|
+
from .pump_levels import TapLevels
|
|
62
|
+
|
|
63
|
+
return TapLevels(bands, rate=fmt.rate, channels=fmt.channels)
|
|
64
|
+
|
|
65
|
+
return tap_levels
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class Spectrum:
|
|
69
|
+
"""A spectrum analyzer drawn on ``display_drv``, fed by ``source``.
|
|
70
|
+
|
|
71
|
+
Every keyword is optional:
|
|
72
|
+
|
|
73
|
+
- ``bands``: how many bars. Default: half of what ``band_count_for`` gives
|
|
74
|
+
for the panel's width.
|
|
75
|
+
- ``height``: the meter's height in rows. Default: half the panel.
|
|
76
|
+
- ``y``: the meter's top row. Default: the bottom of the panel, and
|
|
77
|
+
``start()`` clears the rest of the panel first. Given, the meter paints
|
|
78
|
+
only its own rows and leaves the rest of the panel to you.
|
|
79
|
+
- ``x`` and ``width``: the meter's left column and width. Default: the
|
|
80
|
+
whole width. A narrower meter paints only its own rectangle, so give
|
|
81
|
+
``y`` too.
|
|
82
|
+
- ``style``: ``"smooth"`` or ``"segmented"``.
|
|
83
|
+
- ``report``: print the frame rate and per-part costs every few seconds.
|
|
84
|
+
|
|
85
|
+
Halving bands and height trades resolution for frame rate under loud
|
|
86
|
+
music: 18-19 fps full size, 35-45 at half by half on the ESP32-P4.
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
def __init__(self, display_drv, source, *, bands=None, height=None, y=None, x=0, width=None,
|
|
90
|
+
style="smooth", report=False):
|
|
91
|
+
self.display_drv = display_drv
|
|
92
|
+
W, H = display_drv.width, display_drv.height
|
|
93
|
+
if height is None:
|
|
94
|
+
height = H // 2
|
|
95
|
+
if width is None:
|
|
96
|
+
width = W - x
|
|
97
|
+
if bands is None:
|
|
98
|
+
bands = band_count_for(width) // 2
|
|
99
|
+
self.x = x
|
|
100
|
+
self.y = H - height if y is None else y
|
|
101
|
+
self._clear_panel = y is None # a placed meter leaves the rest alone
|
|
102
|
+
self.view = SpectrumView(width, height, bands=bands, style=style)
|
|
103
|
+
# A class (FakeMusic) or a factory (levels_for) builds the source for
|
|
104
|
+
# this band count; anything else already is one.
|
|
105
|
+
if isinstance(source, type) or not hasattr(source, "levels"):
|
|
106
|
+
source = source(self.view.bands)
|
|
107
|
+
self.source = source
|
|
108
|
+
self.report = report
|
|
109
|
+
self.last_report = ""
|
|
110
|
+
self.timer = None
|
|
111
|
+
# A panel that needs presenting (the P4's DSI panel samples its
|
|
112
|
+
# framebuffer only when told to) gets just the changed rows presented
|
|
113
|
+
# after each frame, rather than appdev's whole-frame refresh every
|
|
114
|
+
# 33 ms, which costs 22 ms a time on the P4.
|
|
115
|
+
self.present_rows = bool(getattr(display_drv, "needs_refresh", False)) and hasattr(
|
|
116
|
+
getattr(display_drv, "_raw_buffer", None), "refresh_rect"
|
|
117
|
+
)
|
|
118
|
+
# Any other display that needs presenting (a desktop window) is shown
|
|
119
|
+
# whole after each frame: an app that leaves presenting to LVGL has
|
|
120
|
+
# stopped appdev's refresh, so the bars would show only when LVGL
|
|
121
|
+
# next drew something.
|
|
122
|
+
self.present_all = bool(getattr(display_drv, "needs_refresh", False)) and not self.present_rows
|
|
123
|
+
self._send = self._panel_blit()
|
|
124
|
+
self._dirty = [0, 0] # rows touched this frame, top and bottom
|
|
125
|
+
self._stats = [0, 0, 0, 0, 0] # frames, data us, update us, draw us, report start
|
|
126
|
+
self._t0 = self._last = 0
|
|
127
|
+
|
|
128
|
+
def _panel_blit(self):
|
|
129
|
+
"""How a run of bar rows reaches the panel.
|
|
130
|
+
|
|
131
|
+
Where the driver shares a packed framebuffer that has to be presented
|
|
132
|
+
(the P4's DSI panel), rows are copied straight into it with no cache
|
|
133
|
+
sync, and the frame's dirty band is synced and presented once, after
|
|
134
|
+
the bars. The panel's own ``blit`` syncs the cache for every call,
|
|
135
|
+
and a cache sync runs with interrupts off: forty-odd of them a frame
|
|
136
|
+
kept the USB interrupt waiting long enough to lose sound-card
|
|
137
|
+
packets. Otherwise, the driver's ``blit_rect``."""
|
|
138
|
+
d = self.display_drv
|
|
139
|
+
if self.present_rows and getattr(d, "share_framebuffer", False):
|
|
140
|
+
buf, _, n, stride = d.framebuffers()
|
|
141
|
+
w, h = d.width, d.height
|
|
142
|
+
if n == w * h * 2 and stride == w * 2:
|
|
143
|
+
return FrameBuffer(buf, w, h, RGB565).blit_rect
|
|
144
|
+
return d.blit_rect
|
|
145
|
+
|
|
146
|
+
def _blit(self, buf, x, y, w, h):
|
|
147
|
+
x += self.x
|
|
148
|
+
y += self.y
|
|
149
|
+
self._send(buf, x, y, w, h)
|
|
150
|
+
d = self._dirty
|
|
151
|
+
if y < d[0]:
|
|
152
|
+
d[0] = y
|
|
153
|
+
if y + h > d[1]:
|
|
154
|
+
d[1] = y + h
|
|
155
|
+
|
|
156
|
+
def start(self, app, period_ms=FRAME_MS):
|
|
157
|
+
"""Paint the meter's background and start drawing from ``app``'s timer.
|
|
158
|
+
|
|
159
|
+
A meter placed with ``y=`` paints only its own rows; one at the
|
|
160
|
+
default place clears the whole panel first.
|
|
161
|
+
"""
|
|
162
|
+
d, view = self.display_drv, self.view
|
|
163
|
+
fill = getattr(d, "fill_rect", None)
|
|
164
|
+
if fill is not None and self._clear_panel and view.height < d.height:
|
|
165
|
+
fill(0, 0, d.width, d.height, 0) # clear whatever the panel showed before
|
|
166
|
+
d.blit_rect(view.strip(0, view.height), self.x, self.y, view.width, view.height)
|
|
167
|
+
if self.present_rows:
|
|
168
|
+
d.show()
|
|
169
|
+
view._build_bar_columns() # a second on the P4; not on the first frame
|
|
170
|
+
self._t0 = self._last = ticks_ms()
|
|
171
|
+
self._stats = [0, 0, 0, 0, self._t0]
|
|
172
|
+
self.timer = app.every(self.tick, period=period_ms)
|
|
173
|
+
return self
|
|
174
|
+
|
|
175
|
+
def stop(self):
|
|
176
|
+
"""Stop drawing; the last frame stays on the panel."""
|
|
177
|
+
if self.timer is not None:
|
|
178
|
+
self.timer.deinit()
|
|
179
|
+
self.timer = None
|
|
180
|
+
|
|
181
|
+
def tick(self, _=None):
|
|
182
|
+
"""Draw one frame. ``start`` calls this from a timer."""
|
|
183
|
+
now = ticks_ms()
|
|
184
|
+
dt = ticks_diff(now, self._last) / 1000
|
|
185
|
+
self._last = now
|
|
186
|
+
a = ticks_us()
|
|
187
|
+
levels = self.source.levels(ticks_diff(now, self._t0) / 1000)
|
|
188
|
+
b = ticks_us()
|
|
189
|
+
view = self.view
|
|
190
|
+
view.update(levels, min(dt, 0.1))
|
|
191
|
+
c = ticks_us()
|
|
192
|
+
dirty = self._dirty
|
|
193
|
+
dirty[0], dirty[1] = self.y + view.height, 0
|
|
194
|
+
view.render_columns(self._blit)
|
|
195
|
+
if dirty[1] > dirty[0]:
|
|
196
|
+
if self.present_rows:
|
|
197
|
+
self.display_drv.flush_rect(self.x, dirty[0], view.width, dirty[1] - dirty[0])
|
|
198
|
+
elif self.present_all:
|
|
199
|
+
self.display_drv.show()
|
|
200
|
+
if not self.report:
|
|
201
|
+
return
|
|
202
|
+
d = ticks_us()
|
|
203
|
+
s = self._stats
|
|
204
|
+
s[0] += 1
|
|
205
|
+
s[1] += b - a
|
|
206
|
+
s[2] += c - b
|
|
207
|
+
s[3] += d - c
|
|
208
|
+
span = ticks_diff(now, s[4])
|
|
209
|
+
if span >= REPORT_S * 1000:
|
|
210
|
+
n = s[0]
|
|
211
|
+
self.last_report = "{:.1f} fps; per frame: data {:.2f} ms, update {:.2f} ms, draw+send {:.2f} ms".format(
|
|
212
|
+
n * 1000 / span, s[1] / n / 1000, s[2] / n / 1000, s[3] / n / 1000
|
|
213
|
+
)
|
|
214
|
+
print(self.last_report)
|
|
215
|
+
s[0] = s[1] = s[2] = s[3] = 0
|
|
216
|
+
s[4] = now
|
|
217
|
+
|
|
218
|
+
def capture(self, path):
|
|
219
|
+
"""Write the meter's rows on screen to ``path`` as raw little-endian
|
|
220
|
+
RGB565: from the panel's own framebuffer when the driver shares it,
|
|
221
|
+
else a rebuild."""
|
|
222
|
+
d, view = self.display_drv, self.view
|
|
223
|
+
frame = None
|
|
224
|
+
fbs = getattr(d, "framebuffers", None)
|
|
225
|
+
if fbs is not None and getattr(d, "share_framebuffer", False):
|
|
226
|
+
buf, _, n, stride = fbs()
|
|
227
|
+
if stride == view.width * 2 and n >= (self.y + view.height) * stride:
|
|
228
|
+
frame = memoryview(buf)[self.y * stride : (self.y + view.height) * stride]
|
|
229
|
+
with open(path, "wb") as f:
|
|
230
|
+
f.write(frame if frame is not None else view.compose())
|
|
231
|
+
return view.width, view.height
|