-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeck.py
More file actions
1604 lines (1431 loc) · 67.9 KB
/
Copy pathdeck.py
File metadata and controls
1604 lines (1431 loc) · 67.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Launchpad Mini MK3 — macro deck (Stream-Deck style).
Programs pads to run actions: launch apps, media play/pause, next/prev,
volume up/down/mute, Discord mute/deafen (via a global hotkey you set in
Discord). Pads are colour-coded by category, flash white on press, and a
legend is printed / shown so you know what each pad does.
Layout is loaded from deck_config.json if present, else a sensible default
is used (and written to that file so you can edit it).
Run: python deck.py (add --list to see MIDI ports)
"""
import argparse
import collections
import ctypes
import ctypes.wintypes # noqa: F401 (Streamlabs named-pipe client)
import glob
import json
import math
import os
import random
import subprocess
import sys
import threading
import time
import warnings
sys.coinit_flags = 0 # COINIT_MULTITHREADED for comtypes (matches soundcard) -> no COM clash
import numpy as np
import pygame.midi as pm
import soundcard as sc
import lightshow as LS
import winmidi
warnings.filterwarnings("ignore")
HDR = [0x00, 0x20, 0x29, 0x02, 0x0D]
SYSEX_PROGRAMMER = [0xF0] + HDR + [0x0E, 0x01, 0xF7]
SYSEX_LIVE = [0xF0] + HDR + [0x0E, 0x00, 0xF7]
N = 8
HERE = os.path.dirname(os.path.abspath(__file__))
if getattr(sys, "frozen", False): # bundled .exe -> writable user config
_cfgdir = os.path.join(os.environ.get("APPDATA", HERE), "LaunchpadDeck")
try:
os.makedirs(_cfgdir, exist_ok=True)
except Exception:
_cfgdir = HERE
CONFIG = os.path.join(_cfgdir, "deck_config.json")
else:
CONFIG = os.path.join(HERE, "deck_config.json")
LOGDIR = os.path.dirname(CONFIG)
LOGFILE = os.path.join(LOGDIR, "deck.log")
try:
import faulthandler
_logfh = open(LOGFILE, "a", buffering=1, encoding="utf-8")
faulthandler.enable(_logfh) # dumps native (C-level) crashes here too
except Exception:
_logfh = None
def log(msg):
print(msg, flush=True)
try:
if _logfh:
import datetime
_logfh.write(f"{datetime.datetime.now():%H:%M:%S} {msg}\n")
except Exception:
pass
# ---------------- colours (RGB 0-127) ----------------
C = {
"blue": (0, 40, 127), "green": (0, 127, 25), "red": (127, 0, 0),
"orange": (127, 45, 0), "cyan": (0, 110, 120), "purple": (85, 0, 127),
"yellow": (120, 110, 0), "white": (127, 127, 127), "pink": (127, 0, 70),
"spotify": (20, 120, 45), "discord": (70, 60, 127), "off": (0, 0, 0),
}
TOP_ROW = [91, 92, 93, 94, 95, 96, 97, 98] # top round buttons (CC) -> light-show controls
RIGHT_COL = [19, 29, 39, 49, 59, 69, 79, 89] # right column (CC) -> sensitivity / input level
_LIB_CACHE = None
def get_clip_library():
"""Load the project light-show clips once (from Desktop *\\Lights\\*.mid)."""
global _LIB_CACHE
if _LIB_CACHE is None:
try:
desk = os.path.join(os.path.expanduser("~"), "Desktop")
folders = [d for d in glob.glob(os.path.join(desk, "*", "Lights")) if os.path.isdir(d)]
_LIB_CACHE = LS.load_library(folders, cap=200) if folders else []
print(f"[deck] loaded {len(_LIB_CACHE)} project clips", flush=True)
except Exception as e:
print(f"[deck] clip load failed: {e}", flush=True); _LIB_CACHE = []
return _LIB_CACHE
# ---- scrolling clock (deck 'clock' mode) ----
_FONT = {
"0": ["111", "101", "101", "101", "111"], "1": ["010", "110", "010", "010", "111"],
"2": ["111", "001", "111", "100", "111"], "3": ["111", "001", "111", "001", "111"],
"4": ["101", "101", "111", "001", "001"], "5": ["111", "100", "111", "001", "111"],
"6": ["111", "100", "111", "101", "111"], "7": ["111", "001", "010", "010", "010"],
"8": ["111", "101", "111", "101", "111"], "9": ["111", "101", "111", "001", "111"],
":": ["000", "010", "000", "010", "000"],
}
class ClockView:
def _columns(self):
import datetime
s = datetime.datetime.now().strftime("%H:%M")
cols = []
for ch in s:
g = _FONT.get(ch, ["000"] * 5)
for x in range(3):
cols.append([g[y][x] == "1" for y in range(5)])
cols.append([False] * 5) # gap column
return cols
def frame(self): # -> dict pad_index -> (r,g,b)
cols = self._columns(); width = len(cols)
pos = int(time.time() * 4.0) % (width + N)
col_rgb = (0, 110, 120)
out = {}
for x in range(N):
ci = pos - N + x
if 0 <= ci < width:
bits = cols[ci]
for y in range(5):
if bits[y]:
out[pad_index(x, 6 - y)] = col_rgb # digits on rows 6..2
return out
def pad_index(col, row): # row 0 = bottom
return (row + 1) * 10 + (col + 1)
def rgb_sysex(colours): # colours: dict pad_index -> (r,g,b)
body = []
for idx, (r, g, b) in colours.items():
body += [0x03, idx, int(r), int(g), int(b)]
return [0xF0] + HDR + [0x03] + body + [0xF7]
# ---- section blocks (visual zones, dim background tint) ----
SECTIONS = [
("Media", [6, 7], [0, 1, 2, 3], (0, 1, 3)),
("Volume", [6, 7], [4, 5, 6, 7], (3, 1, 0)),
("Programs", [3, 4], [0, 1, 2, 3, 4, 5, 6, 7], (0, 2, 2)),
("Voice", [0, 1], [0, 1, 2, 3, 4, 5, 6, 7], (0, 2, 1)),
]
SECTION_BG = {}
for _name, _rows, _cols, _tint in SECTIONS:
for _r in _rows:
for _c in _cols:
SECTION_BG[pad_index(_c, _r)] = _tint
# ---- 8x8 action icons (drawn full-grid on press) ----
def _parse_icon(rows):
cells = []
for i, line in enumerate(rows):
for c, ch in enumerate(line):
if ch == "#":
cells.append((c, 7 - i)) # row 0 = bottom
return cells
ICONS = {}
def _icon(name, rows, color):
ICONS[name] = (_parse_icon(rows), color)
_icon("play", ["..#.....", "..##....", "..###...", "..####..",
"..####..", "..###...", "..##....", "..#....."], C["green"])
_icon("stop", ["........", ".######.", ".######.", ".######.",
".######.", ".######.", ".######.", "........"], C["pink"])
_icon("next", [".#....#.", ".##...#.", ".###..#.", ".####.#.",
".####.#.", ".###..#.", ".##...#.", ".#....#."], C["blue"])
_icon("prev", [".#....#.", ".#...##.", ".#..###.", ".#.####.",
".#.####.", ".#..###.", ".#...##.", ".#....#."], C["blue"])
_icon("volup", ["...##...", "...##...", "...##...", "########",
"########", "...##...", "...##...", "...##..."], C["green"])
_icon("voldown", ["........", "........", "........", "########",
"########", "........", "........", "........"], C["orange"])
_icon("mute", ["#......#", ".#....#.", "..#..#..", "...##...",
"...##...", "..#..#..", ".#....#.", "#......#"], C["red"])
_icon("mic", ["...##...", "..####..", "..####..", "..####..",
"...##...", "...##...", ".######.", "........"], C["green"])
_icon("camera", ["........", ".#....#.", ".######.", ".##..##.",
".#.##.#.", ".##..##.", ".######.", "........"], C["cyan"])
_icon("lock", ["..####..", ".##..##.", ".##..##.", "########",
"########", "##.##.##", "########", "........"], C["yellow"])
_icon("rocket", ["...##...", "..####..", "..####..", ".######.",
".######.", ".#.##.#.", "#......#", "..#..#.."], C["cyan"])
_icon("light", ["...##...", "#..##..#", ".######.", "..####..",
".######.", "#..##..#", "...##...", "........"], C["purple"])
_icon("heart", ["........", ".##..##.", "########", "########",
".######.", "..####..", "...##...", "........"], C["red"])
_icon("note", ["....###.", "....#.#.", "....#...", "....#...",
"....#...", ".####...", ".####...", "..##...."], C["spotify"])
_icon("globe", ["..####..", ".#.##.#.", "#..##..#", "########",
"#..##..#", "#..##..#", ".#.##.#.", "..####.."], C["cyan"])
_icon("folder", ["........", "###.....", "#######.", "#######.",
"#######.", "#######.", "#######.", "........"], C["yellow"])
_icon("gear", ["...##...", ".#.##.#.", "..####..", "###..###",
"###..###", "..####..", ".#.##.#.", "...##..."], C["yellow"])
_icon("plane", ["......#.", ".....##.", "...####.", ".#####..",
"...####.", ".....##.", "......#.", "........"], C["blue"])
_icon("apps", ["........", ".##..##.", ".##..##.", "........",
".##..##.", ".##..##.", "........", "........"], C["green"])
_icon("calc", [".######.", ".#.##.#.", ".######.", ".#.#.#.#",
".######.", ".#.#.#.#", ".######.", "........"], C["purple"])
_icon("headphone", ["..####..", ".#....#.", "##....##", "##....##",
"##....##", "##....##", "##....##", "........"], C["purple"])
_icon("clock", ["..####..", ".#.##.#.", "#..#...#", "#..###.#",
"#......#", "#......#", ".#....#.", "..####.."], C["cyan"])
def get_icon(e):
t = e.get("type"); p = (e.get("param", "") or "").lower()
key = None
if t == "media":
key = {"playpause": "play", "stop": "stop", "next": "next", "prev": "prev",
"volup": "volup", "voldown": "voldown", "mute": "mute"}.get(e.get("param", ""))
elif t == "sysmute":
key = "mute"
elif t == "mic":
key = "mic"
elif t == "lock":
key = "lock"
elif t == "lightshow":
key = "light"
elif t == "clock":
key = "clock"
elif t == "multi":
key = "apps"
elif t == "app":
key = {"spotify": "note", "browser": "globe", "chrome": "globe",
"discord": "rocket", "telegram": "plane", "steelseries": "gear"}.get(p, "rocket")
elif t == "run":
if "explorer" in p:
key = "folder"
elif "calc" in p:
key = "calc"
else:
key = "rocket"
elif t == "hotkey":
if "shift+s" in p:
key = "camera"
elif p.replace(" ", "") == "win+l":
key = "lock"
elif "esc" in p:
key = "gear"
elif p.replace(" ", "").endswith("+d"):
key = "headphone"
return ICONS.get(key) if key else None
# ---------------- Windows key / media sender ----------------
user32 = ctypes.windll.user32
KEYUP = 0x0002
VK = {"ctrl": 0x11, "control": 0x11, "shift": 0x10, "alt": 0x12, "win": 0x5B,
"enter": 0x0D, "space": 0x20, "tab": 0x09, "esc": 0x1B}
MEDIA = {"playpause": 0xB3, "next": 0xB0, "prev": 0xB1,
"volup": 0xAF, "voldown": 0xAE, "mute": 0xAD, "stop": 0xB2}
def _key(vk, up=False):
user32.keybd_event(vk, 0, KEYUP if up else 0, 0)
def send_media(name, repeat=1):
vk = MEDIA.get(name)
if vk is None:
return
for _ in range(repeat):
_key(vk); _key(vk, True); time.sleep(0.01)
def send_combo(combo):
keys = combo.lower().replace(" ", "").split("+")
vks = []
for k in keys:
if k in VK:
vks.append(VK[k])
elif len(k) == 1:
vks.append(ord(k.upper()))
for v in vks:
_key(v)
time.sleep(0.02)
for v in reversed(vks):
_key(v, True)
def launch_app(name):
name = name.lower()
try:
if name == "spotify":
try:
os.startfile("spotify:")
except OSError:
p = os.path.expandvars(r"%APPDATA%\Spotify\Spotify.exe")
if os.path.exists(p):
os.startfile(p)
elif name == "discord":
upd = os.path.expandvars(r"%LOCALAPPDATA%\Discord\Update.exe")
if os.path.exists(upd):
subprocess.Popen([upd, "--processStart", "Discord.exe"])
else:
os.startfile("discord:")
elif name == "browser":
os.startfile("https://google.com")
else:
os.startfile(name)
except Exception as e:
print(f"[deck] launch '{name}' failed: {e}", flush=True)
# ---------------- system mic / speaker mute (works everywhere incl. Discord) ----
_AUDIO = {}
def _make_epvol(a, flow, role): # flow: 0=speaker,1=mic; role: 0=console,2=communications
dev = a["enum"].GetDefaultAudioEndpoint(flow, role)
return a["cast"](dev.Activate(a["iaev"]._iid_, a["ctx"], None), a["ptr"](a["iaev"]))
def init_audio():
try:
import comtypes
try:
comtypes.CoInitialize() # may already be initialised (soundcard) -> ignore
except Exception:
pass
from pycaw.pycaw import IMMDeviceEnumerator, IAudioEndpointVolume
from pycaw.constants import CLSID_MMDeviceEnumerator
from comtypes import CoCreateInstance, CLSCTX_ALL, cast, POINTER
_AUDIO.update(enum=CoCreateInstance(CLSID_MMDeviceEnumerator, IMMDeviceEnumerator, CLSCTX_ALL),
cast=cast, ptr=POINTER, iaev=IAudioEndpointVolume, ctx=CLSCTX_ALL)
_AUDIO["mic"] = _make_epvol(_AUDIO, 1, 0) # cache endpoints (avoid COM churn)
_AUDIO["spk"] = _make_epvol(_AUDIO, 0, 0)
try:
_AUDIO["mic_comm"] = _make_epvol(_AUDIO, 1, 2)
except Exception:
_AUDIO["mic_comm"] = None
log(f"[deck] audio ready (mic muted={is_muted(1)})")
except Exception as e:
log(f"[deck] audio init failed: {e}")
def _ep(flow):
return _AUDIO.get("mic" if flow == 1 else "spk")
def toggle_mute(flow):
try:
v = _ep(flow)
if v is None:
return
newmute = 0 if v.GetMute() else 1
v.SetMute(newmute, None)
if flow == 1 and _AUDIO.get("mic_comm") is not None:
try:
_AUDIO["mic_comm"].SetMute(newmute, None)
except Exception:
pass
except Exception as e:
log(f"[deck] mute toggle failed: {e}")
def is_muted(flow):
try:
v = _ep(flow)
return bool(v.GetMute()) if v is not None else False
except Exception:
return False
def launch_named(name):
"""Best-effort launch of a well-known program by name."""
n = name.lower().strip()
desktop = os.path.join(os.path.expanduser("~"), "Desktop")
def lnk(fname):
p = os.path.join(desktop, fname)
return p if os.path.exists(p) else None
def first_exe(*paths):
for p in paths:
if p and os.path.exists(p):
os.startfile(p); return True
return False
def start_menu_lnk(*parts): # find a Start-Menu shortcut by name
roots = [os.path.join(os.environ.get("ProgramData", ""), r"Microsoft\Windows\Start Menu\Programs"),
os.path.join(ap, r"Microsoft\Windows\Start Menu\Programs")]
for root in roots:
if not os.path.isdir(root):
continue
for dp, _dn, fn in os.walk(root):
for f in fn:
lf = f.lower()
if lf.endswith(".lnk") and all(p in lf for p in parts):
return os.path.join(dp, f)
return None
pf = os.environ.get("ProgramFiles", ""); pf86 = os.environ.get("ProgramFiles(x86)", "")
la = os.environ.get("LOCALAPPDATA", ""); ap = os.environ.get("APPDATA", "")
try:
if "magic" in n:
first_exe(lnk("MAGIC VPN.lnk"))
elif "steel" in n:
if not first_exe(os.path.join(pf, "SteelSeries", "GG", "SteelSeriesGG.exe"),
os.path.join(pf86, "SteelSeries", "GG", "SteelSeriesGG.exe"),
os.path.join(pf, "SteelSeries", "GG", "SteelSeries GG.exe"),
os.path.join(pf86, "SteelSeries", "GG", "SteelSeries GG.exe"),
lnk("SteelSeries GG.lnk")):
first_exe(start_menu_lnk("steelseries"))
elif "spotify" in n:
try:
os.startfile("spotify:")
except Exception:
first_exe(lnk("Spotify.lnk"), os.path.join(ap, "Spotify", "Spotify.exe"))
elif "telegram" in n:
first_exe(lnk("Telegram.lnk"), os.path.join(ap, "Telegram Desktop", "Telegram.exe"))
elif "chrome" in n:
if not first_exe(os.path.join(pf, "Google", "Chrome", "Application", "chrome.exe"),
os.path.join(pf86, "Google", "Chrome", "Application", "chrome.exe")):
first_exe(lnk("Google Chrome.lnk"))
elif "discord" in n:
launch_app("discord")
else:
os.startfile(name)
except Exception as e:
print(f"[deck] launch_named '{name}' failed: {e}", flush=True)
def set_app_volume(spec):
"""spec = 'name:action' — action: up / down / mute / set:NN (0-100). Adjusts one app's volume."""
try:
from pycaw.pycaw import AudioUtilities, ISimpleAudioVolume
parts = [x.strip() for x in spec.split(":")]
name = parts[0].lower()
action = parts[1].lower() if len(parts) > 1 else "up"
step = 0.08
hit = False
for s in AudioUtilities.GetAllSessions():
if not s.Process:
continue
pname = (s.Process.name() or "").lower()
if name and name not in pname:
continue
hit = True
vol = s._ctl.QueryInterface(ISimpleAudioVolume)
if action == "mute":
vol.SetMute(0 if vol.GetMute() else 1, None)
elif action == "down":
vol.SetMasterVolume(max(0.0, vol.GetMasterVolume() - step), None)
elif action == "set" and len(parts) > 2:
vol.SetMasterVolume(max(0.0, min(1.0, int(parts[2]) / 100.0)), None)
else: # up (default)
vol.SetMasterVolume(min(1.0, vol.GetMasterVolume() + step), None)
if not hit:
log(f"[deck] app volume: '{name}' not playing")
except Exception as e:
log(f"[deck] app volume '{spec}' failed: {e}")
# ------------------------------------------------------------------ OBS / Streamlabs
# Two backends behind one obs_action():
# * "obs" -> OBS Studio via obs-websocket v5 (obsws_python), needs the built-in
# WebSocket Server enabled (Tools -> WebSocket Server Settings).
# * "streamlabs" -> Streamlabs Desktop via its local named-pipe JSON-RPC API.
# * "auto" -> try OBS Studio first, then Streamlabs.
# All calls run on a worker thread (never on the render loop) so a missing / slow
# target can NEVER freeze the pad.
_OBS = {"cl": None}
_OBS_LOCK = threading.Lock()
_OBS_LAST = {"backend": None}
def _obs_settings():
try:
with open(os.path.join(os.path.dirname(CONFIG) or HERE, "settings.json"), encoding="utf-8") as f:
return json.load(f)
except Exception:
return {}
def _obs_backend():
return (_obs_settings().get("obs_backend", "auto") or "auto").lower()
# ---- OBS Studio (obs-websocket v5) ----
def _obsws_client():
if _OBS.get("cl") is not None:
return _OBS["cl"]
import obsws_python as obs
s = _obs_settings()
host = s.get("obs_host", "localhost"); port = int(s.get("obs_port", 4455))
pw = s.get("obs_password", "")
_OBS["cl"] = obs.ReqClient(host=host, port=port, password=pw, timeout=3)
return _OBS["cl"]
def _obsws_action(cmd, arg):
cl = _obsws_client()
if cmd == "scene" and arg:
name = arg
if arg.isdigit(): # "scene:2" -> the 2nd scene in OBS's list
try:
scenes = cl.get_scene_list().scenes
names = [s.get("sceneName") for s in scenes][::-1] # OBS lists bottom-up
i = int(arg) - 1
if 0 <= i < len(names):
name = names[i]
except Exception:
pass
cl.set_current_program_scene(name)
elif cmd == "record":
cl.toggle_record()
elif cmd == "stream":
cl.toggle_stream()
elif cmd == "pause":
cl.toggle_record_pause()
elif cmd == "mute" and arg:
cl.toggle_input_mute(arg)
elif cmd in ("replay", "save_replay"):
cl.save_replay_buffer()
elif cmd == "virtualcam":
cl.toggle_virtual_cam()
# ---- Streamlabs Desktop (local named-pipe JSON-RPC) ----
class _SlobsPipe:
PIPE = r"\\.\pipe\slobs"
_GR = 0x80000000; _GW = 0x40000000; _OPEN = 3
_MSG = 0x00000002; _MORE = 234; _BUSY = 231
def __init__(self):
self.k = ctypes.WinDLL("kernel32", use_last_error=True)
self.k.CreateFileW.restype = ctypes.wintypes.HANDLE
self.k.CreateFileW.argtypes = [ctypes.wintypes.LPCWSTR, ctypes.wintypes.DWORD,
ctypes.wintypes.DWORD, ctypes.wintypes.LPVOID,
ctypes.wintypes.DWORD, ctypes.wintypes.DWORD,
ctypes.wintypes.HANDLE]
self.k.WaitNamedPipeW.argtypes = [ctypes.wintypes.LPCWSTR, ctypes.wintypes.DWORD]
self.k.PeekNamedPipe.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.LPVOID,
ctypes.wintypes.DWORD, ctypes.wintypes.LPDWORD,
ctypes.wintypes.LPDWORD, ctypes.wintypes.LPDWORD]
self.INVALID = ctypes.wintypes.HANDLE(-1).value
self.h = None
def open(self):
for _ in range(6):
h = self.k.CreateFileW(self.PIPE, self._GR | self._GW, 0, None, self._OPEN, 0, None)
if h != self.INVALID:
mode = ctypes.wintypes.DWORD(self._MSG)
self.k.SetNamedPipeHandleState(h, ctypes.byref(mode), None, None)
self.h = h
return True
if ctypes.get_last_error() == self._BUSY:
self.k.WaitNamedPipeW(self.PIPE, 800)
continue
return False
return False
_MISS = object() # "matching id not seen yet" sentinel
def _match(self, buf, rid):
# accept newline-delimited OR single-message JSON; ignore async event frames
for line in buf.decode("utf-8", "replace").replace("\r", "").split("\n"):
line = line.strip()
if not line:
continue
try:
obj = json.loads(line)
except Exception:
continue # partial / not-yet-complete frame
if isinstance(obj, dict) and obj.get("id") == rid:
return obj.get("result")
return self._MISS
def request(self, method, resource, *args, timeout=2.5):
"""Send one JSON-RPC request and wait (bounded) for its reply.
NEVER blocks indefinitely: PeekNamedPipe is polled so ReadFile only runs
when data is actually available, and the whole thing gives up after `timeout`.
"""
rid = int(time.time() * 1000) % 100000
req = {"jsonrpc": "2.0", "id": rid, "method": method,
"params": {"resource": resource, "args": list(args)}}
data = (json.dumps(req) + "\n").encode("utf-8")
n = ctypes.wintypes.DWORD(0)
if not self.k.WriteFile(self.h, data, len(data), ctypes.byref(n), None):
return None
deadline = time.time() + timeout
buf = b""
while time.time() < deadline:
avail = ctypes.wintypes.DWORD(0)
if not self.k.PeekNamedPipe(self.h, None, 0, None, ctypes.byref(avail), None):
return None # pipe closed / broken
if avail.value == 0:
time.sleep(0.02)
continue
tmp = ctypes.create_string_buffer(avail.value)
got = ctypes.wintypes.DWORD(0)
ok = self.k.ReadFile(self.h, tmp, avail.value, ctypes.byref(got), None)
buf += tmp.raw[:got.value]
if not ok and ctypes.get_last_error() not in (0, self._MORE):
return None
res = self._match(buf, rid)
if res is not self._MISS:
return res
return None # timed out — reply never arrived
def close(self):
try:
if self.h:
self.k.CloseHandle(self.h)
except Exception:
pass
self.h = None
_SL_VCAM = [False] # local virtual-cam toggle state
def _slobs_pick_scene(scenes, arg):
if arg.isdigit(): # "scene:1" -> the 1st scene (order as in Streamlabs)
i = int(arg) - 1
return scenes[i].get("id") if 0 <= i < len(scenes) else None
for s in scenes: # exact name
if (s.get("name") or "").lower() == arg.lower():
return s.get("id")
for s in scenes: # partial name
if arg.lower() in (s.get("name") or "").lower():
return s.get("id")
return None
def _slobs_action(cmd, arg):
p = _SlobsPipe()
if not p.open():
raise OSError("Streamlabs pipe unavailable (запусти Streamlabs; если он от админа — запусти и Launchpad Deck от админа)")
try:
if cmd == "scene" and arg:
scenes = p.request("getScenes", "ScenesService") or []
sid = _slobs_pick_scene(scenes, arg)
if sid:
p.request("makeSceneActive", "ScenesService", sid)
else:
log("[deck] SLOBS scene '%s' not found. Есть сцены: %s"
% (arg, ", ".join(repr(s.get("name")) for s in scenes)))
elif cmd == "record":
p.request("toggleRecording", "StreamingService")
elif cmd == "stream":
p.request("toggleStreaming", "StreamingService")
elif cmd == "pause":
p.request("toggleRecording", "StreamingService") # SLOBS has no separate pause
elif cmd == "mute" and arg:
srcs = p.request("getSources", "AudioService") or []
src = None
if arg.isdigit():
i = int(arg) - 1
src = srcs[i] if 0 <= i < len(srcs) else None
if src is None:
src = next((s for s in srcs if (s.get("name") or "").lower() == arg.lower()), None)
if src is None:
src = next((s for s in srcs if arg.lower() in (s.get("name") or "").lower()), None)
if src:
want = not bool(src.get("muted"))
rid = src.get("resourceId")
sid = src.get("sourceId") or src.get("id")
done = False
if rid: # AudioSource.setMuted(bool) via its resourceId
r = p.request("setMuted", rid, want)
done = r is not None
if not done and sid: # fallback: AudioService.setMuted(sourceId, bool)
p.request("setMuted", "AudioService", sid, want)
else:
log("[deck] SLOBS audio '%s' not found. Есть источники: %s"
% (arg, ", ".join(repr(s.get("name")) for s in srcs)))
elif cmd in ("replay", "save_replay"):
p.request("saveReplay", "StreamingService")
elif cmd == "virtualcam":
_SL_VCAM[0] = not _SL_VCAM[0]
p.request("start" if _SL_VCAM[0] else "stop", "VirtualWebcamService")
finally:
p.close()
def _slobs_report():
"""Dump the user's Streamlabs scenes + audio sources to a text file for diagnostics."""
p = _SlobsPipe()
if not p.open():
return None
try:
scenes = p.request("getScenes", "ScenesService") or []
srcs = p.request("getSources", "AudioService") or []
model = p.request("getModel", "StreamingService") or {}
finally:
p.close()
lines = ["Streamlabs Desktop — найденные объекты", "", "СЦЕНЫ (для пэда: scene:НОМЕР или scene:Имя):"]
for i, s in enumerate(scenes, 1):
lines.append(" %d) %s" % (i, s.get("name")))
lines.append("")
lines.append("АУДИО-ИСТОЧНИКИ (для пэда: mute:Имя или mute:НОМЕР):")
for i, s in enumerate(srcs, 1):
lines.append(" %d) %r muted=%s (sourceId=%s, resourceId=%s)"
% (i, s.get("name"), s.get("muted"), s.get("sourceId"), s.get("resourceId")))
lines.append("")
lines.append("StreamingService.getModel: %s" % json.dumps(model, ensure_ascii=False))
txt = "\n".join(lines)
try:
path = os.path.join(os.path.dirname(CONFIG) or HERE, "streamlabs_report.txt")
with open(path, "w", encoding="utf-8") as f:
f.write(txt)
except Exception:
path = None
return {"path": path, "scenes": [s.get("name") for s in scenes],
"sources": [s.get("name") for s in srcs]}
def _do_obs_action(spec):
parts = [x.strip() for x in spec.split(":", 1)]
cmd = parts[0].lower(); arg = parts[1] if len(parts) > 1 else ""
backend = _obs_backend()
order = {"obs": ["obs"], "streamlabs": ["streamlabs"]}.get(backend, ["obs", "streamlabs"])
if backend not in ("obs", "streamlabs") and _OBS_LAST["backend"] in order:
order = [_OBS_LAST["backend"]] + [b for b in order if b != _OBS_LAST["backend"]]
errs = []
for b in order:
try:
if b == "obs":
_obsws_action(cmd, arg)
else:
_slobs_action(cmd, arg)
_OBS_LAST["backend"] = b
return
except Exception as e:
if b == "obs":
_OBS["cl"] = None # drop stale ws connection, reconnect next time
errs.append(f"{b}: {e}")
log(f"[deck] OBS action '{spec}' failed -> " + " | ".join(errs))
def obs_action(spec):
"""Fire-and-forget on a worker thread so the render loop never blocks.
spec: scene:Name / record / stream / pause / mute:Source / replay / virtualcam.
"""
def _worker():
with _OBS_LOCK: # serialise requests (one client at a time)
_do_obs_action(spec)
threading.Thread(target=_worker, daemon=True).start()
def _obs_test_inner():
backend = _obs_backend()
order = {"obs": ["obs"], "streamlabs": ["streamlabs"]}.get(backend, ["obs", "streamlabs"])
errs = []
for b in order:
try:
if b == "obs":
cl = _obsws_client()
cl.get_version()
_OBS_LAST["backend"] = "obs"
return True, "OBS Studio", "OBS Studio"
else:
p = _SlobsPipe()
if not p.open():
raise OSError("pipe unavailable (Streamlabs не запущен, или он от админа — запусти Launchpad Deck тоже от админа)")
try:
scenes = p.request("getScenes", "ScenesService")
finally:
p.close()
if scenes is None:
raise OSError("no reply from Streamlabs pipe")
_OBS_LAST["backend"] = "streamlabs"
rep = _slobs_report()
msg = "Streamlabs Desktop"
if rep and rep.get("scenes"):
msg += " · сцены: " + ", ".join(str(s) for s in rep["scenes"][:6])
return True, "Streamlabs", msg
except Exception as e:
if b == "obs":
_OBS["cl"] = None
errs.append(f"{b}: {e}")
return False, None, " | ".join(errs)
def obs_test():
"""Connectivity check for the GUI 'test connection' button.
Runs on a worker thread with a hard join timeout so it can NEVER hang the
caller (the pywebview API thread), even if a backend misbehaves.
Returns (ok, backend_name, message).
"""
box = {"r": (False, None, "timeout")}
def work():
try:
box["r"] = _obs_test_inner()
except Exception as e:
box["r"] = (False, None, str(e))
t = threading.Thread(target=work, daemon=True)
t.start()
t.join(7.0)
if t.is_alive():
return False, None, "timeout — программа не ответила вовремя"
return box["r"]
def run_action(a):
t = a.get("type"); p = a.get("param", "")
try:
if t == "multi":
for name in [x.strip() for x in p.replace(",", ";").split(";") if x.strip()]:
launch_named(name); time.sleep(0.35)
elif t == "media":
send_media(p)
elif t == "hotkey":
send_combo(p)
elif t == "app":
launch_app(p)
elif t == "mic":
toggle_mute(1)
elif t == "sysmute":
toggle_mute(0)
elif t == "appvol":
set_app_volume(p)
elif t == "obs":
obs_action(p)
elif t == "lock":
ctypes.windll.user32.LockWorkStation()
elif t == "color":
return # decorative colour pad, no action
elif t in ("run", "url", "open"):
os.startfile(p)
print(f"[deck] ran: {a.get('label', t)}", flush=True)
except Exception as e:
print(f"[deck] action error: {e}", flush=True)
# ---------------- default layout ----------------
# each entry: (col, row): {label, color, type, param}
def default_layout():
L = {}
def put(col, row, label, color, type, param):
L[f"{col},{row}"] = {"label": label, "color": color, "type": type, "param": param}
# --- MEDIA block (top-left) ---
put(0, 7, "Prev", "blue", "media", "prev")
put(1, 7, "Play/Pause", "green", "media", "playpause")
put(2, 7, "Next", "blue", "media", "next")
put(1, 6, "Stop", "pink", "media", "stop")
# --- VOLUME block (top-right) ---
put(4, 7, "Vol -", "orange", "media", "voldown")
put(5, 7, "Vol +", "orange", "media", "volup")
put(6, 7, "Sys Mute", "red", "sysmute", "") # speaker mute (green/red state)
# --- PROGRAMS block (middle) ---
put(0, 4, "Spotify", "spotify", "app", "spotify")
put(1, 4, "Discord", "discord", "app", "discord")
put(2, 4, "Browser", "cyan", "app", "browser")
put(3, 4, "Проводник", "blue", "run", r"C:\Windows\explorer.exe")
put(0, 3, "Калькулятор", "purple", "run", "calc.exe")
put(1, 3, "Диспетчер", "yellow", "hotkey", "ctrl+shift+esc")
# --- VOICE / SYSTEM block (bottom) ---
put(0, 1, "Микро", "green", "mic", "") # system mic mute (works in Discord!)
put(1, 1, "DC Deafen", "purple", "hotkey", "ctrl+shift+alt+d") # set same keybind in Discord
put(2, 1, "Скриншот", "cyan", "hotkey", "win+shift+s")
put(3, 1, "Блок ПК", "red", "lock", "")
put(4, 1, "Свет", "purple", "lightshow", "") # toggle the light show on the pad
put(5, 1, "Часы", "cyan", "clock", "") # toggle a scrolling clock on the pad
# one button (bottom-right) that launches all main programs at once
put(7, 0, "Всё сразу", "green", "multi",
"magic;steelseries;spotify;telegram;chrome;discord")
return L
def load_layout():
if os.path.exists(CONFIG):
try:
with open(CONFIG, encoding="utf-8") as f:
return json.load(f)
except Exception as e:
print(f"[deck] bad config, using default: {e}", flush=True)
lay = default_layout()
try:
with open(CONFIG, "w", encoding="utf-8") as f:
json.dump(lay, f, ensure_ascii=False, indent=2)
except Exception:
pass
return lay
_LP_PATTERNS = ("LPMiniMK3", "LPProMK3", "LPX", "Launchpad", "Mini MK3", "Mini MK2", "Launchpad X")
def find_port(want_output):
pm.init()
idxs = []
for i in range(pm.get_count()):
_i, raw, is_in, is_out, _o = pm.get_device_info(i)
name = raw.decode(errors="replace")
if not any(p in name for p in _LP_PATTERNS):
continue
if want_output and is_out and "MIDIOUT2" not in name:
return i
if (not want_output) and is_in:
idxs.append(i)
return idxs if not want_output else None
def print_legend(layout):
print("\n=== DECK LAYOUT (what each pad does) ===")
for r in range(N - 1, -1, -1):
line = ""
for c in range(N):
e = layout.get(f"{c},{r}")
line += f"[{e['label'][:9]:^9}]" if e else "[ . . . . ]"
print(line)
print("\nActions:")
for key, e in layout.items():
print(f" {e['label']:14} -> {e['type']}:{e['param']}")
print("=" * 40 + "\n", flush=True)
class LightEngine:
"""Embedded audio-reactive light show (reuses lightshow effects) so the
deck can toggle it on the pad within the same process (no MIDI conflict)."""
SR = 48000
BLOCK = 1024
def __init__(self, cfg=None):
spk = sc.default_speaker()
self.rec_cm = sc.get_microphone(spk.name, include_loopback=True).recorder(
samplerate=self.SR, channels=2, blocksize=self.BLOCK)
self.rec = self.rec_cm.__enter__()
self.cfg = cfg if cfg is not None else {"sens": 1.85, "gain": 1.25, "bright": 1.0}
self.cfg.setdefault("sens", 1.85); self.cfg.setdefault("gain", 1.25); self.cfg.setdefault("bright", 1.0)
self.cfg.setdefault("bass", 1.0); self.cfg.setdefault("treble", 1.0)
self.effects = [E() for E in LS.GEN_EFFECTS] # generative modes only (no clips)
try: # + user plugins (custom light effects)
plugdir = os.path.join(os.path.dirname(CONFIG) or HERE, "plugins")
os.makedirs(plugdir, exist_ok=True)
for E in LS.load_plugins(plugdir):
self.effects.append(E())
log(f"[deck] plugins: {len(self.effects) - len(LS.GEN_EFFECTS)} custom effect(s)")
except Exception as e:
log(f"[deck] plugin load failed: {e}")
self.cur = 0; self.scene_t = time.time()
self.auto = True; self.palette_shift = 0.0
self.hud_until = 0.0; self.hud_frac = 0.0; self.hud_color = (1.0, 1.0, 1.0)
self.mid_max = 1e-6; self.mid_hist = collections.deque(maxlen=43); self.since_snare = 99
self.nxt = None; self.fade = 0.0
self.energy_slow = 0.3; self.last_drop = 0.0; self.drop_until = 0.0; self.silent_since = None
self.drop_effect = LS.DropBurst(); self.idle_effect = LS.IdleAnim()
self.ripples = [] # pad-press ripples (colour from where you tap)
self.ctx = LS.Ctx()
self.flow = 0.0; self.hue_drift = 0.0
self.running_max = 1e-4; self.bass_max = 1e-6; self.treb_max = 1e-6
self.band_max = np.full(8, 1e-6); self.bass_hist = collections.deque(maxlen=43)
self.since_beat = 99; self.bass_kick = 0.0
self.freqs = np.fft.rfftfreq(self.BLOCK, 1 / self.SR)
self.bass_bins = np.where((self.freqs >= 30) & (self.freqs <= 160))[0]
self.mid_bins = np.where((self.freqs > 160) & (self.freqs <= 2000))[0]
self.treb_bins = np.where((self.freqs > 2000) & (self.freqs <= 16000))[0]
edges = np.logspace(np.log10(40), np.log10(16000), 9)
self.band_bins = [np.where((self.freqs >= edges[b]) & (self.freqs < edges[b + 1]))[0] for b in range(8)]
self.win = np.hanning(self.BLOCK).astype(np.float32)
self.last = time.time()
def frame(self):
try:
data = self.rec.record(numframes=self.BLOCK)
except Exception:
time.sleep(0.02); return None
mono = data.mean(axis=1)
if len(mono) < self.BLOCK:
return None
spec = np.abs(np.fft.rfft(mono[:self.BLOCK] * self.win)).astype(np.float32)
rms = float(np.sqrt(np.mean(mono ** 2)))
self.running_max = max(self.running_max * 0.9995, rms, 1e-4)
mag = spec + 1e-9