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,1069 @@
1
+ # SPDX-FileCopyrightText: 2026 Brad Barnett
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """The app: an instrument's control panel, opened straight away.
5
+
6
+ The last instrument played opens at the start, created at the output's rate
7
+ and playing through the board's audio out. The drop-down in the panel's title
8
+ bar picks another, and so do a keyboard's Stop and Play buttons; Rewind and
9
+ Fast Forward step through the patches. While the panel is up, MIDI from every
10
+ keyboard the program can reach plays it, and the line under the name shows
11
+ what rendering it costs. Pads on MIDI channel 10 play a drum kit one sound per
12
+ pad, and everything else plays its General MIDI notes.
13
+
14
+ MIDI channel 1 always has an instrument. The small drop-down beside the
15
+ instrument's picks another channel to show, and an instrument chosen while it
16
+ shows becomes that channel's own. A channel without one plays channel 1's.
17
+ """
18
+
19
+ import sys
20
+
21
+ import lvgl as lv
22
+
23
+ from . import midi as _midi
24
+ from . import pads as _pads
25
+ from .catalog import DEFAULT, RENAMED, catalog, find
26
+ from .meters import TICK_MS as METER_MS
27
+ from .meters import Meters
28
+ from .parts import CHANNELS, Mix, Part
29
+
30
+ #: How often the keyboards are read, and the instrument told to take in
31
+ #: what was played, in milliseconds.
32
+ MIDI_MS = 4
33
+ FILL_MS = 10
34
+ #: Every so many fills the app checks what the pump's render costs.
35
+ GOVERN_EVERY = 5
36
+ #: The share of a block's time the voices may take before the app caps them.
37
+ BUDGET = 0.85
38
+ #: Reads to skip after changing the cap, while the stolen voices ring out.
39
+ SETTLE = 4
40
+ #: How often the load readout and the MIDI device names are refreshed.
41
+ STATUS_MS = 500
42
+ #: How often the load is printed to the console while an instrument
43
+ #: plays, for a log of a bench session; 0 prints nothing.
44
+ LOG_MS = 5000
45
+ #: How long a pad's note sounds when there's no keyboard.
46
+ PAD_NOTE_MS = 300
47
+ #: The controllers that move the first twelve macros: what a Donner DMK-25
48
+ #: PRO's four knobs send across its banks A, B and C.
49
+ KNOB_CCS = (30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41)
50
+ #: The controllers that also move the first eight macros: Sound Controllers
51
+ #: 1 to 8 in the MIDI spec, which many keyboards' knobs send. Any other
52
+ #: controller goes to the instrument itself.
53
+ SOUND_CCS = (70, 71, 72, 73, 74, 75, 76, 77)
54
+ #: Channel volume on MIDI channel 1 is the output's volume: slider S1 on a
55
+ #: DMK-25 PRO. Its other sliders send it on other channels.
56
+ VOLUME_CC = 7
57
+ #: A DMK-25 PRO's Rewind and Fast Forward buttons step through the patches,
58
+ #: and its Stop and Play buttons through the instruments.
59
+ PATCH_CCS = {16: -1, 17: 1}
60
+ INSTRUMENT_CCS = {18: -1, 19: 1}
61
+ #: MIDI channel 10, counted from 0: where a keyboard's pads send.
62
+ PAD_CHANNEL = 9
63
+ #: How long to wait for a USB keyboard before opening the first instrument,
64
+ #: whose pads play notes if there isn't one.
65
+ KEYBOARD_WAIT_MS = 10000
66
+ KEYBOARD_POLL_MS = 100
67
+
68
+ BG = 0x141518
69
+ PANEL = 0x24262B
70
+ TEXT = 0xE8E6E1
71
+ DIM = 0x8A8D93
72
+ ACCENT = 0xD8402F
73
+ MENU_W = 260
74
+ MENU_H = 36
75
+ #: The channel drop-down under the instrument's, on an 800 wide panel.
76
+ CHANNEL_W = 86
77
+ CHANNEL_H = 28
78
+ CHANNEL_INSET = 28
79
+ #: On a compact panel it takes this much of the instrument menu's width, and
80
+ #: shows the channel's number alone.
81
+ CHANNEL_COMPACT_W = 40
82
+ #: The instrument menu's first entry on any channel but the first.
83
+ FOLLOW = "Same as Ch 1"
84
+ #: The share of the panel's width up to the patch card's right edge, and where
85
+ #: the card starts on an 800 wide panel: controlpanel's own layout, kept in step
86
+ #: by the check.
87
+ PATCH_SHARE = 0.34
88
+ PATCH_INSET = 24
89
+ #: The space either side of the meters, on an 800 wide panel.
90
+ METER_GAP = 6
91
+
92
+ #: The running app, for a console or a bench script: ``current.adapter``
93
+ #: is the adapter of the instrument on the panel, ``current.parts`` has every
94
+ #: channel's, and ``current.parser.feed()`` plays MIDI bytes. None while the
95
+ #: app isn't open.
96
+ current = None
97
+
98
+
99
+ def _style(obj, bg=None, radius=0):
100
+ obj.set_style_border_width(0, 0)
101
+ obj.set_style_radius(radius, 0)
102
+ obj.set_style_pad_all(0, 0)
103
+ if bg is not None:
104
+ obj.set_style_bg_color(lv.color_hex(bg), 0)
105
+ obj.set_style_bg_opa(lv.OPA.COVER, 0)
106
+
107
+
108
+ def _label(parent, text, color=TEXT, font=None):
109
+ label = lv.label(parent)
110
+ label.set_text(text)
111
+ label.set_style_text_color(lv.color_hex(color), 0)
112
+ if font is not None:
113
+ label.set_style_text_font(font, 0)
114
+ return label
115
+
116
+
117
+ def _display_x(panel):
118
+ """Where the panel's display starts: its window sits in a bezel on the header."""
119
+ return panel.display.obj.get_parent().get_parent().get_x()
120
+
121
+
122
+ class Station:
123
+ """The whole app on *scope*. ``main(scope)`` makes one."""
124
+
125
+ def __init__(self, scope):
126
+ self.scope = scope
127
+ self.root = scope.root
128
+ self.width, self.height = scope.size
129
+ self.prefs = scope.store()
130
+ self.inputs = None
131
+ self.output = None
132
+ self.adapter = None
133
+ self.panel = None
134
+ self.name = None
135
+ #: The instruments, by MIDI channel counted from 0, and the channel
136
+ #: the panel shows.
137
+ self.parts = {}
138
+ self.channel = 0
139
+ self._playing = ()
140
+ self._mix = None
141
+ self._restored = False
142
+ self._short = False
143
+ self.loading = False
144
+ self._filling = False
145
+ self._fills = 0
146
+ self._played = 0
147
+ self._idle_us = None
148
+ self._settle = 0
149
+ #: The voices every playing instrument may sound between them, or
150
+ #: None until the governor first reads the instruments' own.
151
+ self._cap = None
152
+ self._fitted = 0
153
+ self._raised = False
154
+ self._read = None
155
+ self._refused = None
156
+ self._timers = []
157
+ self._meters = None
158
+ self._volume = None
159
+ self._held = {}
160
+ self._patch_step = 0
161
+ self._instrument_step = 0
162
+ self._shown = None
163
+ self._since_log = 0
164
+ self._names = None
165
+ self._panel_midi = False
166
+ #: Whether the channel list ends with the Bluetooth MIDI switch.
167
+ self._ble_ok = _midi.ble_available()
168
+ #: Whether the remembered Bluetooth switch has been acted on.
169
+ self._ble_started = False
170
+ try:
171
+ import audioinstruments as ai
172
+
173
+ from .audio import Output
174
+
175
+ self.ai = ai
176
+ self.output = Output(scope)
177
+ except ImportError as e:
178
+ self._missing("Synth Station needs the audio libraries: %s." % (e,))
179
+ return
180
+ if not self.output.can_play:
181
+ self._missing("Synth Station needs a board_peripherals module with an audio_out role, which this board's config doesn't have.")
182
+ return
183
+ self.catalog = catalog(ai)
184
+ name = RENAMED.get(self.prefs.get("name"), self.prefs.get("name"))
185
+ if find(self.catalog, name)[0] is None:
186
+ name = DEFAULT
187
+ self.prefs["name"] = name
188
+ self.instruments = [item for _, items in self.catalog for item in items]
189
+ self.parser = _midi.Parser(self)
190
+ scope.on_close(self.close)
191
+ global current
192
+ current = self
193
+ self._build_splash()
194
+ self._build_menu()
195
+ self._status_timer = scope.every(STATUS_MS, self._status_tick)
196
+ # Opening the keyboards can take a moment (a USB host starting), so
197
+ # it happens once the splash is on the screen.
198
+ scope.after(50, self._open_midi)
199
+ follow = getattr(scope, "follow", None)
200
+ if follow is not None and sys.platform in _midi.DESKTOPS + _midi.BROWSERS:
201
+ follow("midi.in", self._midi_moved)
202
+
203
+ # ---- the splash and the menu -----------------------------------------------
204
+
205
+ def _missing(self, text):
206
+ _style(self.root, BG)
207
+ label = _label(self.root, text)
208
+ label.set_width(self.width - 40)
209
+ label.set_long_mode(lv.label.LONG_MODE.WRAP)
210
+ label.center()
211
+
212
+ def _build_splash(self):
213
+ w, h = self.width, self.height
214
+ _style(self.root, BG)
215
+ splash = lv.obj(self.root)
216
+ _style(splash, BG)
217
+ splash.set_size(w, h)
218
+ splash.remove_flag(lv.obj.FLAG.SCROLLABLE)
219
+ self.splash = splash
220
+ title = _label(splash, "SYNTH STATION", TEXT, lv.font_montserrat_24)
221
+ title.set_pos(16, 12)
222
+ self.midi_label = _label(splash, "MIDI: looking...", DIM, lv.font_montserrat_16)
223
+ self.midi_label.set_long_mode(lv.label.LONG_MODE.DOTS)
224
+ self.midi_label.set_width(w - 32)
225
+ self.midi_label.set_pos(16, 46)
226
+ self.notice = _label(splash, "", ACCENT, lv.font_montserrat_16)
227
+ self.notice.set_pos(16, h - 26)
228
+ self.notice.set_width(w - 32)
229
+ self.notice.set_long_mode(lv.label.LONG_MODE.DOTS)
230
+
231
+ def _build_menu(self):
232
+ menu = lv.dropdown(self.root)
233
+ menu.set_options("\n".join(display for _, display in self.instruments))
234
+ menu.set_style_text_font(lv.font_montserrat_16, 0)
235
+ menu.set_style_text_color(lv.color_hex(TEXT), 0)
236
+ menu.set_style_bg_color(lv.color_hex(PANEL), 0)
237
+ menu.set_style_border_width(0, 0)
238
+ menu.get_list().set_style_text_font(lv.font_montserrat_16, 0)
239
+ menu.add_event_cb(self._menu_changed, lv.EVENT.VALUE_CHANGED, None)
240
+ self.menu = menu
241
+ font = getattr(lv, "font_montserrat_14", lv.font_montserrat_16)
242
+ channels = lv.dropdown(self.root)
243
+ channels.set_style_text_font(font, 0)
244
+ channels.set_style_text_color(lv.color_hex(TEXT), 0)
245
+ channels.set_style_bg_color(lv.color_hex(PANEL), 0)
246
+ channels.set_style_border_width(0, 0)
247
+ channels.set_style_pad_ver(4, 0)
248
+ channels.get_list().set_style_text_font(font, 0)
249
+ channels.add_event_cb(self._channel_changed, lv.EVENT.VALUE_CHANGED, None)
250
+ self.channels = channels
251
+ self._fill_menus()
252
+ self._place_menu()
253
+
254
+ def _fill_menus(self):
255
+ """What both drop-downs list and show, for the channel on the panel."""
256
+ channel = self.channel
257
+ names = [display for _, display in self.instruments]
258
+ if channel:
259
+ names.insert(0, FOLLOW)
260
+ self.menu.set_options("\n".join(names))
261
+ own = self.parts.get(channel)
262
+ if own is not None:
263
+ self._show_in_menu(own.name)
264
+ elif not channel:
265
+ self._show_in_menu(self.prefs["name"])
266
+ self._fill_channels()
267
+
268
+ def _fill_channels(self):
269
+ """The channels, with a star on each that has an instrument of its own."""
270
+ text = "%d%s" if self._short else "Ch %d%s"
271
+ star = "*" if self._short else " *"
272
+ options = [text % (c + 1, star if c and c in self.parts else "") for c in range(CHANNELS)]
273
+ if self._ble_ok:
274
+ # Last, so it's one more step for an encoder and one tap for a finger.
275
+ on = self.inputs is not None and self.inputs.ble is not None
276
+ options.append(("BT on" if on else "BT off") if self._short else
277
+ ("Bluetooth on" if on else "Bluetooth off"))
278
+ self.channels.set_options("\n".join(options))
279
+ self.channels.set_selected(self.channel)
280
+
281
+ def _place_menu(self):
282
+ """On the panel's name plate, or under the splash's title."""
283
+ menu = self.menu
284
+ channels = self.channels
285
+ panel = self.panel
286
+ short = self._short
287
+ if panel is None:
288
+ menu.set_size(MENU_W, MENU_H)
289
+ menu.set_pos(16, 76)
290
+ channels.set_size(CHANNEL_W, MENU_H)
291
+ channels.set_pos(16 + MENU_W + 8, 76)
292
+ else:
293
+ plate = panel.title
294
+ if plate.has_flag(lv.obj.FLAG.HIDDEN): # a compact panel has no plate
295
+ # The two share the room the menu had: the header has no more.
296
+ short = True
297
+ width = MENU_W // 2 - CHANNEL_COMPACT_W - 2
298
+ menu.set_size(width, MENU_H)
299
+ menu.set_pos(2, 2)
300
+ channels.set_size(CHANNEL_COMPACT_W, MENU_H)
301
+ channels.set_pos(2 + width + 2, 2)
302
+ else:
303
+ plate.add_flag(lv.obj.FLAG.HIDDEN)
304
+ # The patch card's width, unless a bigger display leaves the
305
+ # meters no room beside that.
306
+ panel.root.update_layout()
307
+ s = panel._s
308
+ x = s(PATCH_INSET)
309
+ room = _display_x(panel) - 2 * s(METER_GAP) - Meters.width(s)
310
+ right = min(int(panel.width * PATCH_SHARE), room)
311
+ y = max(2, plate.get_y() - 8)
312
+ menu.set_size(max(right - x, MENU_W // 2), MENU_H)
313
+ menu.set_pos(x, y)
314
+ # Under it, right of the engine's light.
315
+ below = y + MENU_H + 2
316
+ channels.set_size(s(CHANNEL_W), min(CHANNEL_H, panel.header.get_height() - below - 2))
317
+ channels.set_pos(x + s(CHANNEL_INSET), below)
318
+ if short and not self._short:
319
+ # Once: a display that's compact stays compact.
320
+ self._short = True
321
+ channels.set_symbol(None)
322
+ # Their lists stay wide enough to read.
323
+ menu.get_list().set_style_min_width(MENU_W // 2, 0)
324
+ channels.get_list().set_style_min_width(CHANNEL_W, 0)
325
+ self._fill_channels()
326
+ menu.move_foreground()
327
+ channels.move_foreground()
328
+
329
+ def _build_meters(self):
330
+ """In the header between the menu and the display, if they fit."""
331
+ panel = self.panel
332
+ s = panel._s
333
+ menu = self.menu
334
+ menu.update_layout()
335
+ channels = self.channels
336
+ channels.update_layout()
337
+ left = max(menu.get_x() + menu.get_width(), channels.get_x() + channels.get_width()) + s(METER_GAP)
338
+ room = _display_x(panel) - s(METER_GAP) - left
339
+ width = Meters.width(s)
340
+ if room >= width:
341
+ pad = s(6)
342
+ self._meters = Meters(panel.header, left + (room - width) // 2, pad, panel.header.get_height() - 2 * pad, s)
343
+
344
+ def _meter_tick(self, _timer=None):
345
+ left, right = self.output.levels()
346
+ self._meters.tick(left, right)
347
+
348
+ def _menu_changed(self, _event):
349
+ at = self.menu.get_selected()
350
+ if self.channel:
351
+ if at == 0:
352
+ self.follow()
353
+ return
354
+ at -= 1
355
+ self.choose(self.instruments[at][0])
356
+
357
+ def _channel_changed(self, _event):
358
+ at = self.channels.get_selected()
359
+ if at == CHANNELS:
360
+ self.set_ble(self.inputs is None or self.inputs.ble is None)
361
+ return
362
+ self.show(at)
363
+
364
+ def set_ble(self, on):
365
+ """Turn Bluetooth MIDI on or off, and remember it for the next time
366
+ the app opens. A failure to start is said where the MIDI status is."""
367
+ inputs = self.inputs
368
+ if inputs is None:
369
+ return
370
+ self.prefs["ble"] = bool(on)
371
+ self._ble_started = True
372
+ try:
373
+ inputs.set_ble(on, self.parser)
374
+ except Exception as e: # said on the status line by ble_text()
375
+ print("synthstation: Bluetooth MIDI didn't start:", e)
376
+ self.prefs["ble"] = False
377
+ self._fill_channels()
378
+ self._shown = None
379
+ self._status_tick()
380
+
381
+ def _show_in_menu(self, name):
382
+ for i, (module, _) in enumerate(self.instruments):
383
+ if module == name:
384
+ self.menu.set_selected(i + 1 if self.channel else i)
385
+ return
386
+
387
+ # ---- MIDI ------------------------------------------------------------------
388
+
389
+ def _open_midi(self, _timer=None):
390
+ self.inputs = _midi.Inputs().open()
391
+ self._show_midi()
392
+ self._first_instrument(KEYBOARD_WAIT_MS)
393
+
394
+ def _midi_moved(self, endpoints):
395
+ """Other MIDI inputs were chosen for the computer: read those, or
396
+ every input again when none is."""
397
+ if self.inputs is None:
398
+ return # not open yet, or reopening below
399
+ self.inputs.close()
400
+ self.inputs = None
401
+ if any(ep.error for ep in endpoints):
402
+ # This app held a port the choice wanted, and a port has one
403
+ # reader at a time: now it's let go, ask for the choice again.
404
+ import endpointkit
405
+
406
+ endpointkit.select("midi.in", endpointkit.chosen("midi.in"))
407
+ self.inputs = _midi.Inputs().open()
408
+ self._show_midi()
409
+
410
+ def _first_instrument(self, wait_ms):
411
+ """Open the last instrument played, once a keyboard is seen or the wait is over."""
412
+ if self.panel is not None or self.loading or self.inputs is None:
413
+ return
414
+ # A keyboard shows up as the port is read, and nothing else reads it yet.
415
+ self.inputs.poll(self.parser)
416
+ if wait_ms > 0 and self.inputs.kind == "usb" and not self.has_midi():
417
+ self.scope.after(KEYBOARD_POLL_MS, lambda t: self._first_instrument(wait_ms - KEYBOARD_POLL_MS))
418
+ return
419
+ self._show_midi()
420
+ self.pick(self.prefs["name"])
421
+
422
+ def _midi_text(self):
423
+ text = self._inputs_text()
424
+ ble = self.inputs.ble_text() if self.inputs is not None else None
425
+ if ble is not None and ble != "Bluetooth": # while connected, it's one of the names
426
+ text += " " + ble + "."
427
+ return text
428
+
429
+ def _inputs_text(self):
430
+ inputs = self.inputs
431
+ if inputs is None:
432
+ return "MIDI: looking..."
433
+ if inputs.kind is None and inputs.names():
434
+ return "MIDI: " + " + ".join(inputs.names())
435
+ if inputs.kind is None:
436
+ if inputs.why == _midi.NO_INPUT:
437
+ return "No MIDI keyboard: the pads play notes."
438
+ return "No MIDI (%s): the pads play notes." % (inputs.why,)
439
+ names = inputs.names()
440
+ if not names:
441
+ if inputs.kind == "usb":
442
+ return "No MIDI keyboard: plug one into the USB host port, or play the pads."
443
+ if inputs.kind == "web" and inputs.ports[0].why:
444
+ return "No MIDI: the browser refused it. The pads play notes."
445
+ return "No MIDI keyboard: the pads play notes."
446
+ return "MIDI: " + " + ".join(names)
447
+
448
+ def has_midi(self):
449
+ inputs = self.inputs
450
+ return inputs is not None and bool(inputs.names())
451
+
452
+ def _show_midi(self):
453
+ text = self._midi_text()
454
+ if text != self._names:
455
+ self._names = text
456
+ self.midi_label.set_text(text)
457
+ self.midi_label.set_style_text_color(lv.color_hex(TEXT if self.has_midi() else ACCENT), 0)
458
+
459
+ # The parser's sink: a keyboard's messages land here.
460
+
461
+ def _part(self, channel):
462
+ """The part MIDI channel *channel* plays: its own, or channel 1's."""
463
+ parts = self.parts
464
+ return parts.get(channel) or parts.get(0)
465
+
466
+ def note_on(self, note, velocity, channel=0):
467
+ if self._meters is not None:
468
+ self._meters.strike(velocity)
469
+ part = self._part(channel)
470
+ if part is None or self.loading:
471
+ return
472
+ if channel == PAD_CHANNEL and part.pad_notes is not None:
473
+ pad = note - _pads.FIRST_PAD
474
+ if not 0 <= pad < len(part.pad_notes):
475
+ return # a pad past the kit's last sound is silent
476
+ # Kept for the release: a SoundFont's next kit lays out differently.
477
+ part.struck[note] = note = part.pad_notes[pad]
478
+ if self._mix is not None:
479
+ self._mix.wake(part.adapter.instrument)
480
+ part.adapter.note_on(note, velocity)
481
+ self._played = 2
482
+
483
+ def note_off(self, note, channel=0):
484
+ part = self._part(channel)
485
+ if part is None or self.loading:
486
+ return
487
+ if channel == PAD_CHANNEL and part.pad_notes is not None:
488
+ note = part.struck.pop(note, None)
489
+ if note is None:
490
+ return
491
+ part.adapter.note_off(note)
492
+
493
+ def control(self, controller, value, channel=0):
494
+ part = self._part(channel)
495
+ if part is None or self.loading:
496
+ return
497
+ adapter = part.adapter
498
+ if controller == VOLUME_CC and channel == 0:
499
+ # Like the knobs: the codec is across I2C, so only the last value.
500
+ self._volume = value
501
+ return
502
+ if controller in PATCH_CCS or controller in INSTRUMENT_CCS:
503
+ # Once per press, whatever a button or a slider sends after it.
504
+ pressed = value >= 64
505
+ if pressed and not self._held.get(controller):
506
+ if controller in PATCH_CCS:
507
+ self._patch_step += PATCH_CCS[controller]
508
+ else:
509
+ self._instrument_step += INSTRUMENT_CCS[controller]
510
+ self._held[controller] = pressed
511
+ return
512
+ if controller in KNOB_CCS:
513
+ knob = KNOB_CCS.index(controller)
514
+ elif controller in SOUND_CCS:
515
+ knob = SOUND_CCS.index(controller)
516
+ else:
517
+ knob = -1
518
+ if 0 <= knob < adapter.macro_count:
519
+ # Only each knob's last value, applied once everything waiting
520
+ # has been read: a macro change can take milliseconds, and a
521
+ # fast sweep sends a hundred values a second.
522
+ part.knobs[knob] = value
523
+ else:
524
+ adapter.instrument.control_change(controller, value)
525
+
526
+ def bend(self, value, channel=0):
527
+ part = self._part(channel)
528
+ if part is not None and not self.loading:
529
+ part.adapter.instrument.pitch_bend(value)
530
+
531
+ def program(self, number, channel=0):
532
+ part = self._part(channel)
533
+ if part is not None:
534
+ part.program = number
535
+
536
+ def _lay_out_pads(self, part):
537
+ """Read the pads' notes once per patch, as asking a SoundFont takes a moment."""
538
+ adapter = part.adapter
539
+ part.pad_patch = adapter.patch_index
540
+ part.pad_notes = _pads.pad_notes(part.name, adapter.instrument)
541
+
542
+ def _midi_tick(self, _timer=None):
543
+ inputs = self.inputs
544
+ if inputs is None or self.adapter is None or self.loading:
545
+ return
546
+ playing = self._playing
547
+ for part in playing:
548
+ if part.adapter.patch_index != part.pad_patch:
549
+ self._lay_out_pads(part)
550
+ inputs.poll(self.parser)
551
+ for part in playing:
552
+ adapter = part.adapter
553
+ if part.knobs:
554
+ knobs = part.knobs
555
+ part.knobs = {}
556
+ for knob, value in knobs.items():
557
+ adapter.note_cc(knob, value)
558
+ if part.program is not None:
559
+ number = part.program
560
+ part.program = None
561
+ # Only a program the instrument has: the others would be silence.
562
+ if number in (adapter.instrument.patches or {}):
563
+ adapter.note_program(number)
564
+ if self._volume is not None:
565
+ self.output.set_volume(self._volume * 100 // 127)
566
+ self._volume = None
567
+ if self._patch_step:
568
+ step = self._patch_step
569
+ self._patch_step = 0
570
+ self._step_patch(step)
571
+ if self._instrument_step:
572
+ step = self._instrument_step
573
+ self._instrument_step = 0
574
+ # Not from inside this timer: the change stops it.
575
+ self.scope.after(1, lambda t: self._step_instrument(step))
576
+
577
+ def _step_patch(self, step):
578
+ adapter = self.adapter
579
+ keys = sorted(adapter.instrument.patches or {})
580
+ if len(keys) > 1:
581
+ at = keys.index(adapter.patch_index) if adapter.patch_index in keys else 0
582
+ adapter.note_program(keys[(at + step) % len(keys)])
583
+
584
+ def _step_instrument(self, step):
585
+ names = [module for module, _ in self.instruments]
586
+ at = names.index(self.name) if self.name in names else 0
587
+ self.choose(names[(at + step) % len(names)])
588
+
589
+ # ---- the instrument ------------------------------------------------------
590
+
591
+ def choose(self, name):
592
+ """Give the channel on the panel instrument *name*, from the menu or
593
+ a keyboard's buttons. On channel 1 that changes what every channel
594
+ without an instrument of its own plays."""
595
+ own = self.parts.get(self.channel)
596
+ if self.loading or (own is not None and name == own.name and self.panel is not None):
597
+ return
598
+ self._close_panel()
599
+ self._silence()
600
+ self._drop(self.channel)
601
+ self._remember()
602
+ self.splash.remove_flag(lv.obj.FLAG.HIDDEN)
603
+ self._place_menu()
604
+ self.pick(name)
605
+
606
+ def show(self, channel):
607
+ """Put MIDI channel *channel*, 0 to 15, on the panel: its own
608
+ instrument, or channel 1's while it has none. The sound carries on."""
609
+ if self.loading or not 0 <= channel < CHANNELS:
610
+ return
611
+ self._close_panel()
612
+ self.channel = channel
613
+ self._fill_menus()
614
+ if 0 in self.parts and (self.output.instrument is not None or self._play()):
615
+ self._open_panel()
616
+
617
+ def follow(self):
618
+ """Take away the instrument of the channel on the panel, so that it
619
+ plays channel 1's again."""
620
+ channel = self.channel
621
+ if self.loading or not channel or channel not in self.parts:
622
+ return
623
+ self._close_panel()
624
+ self._silence()
625
+ self._drop(channel)
626
+ self._remember()
627
+ self._fill_menus()
628
+ if 0 in self.parts and self._play():
629
+ self._open_panel()
630
+
631
+ def _reopen(self):
632
+ self._close_panel()
633
+ self._open_panel()
634
+
635
+ def _silence(self):
636
+ """Stop the output and let go of the mix, before a part changes."""
637
+ self.output.stop()
638
+ mix = self._mix
639
+ self._mix = None
640
+ if mix is not None:
641
+ mix.deinit()
642
+
643
+ def _drop(self, channel):
644
+ """Deinitialise a channel's own instrument. Nothing may be pulling it."""
645
+ part = self.parts.pop(channel, None)
646
+ self._playing = tuple(self.parts[c] for c in sorted(self.parts))
647
+ if part is not None:
648
+ part.forget()
649
+ part.adapter.instrument.deinit()
650
+
651
+ def _remember(self):
652
+ """Keep which channels have which instruments for the next time the
653
+ app opens, once the ones kept last time are back."""
654
+ if self._restored:
655
+ self.prefs["parts"] = {str(c + 1): part.name for c, part in self.parts.items() if c}
656
+
657
+ def _patch_key(self, channel, name):
658
+ return name if not channel else "%d:%s" % (channel + 1, name)
659
+
660
+ def _play(self):
661
+ """Send every part to the output: one as it is, several through a mix.
662
+
663
+ Returns False, with the reason on the splash, when the output won't start.
664
+ """
665
+ self._silence()
666
+ playing = self._playing = tuple(self.parts[c] for c in sorted(self.parts))
667
+ output = self.output
668
+ try:
669
+ if len(playing) == 1:
670
+ output.start(playing[0].adapter.instrument)
671
+ else:
672
+ self._mix = Mix([part.adapter.instrument for part in playing], output.rate, output.channels)
673
+ output.start(self._mix)
674
+ except Exception as e:
675
+ self._silence()
676
+ self.notice.set_text("No sound out: %s" % (e,))
677
+ return False
678
+ return True
679
+
680
+ def pick(self, name):
681
+ """Open instrument *name* on the panel."""
682
+ if self.loading or self.panel is not None:
683
+ return
684
+ self.loading = True
685
+ self._show_in_menu(name)
686
+ self.notice.set_text("Loading %s..." % find(self.catalog, name)[1])
687
+ # Give the screen a frame to show that before the work starts.
688
+ self.scope.after(30, lambda t: self._load(name))
689
+
690
+ def _create(self, name):
691
+ import audioinstruments.panel
692
+
693
+ adapter = audioinstruments.panel.create(name, self.output.rate, channel_count=self.output.channels)
694
+ inst = adapter.instrument
695
+ # Build the voices' tables now, not on the first key.
696
+ note_map = getattr(self.ai.load(name), "NOTE_MAP", None)
697
+ for note in ([n for n, _ in note_map] if note_map else (60,)):
698
+ inst.note_on(note, 1)
699
+ inst.fill()
700
+ inst.all_notes_off()
701
+ inst.fill()
702
+ return adapter
703
+
704
+ def _add(self, channel, name):
705
+ """Create instrument *name* as *channel*'s part, on the patch it was left on."""
706
+ adapter = self._create(name)
707
+ inst = adapter.instrument
708
+ patch = self.prefs.get("patches", {}).get(self._patch_key(channel, name))
709
+ if patch and patch in (inst.patches or {}):
710
+ adapter.set_patch(patch)
711
+ # RELOAD builds the instrument again. Nothing is played or filled
712
+ # while it does; then the output takes the new one and lets go of
713
+ # the old, which is deinitialised once nothing pulls it.
714
+ reload = adapter.request_reload
715
+
716
+ def request_reload():
717
+ self.loading = True
718
+ try:
719
+ return reload()
720
+ finally:
721
+ self.loading = False
722
+
723
+ adapter.request_reload = request_reload
724
+ adapter.on_reload(self._reloaded)
725
+ part = self.parts[channel] = Part(name, adapter)
726
+ # A drum machine's voices are its sounds, one circuit each: a cap would
727
+ # silence the sounds past it, so it's never capped.
728
+ part.most = 1 if name in _pads.KIT_PADS else inst.voices
729
+ self._lay_out_pads(part)
730
+ return part
731
+
732
+ def _restore(self):
733
+ """Bring back the other channels' instruments from the last time the app was open."""
734
+ for key, name in sorted(self.prefs.get("parts", {}).items()):
735
+ channel = int(key) - 1
736
+ name = RENAMED.get(name, name)
737
+ if not 0 < channel < CHANNELS or channel in self.parts or find(self.catalog, name)[0] is None:
738
+ continue
739
+ try:
740
+ self._add(channel, name)
741
+ except Exception as e:
742
+ print("synthstation: channel %s's %s didn't load: %s" % (key, name, e))
743
+
744
+ def _load(self, name):
745
+ display = find(self.catalog, name)[1]
746
+ channel = self.channel
747
+ try:
748
+ self._add(channel, name)
749
+ except Exception as e:
750
+ self.notice.set_text("%s didn't load: %s" % (display, e))
751
+ self.loading = False
752
+ return
753
+ if not channel:
754
+ self.prefs["name"] = name
755
+ if not self._restored and 0 in self.parts:
756
+ self._restored = True
757
+ self._restore()
758
+ self._remember()
759
+ if 0 not in self.parts:
760
+ self.notice.set_text("Choose an instrument for Ch 1 first.")
761
+ self.loading = False
762
+ return
763
+ if not self._play():
764
+ self.loading = False
765
+ return
766
+ self._fill_menus()
767
+ self._open_panel()
768
+ self.loading = False
769
+ if self._ble_ok and self.prefs.get("ble") and not self._ble_started:
770
+ # After the sound: on a board short of internal RAM, Bluetooth
771
+ # failing to start is said on the status line, and the
772
+ # instrument still plays.
773
+ self._ble_started = True
774
+ self.set_ble(True)
775
+ self._status_tick()
776
+
777
+ def _open_panel(self):
778
+ """Build the panel for the channel being shown. Its part is already playing."""
779
+ part = self._part(self.channel)
780
+ adapter = part.adapter
781
+ name = part.name
782
+ self.name = name
783
+ self._idle_us = None
784
+ self._settle = 0
785
+ self._cap = None
786
+ self._fitted = 0
787
+ self._raised = False
788
+ self._read = None
789
+ self._refused = None
790
+ self.adapter = adapter
791
+ self.notice.set_text("")
792
+ self.splash.add_flag(lv.obj.FLAG.HIDDEN)
793
+ shown = adapter
794
+ if not self.has_midi():
795
+ shown = _pads.NotePads(adapter, _pads.notes_for(self.ai.load(name)), self._pad_note)
796
+ self._panel_midi = self.has_midi()
797
+ self.panel = self._build_panel(shown, find(self.catalog, name)[1])
798
+ self._place_menu()
799
+ self._build_meters()
800
+ self._shown = None
801
+ self._since_log = 0
802
+ self._timers = [
803
+ self.scope.every(MIDI_MS, self._midi_tick),
804
+ self.scope.every(FILL_MS, self._fill),
805
+ ]
806
+ if self._meters is not None:
807
+ self._timers.append(self.scope.every(METER_MS, self._meter_tick))
808
+
809
+ def _reloaded(self, new, old):
810
+ # Every adapter already holds its newest instrument.
811
+ self._play()
812
+ old.deinit()
813
+
814
+ def _build_panel(self, adapter, title):
815
+ import sys
816
+
817
+ import audioinstruments.panel_view as panel_view
818
+
819
+ two_wheels = False
820
+ if getattr(sys, "platform", "") in ("linux", "darwin", "win32"):
821
+ # Only the display_driver that opened this window: importing it
822
+ # here would open another.
823
+ driver = sys.modules.get("display_driver")
824
+ if driver is not None and hasattr(driver, "set_wheel_mapping"):
825
+ driver.set_wheel_mapping(adjust_axis="h", adjust_sign=1, navigate=True, navigate_sign=-1)
826
+ two_wheels = True
827
+ self._wheels = driver
828
+ return panel_view.build(
829
+ adapter, screen=self.root, title=title, subtitle=None if self.has_midi() else "No MIDI",
830
+ two_wheels=two_wheels)
831
+
832
+ def _pad_note(self, note):
833
+ adapter = self.adapter
834
+ if adapter is None:
835
+ return
836
+ if self._mix is not None:
837
+ self._mix.wake(adapter.instrument)
838
+ adapter.note_on(note, 100)
839
+ self.scope.after(PAD_NOTE_MS, lambda t: self.adapter is adapter and adapter.note_off(note))
840
+
841
+ def _fill(self, _timer=None):
842
+ """Let the instrument take in what was played. A tick can land
843
+ between the bytecodes of whatever the app is doing, so one that
844
+ arrives inside another fill, or while the instrument is being
845
+ swapped, is dropped."""
846
+ adapter = self.adapter
847
+ if adapter is None or self._filling or self.loading:
848
+ return
849
+ playing = self._playing
850
+ self._filling = True
851
+ try:
852
+ for part in playing:
853
+ part.adapter.instrument.fill()
854
+ if self._mix is not None:
855
+ self._mix.tick(FILL_MS)
856
+ finally:
857
+ self._filling = False
858
+ self._fills += 1
859
+ # A new note is read again once its strike has rendered, rather than
860
+ # waiting for the next scheduled look.
861
+ if self._played:
862
+ self._played -= 1
863
+ if self._played == 1 or self._fills % GOVERN_EVERY == 0:
864
+ self._govern()
865
+
866
+ def _govern(self):
867
+ """Cap the voices at what the pump can render in time.
868
+
869
+ The pump renders on a core of its own, so a chord the core can't
870
+ keep up with doesn't slow the app, it starves the speaker: the audio
871
+ runs behind for as long as the keys are held. Each sounding voice
872
+ costs about the same, so from the cost of the blocks just rendered
873
+ this works out how many voices fit in `BUDGET` of a block's time.
874
+ That count is one cap for every instrument playing, and `_share`
875
+ hands it out between them. The extra notes steal instead of
876
+ everything going quiet. The cap is set from the first sounding
877
+ voice, before a chord needs it. That voice also wakes whatever the
878
+ voices share, so it reads dearer than the voices after it: with
879
+ every allowed voice sounding and room for one more, the cap goes up
880
+ one, and a count that has fit stays allowed unless the blocks go
881
+ over budget. A cap it just raised stays up until a chord has used it
882
+ or the blocks go over budget: the keys already held can't take the
883
+ new voice, so their reads say nothing about it. A count that went
884
+ over budget isn't tried again until the keys are up, because each
885
+ try steals a note.
886
+
887
+ A drum machine's sounds are outside the cap, and what they cost
888
+ counts against the other instruments' voices.
889
+ """
890
+ output = self.output
891
+ cost = output.pull_us()
892
+ parts = [part for part in self._playing if part.most > 1]
893
+ if cost is None or not parts:
894
+ return
895
+ if self._settle:
896
+ # The blocks right after a cap still carry the voices it stole.
897
+ self._settle -= 1
898
+ return
899
+ counts = [part.adapter.instrument.voice_pool.sounding() for part in parts]
900
+ sounding = sum(counts)
901
+ voices = self._cap
902
+ if voices is None:
903
+ voices = self._cap = sum(part.adapter.instrument.voices for part in parts)
904
+ if sounding == 0:
905
+ self._idle_us = cost if self._idle_us is None else min(self._idle_us, cost)
906
+ self._refused = None
907
+ self._share(parts, counts)
908
+ return
909
+ idle = self._idle_us or 0
910
+ budget = BUDGET * output.block_us()
911
+ per_voice = (cost - idle) / sounding
912
+ if per_voice <= 0:
913
+ self._share(parts, counts)
914
+ return
915
+ # Every part that's sounding keeps a voice: the cap thins chords, it
916
+ # never silences a keyboard.
917
+ fit = max(len(counts) - counts.count(0), int((budget - idle) / per_voice + 0.5))
918
+ # Just after a key the mean still holds blocks from before it.
919
+ settled = self._played == 0
920
+ if cost <= budget:
921
+ if settled and sounding > self._fitted:
922
+ self._fitted = sounding
923
+ fit = max(fit, self._fitted)
924
+ if fit < voices and (cost > budget or sounding >= voices or not self._raised):
925
+ if cost > budget:
926
+ self._refused = sounding
927
+ self._cap = fit
928
+ self._raised = False
929
+ self._settle = SETTLE
930
+ elif (
931
+ settled
932
+ and sounding >= voices
933
+ and voices < sum(part.most for part in parts)
934
+ and (self._refused is None or voices + 1 < self._refused)
935
+ ):
936
+ step = per_voice
937
+ read = self._read
938
+ if read is not None and read[0] < sounding and cost > read[1]:
939
+ step = (cost - read[1]) / (sounding - read[0])
940
+ if cost + step <= budget:
941
+ self._cap = voices + 1
942
+ self._raised = True
943
+ self._settle = SETTLE
944
+ if settled:
945
+ self._read = (sounding, cost)
946
+ if self._share(parts, counts):
947
+ self._settle = SETTLE
948
+
949
+ def _share(self, parts, counts):
950
+ """Hand the cap out between *parts*, sounding *counts* voices now.
951
+
952
+ The cap counts the voices of the parts that are sounding. Each gets
953
+ what it's sounding and one spare, so its next key sounds without
954
+ stealing and a growing chord shows in the next read. Over the cap,
955
+ the spares go first, then voices from whichever is sounding the
956
+ most: the biggest chord loses a note before a smaller part does,
957
+ and none goes below one voice. Under it, the room left goes to the
958
+ part with the fewest. A quiet part keeps an even split of the cap
959
+ for its next chord, which the read after it trims if it has to.
960
+ Returns True when that stole voices.
961
+ """
962
+ cap = self._cap
963
+ even = max(1, cap // len(parts))
964
+ shares = []
965
+ total = 0
966
+ for part, count in zip(parts, counts):
967
+ share = min(part.most, count + 1 if count else even)
968
+ shares.append(share)
969
+ if count:
970
+ total += share
971
+ while total > cap:
972
+ pick = best = None
973
+ for i, share in enumerate(shares):
974
+ if counts[i] and share > 1:
975
+ # A spare before a sounding voice, then the biggest share.
976
+ key = (share > counts[i], share)
977
+ if best is None or key > best:
978
+ pick, best = i, key
979
+ if pick is None:
980
+ break
981
+ shares[pick] -= 1
982
+ total -= 1
983
+ while total < cap:
984
+ pick = None
985
+ for i, share in enumerate(shares):
986
+ if counts[i] and share < parts[i].most and (pick is None or share < shares[pick]):
987
+ pick = i
988
+ if pick is None:
989
+ break
990
+ shares[pick] += 1
991
+ total += 1
992
+ stole = False
993
+ for part, share, count in zip(parts, shares, counts):
994
+ inst = part.adapter.instrument
995
+ if inst.voices != share:
996
+ inst.voices = share
997
+ if share < count:
998
+ stole = True
999
+ return stole
1000
+
1001
+ def _close_panel(self):
1002
+ """Take the panel down. The instruments stay, and keep playing."""
1003
+ for timer in self._timers:
1004
+ timer.deinit()
1005
+ self._timers = []
1006
+ self._meters = None
1007
+ self.adapter = None
1008
+ patches = self.prefs.setdefault("patches", {})
1009
+ for channel, part in self.parts.items():
1010
+ patches[self._patch_key(channel, part.name)] = part.adapter.patch_index
1011
+ part.forget()
1012
+ panel = self.panel
1013
+ self.panel = None
1014
+ if panel is not None:
1015
+ panel.delete()
1016
+ driver = getattr(self, "_wheels", None)
1017
+ if driver is not None:
1018
+ self._wheels = None
1019
+ driver.set_wheel_mapping(adjust_axis="v", adjust_sign=1, navigate=False, navigate_sign=1)
1020
+
1021
+ # ---- the readout -----------------------------------------------------------
1022
+
1023
+ def _status_text(self):
1024
+ """The display's second line: render load and underruns."""
1025
+ load, worst, underruns = self.output.load()
1026
+ text = "LOAD --" if load is None else "LOAD %d%% U%d" % (load, underruns)
1027
+ inputs = self.inputs
1028
+ if inputs is not None and inputs.ble is not None:
1029
+ text += " BT" if inputs.ble.state == "connected" else " BT..."
1030
+ elif inputs is not None and inputs.ble_why:
1031
+ text += " BT!"
1032
+ return text
1033
+
1034
+ def _status_tick(self, _timer=None):
1035
+ if self.inputs is not None and self.panel is None:
1036
+ self._show_midi()
1037
+ panel = self.panel
1038
+ if panel is None or self.loading:
1039
+ return
1040
+ if self.has_midi() and not self._panel_midi:
1041
+ # A keyboard arrived: its panel has patches where the note pads were.
1042
+ self._reopen()
1043
+ return
1044
+ text = self._status_text()
1045
+ if text != self._shown:
1046
+ self._shown = text
1047
+ panel.set_status(text)
1048
+ if LOG_MS:
1049
+ self._since_log += STATUS_MS
1050
+ if self._since_log >= LOG_MS:
1051
+ self._since_log = 0
1052
+ output = self.output
1053
+ print("synthstation: %s load %s%% peak %s%% underruns %d starved %d ms" % (
1054
+ self.name, output.load_pct, output.worst_pct, output.underruns, output.starved_ms()))
1055
+
1056
+ def close(self):
1057
+ global current
1058
+ if current is self:
1059
+ current = None
1060
+ self._close_panel()
1061
+ if self.output is not None:
1062
+ # Before the instruments go, so nothing pulls a deinitialised one.
1063
+ self._silence()
1064
+ for channel in list(self.parts):
1065
+ self._drop(channel)
1066
+ self.output.close()
1067
+ if self.inputs is not None:
1068
+ self.inputs.close()
1069
+ self.inputs = None