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 @@
1
+ {"name": "midiengine", "title": "midiEngine", "category": "Audio", "icon": "library_music", "color": "#8C1E4E"}
@@ -0,0 +1,85 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Which SoundFonts the midiEngine can play: ``$SOUNDFONT`` alone when it
5
+ is set, else every ``.sf2`` in the folders below, each folder's in name
6
+ order. On a desktop the folder is ``~/soundfonts``
7
+ (``%USERPROFILE%\\soundfonts`` on Windows); on a board ``/sd/soundfonts``
8
+ (the card, mounted while the app is open), then ``/soundfonts`` on flash,
9
+ then ``/data/soundfonts`` (`appkit.places`). With more than one, the app
10
+ asks which.
11
+
12
+ No LVGL here, so the contract runs it on CPython and MicroPython alike.
13
+ """
14
+
15
+ import os
16
+ import sys
17
+
18
+ #: A computer rather than a board: CPython, or MicroPython on a desktop
19
+ #: operating system (micropython.exe, the unix port); appkit.data's test.
20
+ DESKTOP = sys.implementation.name == "cpython" or sys.platform in (
21
+ "linux", "darwin", "win32", "cygwin", "freebsd", "openbsd", "netbsd")
22
+ SOUNDFONTS = "soundfonts" # the folder name, on the card, flash and the data root
23
+
24
+
25
+ def getenv(name):
26
+ fn = getattr(os, "getenv", None)
27
+ return fn(name) if fn is not None else None
28
+
29
+
30
+ def home():
31
+ """A desktop user's folder, with forward slashes (``%USERPROFILE%``,
32
+ else ``$HOME``): ``os.path.expanduser`` isn't in MicroPython."""
33
+ return (getenv("USERPROFILE") or getenv("HOME") or "").replace("\\", "/")
34
+
35
+
36
+ def folders(desktop):
37
+ """Where to look, in order."""
38
+ if desktop:
39
+ return [home() + "/soundfonts"]
40
+ from appkit import places # a board's only: the contract runs the desktop side without appkit
41
+
42
+ return places.folders(SOUNDFONTS)
43
+
44
+
45
+ def where_text():
46
+ """A board's SoundFont folders, for a message."""
47
+ from appkit import places
48
+
49
+ return places.where_text(SOUNDFONTS)
50
+
51
+
52
+ def size_of(path):
53
+ try:
54
+ return os.stat(path)[6]
55
+ except OSError:
56
+ return None
57
+
58
+
59
+ def candidates(where, env=None):
60
+ """``[(path, bytes)]``: ``[env]`` alone when it is set (asked for by
61
+ name, so never a choice), else every ``.sf2`` in the folders *where*.
62
+ A folder that isn't there is skipped; bytes is None when the file
63
+ can't be read."""
64
+ if env:
65
+ return [(env, size_of(env))]
66
+ found = []
67
+ for folder in where:
68
+ try:
69
+ names = sorted(n for n in os.listdir(folder) if n.lower().endswith(".sf2"))
70
+ except OSError:
71
+ continue
72
+ for n in names:
73
+ path = folder + "/" + n
74
+ found.append((path, size_of(path)))
75
+ return found
76
+
77
+
78
+ def name_of(path):
79
+ return str(path).replace("\\", "/").rsplit("/", 1)[-1]
80
+
81
+
82
+ def mb_text(size):
83
+ if size is None:
84
+ return "?"
85
+ return "%.1f MB" % (size / 1048576)
@@ -0,0 +1,165 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """What the apps that play say about the MIDI devices in the hub.
5
+
6
+ Instruments and the midiEngine hear every USB MIDI device at once, through
7
+ ``midiports.usb_host.all_ports()``; on a computer or in a browser page,
8
+ the MIDI inputs chosen in Connections, or every input until some are. `Watch` names the ones open now,
9
+ for the status line, and notices when one comes or goes.
10
+ `ble_available` says whether a board can take Bluetooth MIDI too.
11
+ """
12
+
13
+ import sys
14
+
15
+ #: The platforms that are a browser page, whose MIDI inputs are Web MIDI's.
16
+ BROWSERS = ("webassembly", "emscripten")
17
+
18
+
19
+ def ble_available():
20
+ """True on a board whose firmware has Bluetooth LE, as
21
+ ``midiports.ble.available()`` says, without importing the port: that
22
+ waits until the player turns it on. Starts nothing."""
23
+ if sys.implementation.name not in ("micropython", "circuitpython"):
24
+ return False
25
+ if sys.platform in ("webassembly", "emscripten"):
26
+ return False
27
+ for mod in ("bluetooth", "_bleio"):
28
+ try:
29
+ __import__(mod)
30
+ return True
31
+ except ImportError:
32
+ pass
33
+ return False
34
+
35
+
36
+ def ble_text(port):
37
+ """The status line for a Bluetooth MIDI input."""
38
+ if port.state == "connected":
39
+ return "MIDI: Bluetooth"
40
+ return "Bluetooth MIDI: waiting as %s" % (port.name,)
41
+
42
+
43
+ def name(dev):
44
+ """A device's product string, or its vid:pid when it has none."""
45
+ try:
46
+ product = dev.product
47
+ except Exception: # a device that won't answer a string request
48
+ product = None
49
+ return product or "%04x:%04x" % (dev.idVendor, dev.idProduct)
50
+
51
+
52
+ class Watch:
53
+ """The status line for a merged port's devices, worked out only when
54
+ they change."""
55
+
56
+ def __init__(self):
57
+ self._devices = []
58
+ self.text = None
59
+
60
+ def changed(self, port):
61
+ """True when the devices differ from the last call; ``text`` is then
62
+ what to show, None when there are none."""
63
+ devices = port.devices
64
+ if devices == self._devices:
65
+ return False
66
+ self._devices = list(devices)
67
+ if not devices:
68
+ self.text = None
69
+ else:
70
+ self.text = "MIDI: " + " + ".join(name(d) for d in devices)
71
+ return True
72
+
73
+
74
+ class Merged:
75
+ """Every MIDI input a desktop has, read as one port, the way the hub's
76
+ merged port reads: ``any()``, ``read()``, ``close()``."""
77
+
78
+ def __init__(self, ports):
79
+ self.ports = ports
80
+
81
+ def any(self):
82
+ return sum(p.any() for p in self.ports)
83
+
84
+ def read(self):
85
+ data = b""
86
+ for p in self.ports:
87
+ if p.any():
88
+ data += p.read()
89
+ return data
90
+
91
+ def close(self):
92
+ for p in self.ports:
93
+ p.close()
94
+
95
+
96
+ def open_chosen():
97
+ """``(port, names)`` of the inputs chosen for ``midi.in`` (the connections
98
+ picker, or ``endpointkit.select``), read as one port through
99
+ ``midiports.endpoints``, which opened them; None when none is chosen, or
100
+ endpointkit or the computer's MIDI ports aren't registered."""
101
+ try:
102
+ import endpointkit
103
+ from midiports import endpoints
104
+ except ImportError:
105
+ return None
106
+ try:
107
+ port = endpoints.merged_in()
108
+ except KeyError: # the computer's MIDI ports aren't registered
109
+ return None
110
+ # A browser's port reads the page's Web MIDI ports and the other tabs.
111
+ mine = getattr(port, "providers", (port.provider,))
112
+ chosen = [ep for ep in endpointkit.selected("midi.in") if ep.provider in mine]
113
+ if not chosen:
114
+ return None
115
+ return port, " + ".join(ep.label for ep in chosen)
116
+
117
+
118
+ def open_desktop():
119
+ """``(port, names)`` of a desktop's MIDI inputs: the ones chosen for
120
+ ``midi.in`` when there are any (`open_chosen`), else all of them, since
121
+ the first is as likely a software synth's as a keyboard's; None when it
122
+ has none (or no ``midiports`` backend). The port reads like the merged
123
+ hub port: ``any()``, ``read()``, ``close()``. A browser page is the
124
+ same, with every input Web MIDI offers and every other tab of the page
125
+ until some are chosen."""
126
+ found = open_chosen()
127
+ if found is not None:
128
+ return found
129
+ if sys.platform in BROWSERS:
130
+ try:
131
+ from midiports import webmidi
132
+ except ImportError:
133
+ return None
134
+ ports = [webmidi.page_in()]
135
+ try:
136
+ from midiports import tabs
137
+ except ImportError: # a midiports from before the tabs
138
+ return Merged(ports), "Web MIDI"
139
+ ports.append(tabs.page_in())
140
+ return Merged(ports), "Web MIDI and other tabs"
141
+ if sys.platform.startswith("win"):
142
+ from midiports import windows as mp
143
+ elif sys.platform.startswith("linux"):
144
+ from midiports import linux as mp
145
+ else:
146
+ return None
147
+ import midiports
148
+
149
+ ports = []
150
+ names = []
151
+ for info in mp.available():
152
+ if info.direction not in (midiports.IN, midiports.INOUT):
153
+ continue
154
+ try:
155
+ midi_in, midi_out = mp.ports(info.name)
156
+ except OSError: # another program has it open
157
+ continue
158
+ if midi_out is not None:
159
+ midi_out.close()
160
+ if midi_in is not None:
161
+ ports.append(midi_in)
162
+ names.append(info.name)
163
+ if not ports:
164
+ return None
165
+ return Merged(ports), " + ".join(names)
@@ -0,0 +1,392 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """The midiEngine's MIDI file player: a library of .mid files, played
5
+ into whatever takes raw MIDI bytes (``gm.Module.feed``).
6
+
7
+ The library is a folder, or several read one after another (a board's
8
+ card, flash and data root). With a ``catalog.json`` at a folder's root (``{"version":
9
+ 1, "files": [{"path": "Classical/Pachelbel - Canon in D.mid", "title":
10
+ "Canon in D", "composer": "Johann Pachelbel", "genre": "Classical",
11
+ "seconds": 245, ...}, ...]}``) each piece has a title, a composer, a genre
12
+ and a length, in the catalog's order. Without one the folder is scanned,
13
+ subfolders and all, in path order: the title is the file's name, the genre
14
+ the subfolder it sits in. ``entries`` are the pieces, ``files`` their paths
15
+ relative to their folder, ``genres()`` the genres with their counts.
16
+
17
+ ``Player`` parses a file with ``umidiparser``, streaming each track
18
+ through a small buffer, and releases every channel message and SysEx at
19
+ its time: ``service()`` is called from a timer every few milliseconds,
20
+ compares the clock with the next event's due time (the sum of the
21
+ parser's ``delta_us``, which already follows the file's tempo changes)
22
+ and feeds what is due, for at most ``budget_ms`` a call, the rest on the
23
+ next. No sleeping, so the UI thread stays free, and
24
+ due times are measured from the start of the file, so nothing drifts.
25
+ ``play()`` feeds nothing itself: it is called from a tap, and the first
26
+ events make the parts, so they go on the next ``service()``.
27
+
28
+ ``stop()`` sends All Notes Off on all sixteen channels through the same
29
+ path. At the end of a file the player repeats it when ``loop`` is set,
30
+ else goes on to the next, wrapping at the last. ``next()`` and ``prev()``
31
+ wrap too, and all three stay within the current piece's genre when
32
+ ``scope`` is ``GENRE`` rather than ``ALL``. With no folder, or no .mid
33
+ file in it, ``message`` says where to put them.
34
+
35
+ No LVGL here, and the clock is injectable, so a test can run it on
36
+ CPython or MicroPython with a fake sink and a fake clock.
37
+ """
38
+
39
+
40
+ def _umidiparser_without_native():
41
+ """umidiparser compiled without its ``@micropython.native`` lines, for a
42
+ MicroPython built with no native emitter (the Windows port's omnipython
43
+ variant raises SyntaxError at the first decorator). The same code, run
44
+ as bytecode; a board never comes here."""
45
+ import sys
46
+
47
+ here = __file__.replace("\\", "/")
48
+ path = here[: here.rfind("/") + 1] + "umidiparser.py"
49
+ # All at once: MicroPython reads a file's lines a byte per system call,
50
+ # which took 15 s over a network drive.
51
+ with open(path) as f:
52
+ src = f.read().replace("@micropython.native", "")
53
+ names = {"__name__": "umidiparser"}
54
+ exec(compile(src, path, "exec"), names)
55
+
56
+ class Module: # MicroPython can't make a module object: this holds the names
57
+ pass
58
+
59
+ mod = Module()
60
+ for key in names:
61
+ setattr(mod, key, names[key])
62
+ sys.modules["umidiparser"] = mod
63
+ return mod
64
+
65
+
66
+ try:
67
+ from . import umidiparser
68
+ except SyntaxError: # no native emitter in this interpreter
69
+ umidiparser = _umidiparser_without_native()
70
+ except ImportError: # a test with the app's folder on sys.path
71
+ import umidiparser
72
+
73
+ try:
74
+ from multimer import ticks_diff, ticks_ms
75
+ except ImportError:
76
+ try:
77
+ from time import ticks_diff, ticks_ms # MicroPython without multimer
78
+ except ImportError:
79
+ import time
80
+
81
+ def ticks_ms():
82
+ return int(time.monotonic() * 1000)
83
+
84
+ def ticks_diff(a, b):
85
+ return a - b
86
+
87
+ import os
88
+
89
+ EXT = ".mid"
90
+ CATALOG = "catalog.json"
91
+ BUFFER = 256 # bytes read from the file per track at a time
92
+ BUDGET_MS = 20 # the most one service() call feeds for; what is left goes on the next
93
+ CC_ALL_NOTES_OFF = 123
94
+ ALL = "all" # scope: next and prev walk the whole library
95
+ GENRE = "genre" # scope: they stay in the current piece's genre
96
+ DIR_MODE = 0x4000 # S_IFDIR, in os.stat's mode on every interpreter
97
+
98
+
99
+ def _entry(path, title=None, composer="", genre=None, seconds=0):
100
+ """One piece: what the face shows and what the player plays."""
101
+ name = path.rsplit("/", 1)[-1]
102
+ if name.lower().endswith(EXT):
103
+ name = name[:-len(EXT)]
104
+ if genre is None:
105
+ genre = path.rsplit("/", 1)[0] if "/" in path else ""
106
+ return {"path": path, "title": title or name, "composer": composer or "", "genre": genre or "",
107
+ "seconds": int(seconds or 0)}
108
+
109
+
110
+ def _is_dir(path):
111
+ try:
112
+ return bool(os.stat(path)[0] & DIR_MODE)
113
+ except OSError:
114
+ return False
115
+
116
+
117
+ def _walk(folder, prefix=""):
118
+ """The .mid files under ``folder``, as paths relative to it, in path order."""
119
+ found = []
120
+ for name in sorted(os.listdir(folder)):
121
+ full = folder + "/" + name
122
+ rel = prefix + name
123
+ if _is_dir(full):
124
+ found.extend(_walk(full, rel + "/"))
125
+ elif name.lower().endswith(EXT):
126
+ found.append(rel)
127
+ return found
128
+
129
+
130
+ class Player:
131
+ def __init__(self, folder, sink, now=ticks_ms, loop=False, buffer_size=BUFFER, scope=ALL,
132
+ budget_ms=BUDGET_MS):
133
+ self.folders = [folder] if isinstance(folder, str) else list(folder)
134
+ self.folder = " or ".join(self.folders) # for messages
135
+ self.budget_ms = budget_ms # of real time, whatever clock ``now`` is
136
+ self.sink = sink
137
+ self.now = now
138
+ self.loop = loop
139
+ self.scope = scope
140
+ self.buffer_size = buffer_size
141
+ self.entries = [] # the pieces, each as _entry() makes it
142
+ self.files = [] # their paths, relative to their folder, in the same order
143
+ self.catalog = False # True when a catalog.json described the library
144
+ self.message = None # why there is nothing to play, else None
145
+ self.index = 0
146
+ self.playing = False
147
+ self.length_ms = 0
148
+ self._events = None
149
+ self._pending = None # (due_us, bytes), (due_us, None) at the end
150
+ self._due_us = 0
151
+ self._started = 0
152
+ self.scan()
153
+
154
+ # -- the folder -----------------------------------------------------------------
155
+
156
+ def scan(self):
157
+ """Read the library again (the catalog, else the folder); the
158
+ current file keeps playing, and stays the current one if it is
159
+ still there."""
160
+ current = self._where(self.index) if self.files else None
161
+ entries = []
162
+ self.catalog = False
163
+ folders = 0 # how many of the folders are there
164
+ for root in self.folders:
165
+ try:
166
+ found = self._read_catalog(root)
167
+ except OSError as e: # a catalog that isn't JSON: say so, play nothing
168
+ self.entries, self.files = [], []
169
+ self.message = str(e)
170
+ return
171
+ if found is None:
172
+ try:
173
+ found = [_entry(p) for p in _walk(root)]
174
+ except OSError:
175
+ continue
176
+ else:
177
+ self.catalog = True
178
+ folders += 1
179
+ for e in found:
180
+ e["root"] = root
181
+ entries.extend(found)
182
+ if not folders:
183
+ self.entries, self.files = [], []
184
+ self.message = "No MIDI folder %s. Make it and put .mid files in it." % (self.folder,)
185
+ return
186
+ self.entries = entries
187
+ self.files = [e["path"] for e in entries]
188
+ self.message = None if self.files else "No .mid files in %s. Put some there." % (self.folder,)
189
+ where = [self._where(i) for i in range(len(entries))]
190
+ if current in where:
191
+ self.index = where.index(current)
192
+ elif self.files:
193
+ self.index %= len(self.files)
194
+
195
+ def _where(self, i):
196
+ e = self.entries[i % len(self.entries)]
197
+ return e["root"] + "/" + e["path"]
198
+
199
+ def _read_catalog(self, root):
200
+ """The catalog's entries, or None when there is no catalog.json."""
201
+ try:
202
+ # bytes, decoded as UTF-8: a desktop's text mode would use its
203
+ # locale's codepage (cp1252 on Windows) and fail on the titles
204
+ with open(root + "/" + CATALOG, "rb") as f:
205
+ import json
206
+
207
+ data = json.loads(f.read().decode("utf-8"))
208
+ except OSError:
209
+ return None
210
+ except ValueError as e:
211
+ raise OSError("%s/%s is not JSON: %s" % (root, CATALOG, e))
212
+ entries = []
213
+ for item in data.get("files", ()):
214
+ path = item.get("path")
215
+ if path and path.lower().endswith(EXT):
216
+ entries.append(_entry(path, item.get("title"), item.get("composer"), item.get("genre"),
217
+ item.get("seconds")))
218
+ return entries
219
+
220
+ @property
221
+ def entry(self):
222
+ """The current piece, or an empty one."""
223
+ if not self.entries:
224
+ return _entry("")
225
+ return self.entries[self.index % len(self.entries)]
226
+
227
+ @property
228
+ def name(self):
229
+ """The current file's name without its extension, or ''."""
230
+ if not self.files:
231
+ return ""
232
+ name = self.files[self.index % len(self.files)].rsplit("/", 1)[-1]
233
+ return name[:-len(EXT)]
234
+
235
+ @property
236
+ def title(self):
237
+ return self.entry["title"]
238
+
239
+ @property
240
+ def composer(self):
241
+ return self.entry["composer"]
242
+
243
+ @property
244
+ def genre(self):
245
+ return self.entry["genre"]
246
+
247
+ def genres(self):
248
+ """``[(genre, count), ...]`` in name order; a genre of "" (files at
249
+ the library's root) comes last."""
250
+ counts = {}
251
+ for e in self.entries:
252
+ counts[e["genre"]] = counts.get(e["genre"], 0) + 1
253
+ return sorted(counts.items(), key=lambda kv: (kv[0] == "", kv[0]))
254
+
255
+ def indices(self, genre=None):
256
+ """The indices of the pieces in ``genre``, or of all of them."""
257
+ if genre is None:
258
+ return list(range(len(self.entries)))
259
+ return [i for i, e in enumerate(self.entries) if e["genre"] == genre]
260
+
261
+ def step(self, d):
262
+ """The index ``d`` pieces on from the current one, wrapping, within
263
+ the current genre when the scope is GENRE."""
264
+ if not self.files:
265
+ return 0
266
+ if self.scope == GENRE:
267
+ siblings = self.indices(self.genre)
268
+ at = siblings.index(self.index % len(self.files))
269
+ return siblings[(at + d) % len(siblings)]
270
+ return (self.index + d) % len(self.files)
271
+
272
+ def path(self, i=None):
273
+ i = self.index if i is None else i
274
+ return self._where(i)
275
+
276
+ # -- transport ------------------------------------------------------------------
277
+
278
+ def play(self, i=None):
279
+ """Play file ``i`` (wrapping; default the current one) from its start."""
280
+ if not self.files:
281
+ return False
282
+ if i is not None:
283
+ self.index = i % len(self.files)
284
+ if self.playing:
285
+ self._silence()
286
+ f = umidiparser.MidiFile(self.path(), buffer_size=self.buffer_size, reuse_event_object=True)
287
+ # The catalog's length when it has one: working it out reads the whole
288
+ # file a second time, on the thread that also feeds the audio, and a
289
+ # dense piece takes long enough to empty the output's lookahead.
290
+ seconds = self.entry["seconds"]
291
+ self.length_ms = seconds * 1000 if seconds else f.length_us() // 1000
292
+ self._events = iter(f)
293
+ self._due_us = 0
294
+ self._pending = None
295
+ self._started = self.now()
296
+ self.playing = True
297
+ self._advance()
298
+ # Nothing is fed here. The first program changes and notes make
299
+ # parts and read samples, and play() is called from a tap: the
300
+ # next service() releases what is due at time 0, on the timer.
301
+ return True
302
+
303
+ def stop(self):
304
+ """Stop, and release every note on every channel."""
305
+ if self.playing:
306
+ self._silence()
307
+ self.playing = False
308
+ self._events = None
309
+ self._pending = None
310
+
311
+ def toggle(self):
312
+ if self.playing:
313
+ self.stop()
314
+ else:
315
+ self.play()
316
+
317
+ def next(self):
318
+ return self.play(self.step(1))
319
+
320
+ def prev(self):
321
+ return self.play(self.step(-1))
322
+
323
+ @property
324
+ def elapsed_ms(self):
325
+ if not self.playing:
326
+ return 0
327
+ return min(ticks_diff(self.now(), self._started), self.length_ms)
328
+
329
+ # -- the events -----------------------------------------------------------------
330
+
331
+ def service(self):
332
+ """Feed the events that are due; the number fed. Call it every few ms.
333
+
334
+ A call feeds for at most ``budget_ms`` and leaves the rest, already
335
+ due, to the next: a note that reads a sample from the card can take
336
+ tens of milliseconds, and a backlog fed in one go would hold the
337
+ timer, the screen and the REPL for seconds."""
338
+ if not self.playing:
339
+ return 0
340
+ began = ticks_ms()
341
+ elapsed = ticks_diff(self.now(), self._started)
342
+ n = 0
343
+ ended = False
344
+ while self._pending is not None and self._pending[0] // 1000 <= elapsed:
345
+ due, data = self._pending
346
+ if data is None: # the end of the file, at its time
347
+ if ended: # a second end in one call: a file with no length, looping
348
+ return n
349
+ ended = True
350
+ self._ended()
351
+ if not self.playing:
352
+ return n
353
+ elapsed = ticks_diff(self.now(), self._started) # the next one's start is due now
354
+ continue
355
+ self.sink(data)
356
+ n += 1
357
+ self._advance()
358
+ if ticks_diff(ticks_ms(), began) >= self.budget_ms:
359
+ break
360
+ return n
361
+
362
+ def _advance(self):
363
+ """The next event worth sending into ``_pending``: a channel message
364
+ or a SysEx with its due time, or the end of track with its."""
365
+ events = self._events
366
+ while True:
367
+ try:
368
+ ev = next(events)
369
+ except StopIteration:
370
+ self._pending = (self._due_us, None)
371
+ return
372
+ self._due_us += ev.delta_us
373
+ status = ev.status
374
+ if ev.is_channel() or status == umidiparser.SYSEX:
375
+ self._pending = (self._due_us, ev.to_midi())
376
+ return
377
+ if status == umidiparser.END_OF_TRACK:
378
+ self._pending = (self._due_us, None)
379
+ return
380
+ # Meta events (the parser has already applied the tempo) and escapes.
381
+
382
+ def _ended(self):
383
+ if self._due_us == 0: # a file with nothing in it: don't chase the next one
384
+ self.stop()
385
+ elif self.loop:
386
+ self.play()
387
+ else:
388
+ self.play(self.step(1))
389
+
390
+ def _silence(self):
391
+ for ch in range(16):
392
+ self.sink(bytes((0xB0 | ch, CC_ALL_NOTES_OFF, 0)))