-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathobs_cli.py
More file actions
executable file
·1564 lines (1378 loc) · 50.6 KB
/
obs_cli.py
File metadata and controls
executable file
·1564 lines (1378 loc) · 50.6 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
#!/usr/bin/env python
# coding: utf-8
import argparse
import base64
import json
import logging
import os
import re
import sys
from importlib import metadata
import obsws_python as obs
from rich import print, print_json
from rich.columns import Columns
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from rich_argparse import RichHelpFormatter
def get_version():
pyproject = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"pyproject.toml",
)
try:
with open(pyproject, encoding="utf-8") as f:
match = re.search(
r'^version = "([^"]+)"$',
f.read(),
re.MULTILINE,
)
if match:
return match.group(1)
except FileNotFoundError:
pass
try:
return metadata.version("obs-cli")
except metadata.PackageNotFoundError as exc:
raise RuntimeError("Could not determine obs-cli version") from exc
def response_to_dict(data):
if data is None:
return {}
attrs = getattr(data, "attrs", None)
if callable(attrs):
return {attr: getattr(data, attr) for attr in attrs()}
if isinstance(data, dict):
return data
return {}
def format_fps(video):
numerator = video.get("fps_numerator")
denominator = video.get("fps_denominator")
if numerator is None or denominator in (None, 0):
return _NA
fps = numerator / denominator
return f"{fps:.3f}".rstrip("0").rstrip(".")
def get_obs_info(cl):
version = response_to_dict(cl.get_version())
stats = response_to_dict(cl.get_stats())
video = response_to_dict(cl.get_video_settings())
studio_mode = response_to_dict(cl.get_studio_mode_enabled())
return {
"obs": {
"version": version.get("obs_version"),
"websocket_version": version.get("obs_web_socket_version"),
"rpc_version": version.get("rpc_version"),
"platform": version.get("platform"),
"platform_description": version.get("platform_description"),
"studio_mode_enabled": studio_mode.get("studio_mode_enabled"),
},
"video": {
"base_resolution": (
f"{video.get('base_width')}x{video.get('base_height')}"
if video.get("base_width") is not None
and video.get("base_height") is not None
else None
),
"output_resolution": (
f"{video.get('output_width')}x{video.get('output_height')}"
if video.get("output_width") is not None
and video.get("output_height") is not None
else None
),
"fps": format_fps(video),
"fps_numerator": video.get("fps_numerator"),
"fps_denominator": video.get("fps_denominator"),
},
"stats": {
"active_fps": stats.get("active_fps"),
"cpu_usage": stats.get("cpu_usage"),
"memory_usage": stats.get("memory_usage"),
"available_disk_space": stats.get("available_disk_space"),
"render_skipped_frames": stats.get("render_skipped_frames"),
"render_total_frames": stats.get("render_total_frames"),
"output_skipped_frames": stats.get("output_skipped_frames"),
"output_total_frames": stats.get("output_total_frames"),
"average_frame_render_time": stats.get(
"average_frame_render_time"
),
},
}
def parse_args():
parser = argparse.ArgumentParser(formatter_class=RichHelpFormatter)
parser.add_argument("-D", "--debug", action="store_true", default=False)
parser.add_argument("-q", "--quiet", action="store_true", default=False)
parser.add_argument(
"-V",
"--version",
action="version",
version=get_version(),
)
parser.add_argument(
"-H",
"--host",
default=os.environ.get("OBS_API_HOST", "localhost"),
help="host name default: localhost ($OBS_API_HOST)",
)
parser.add_argument(
"-P",
"--port",
type=int,
default=os.environ.get("OBS_API_PORT", 4455),
help="port number default: 4455 ($OBS_API_PORT)",
)
parser.add_argument(
"-p",
"--password",
required=False,
default=os.environ.get("OBS_API_PASSWORD"),
help="password ($OBS_API_PASSWORD)",
)
parser.add_argument("-j", "--json", action="store_true", default=False)
output_group = parser.add_mutually_exclusive_group()
output_group.add_argument(
"--pretty",
action="store_true",
default=False,
help="Pretty panel-based output for human-readable commands",
)
output_group.add_argument(
"--table",
"--tsv",
dest="table",
action="store_true",
default=False,
help="Force the existing table output",
)
subparsers = parser.add_subparsers(dest="command", required=True)
# Shared parent so subcommands also accept -j/--json after their name.
# argument_default=SUPPRESS means the subparser never writes a default
# for --json, preserving the main parser's value when the flag comes first.
_common = argparse.ArgumentParser(
add_help=False, argument_default=argparse.SUPPRESS
)
_common.add_argument("-j", "--json", action="store_true")
output_group = _common.add_mutually_exclusive_group()
output_group.add_argument("--pretty", action="store_true")
output_group.add_argument(
"--table",
"--tsv",
dest="table",
action="store_true",
)
subparsers.add_parser(
"info",
parents=[_common],
formatter_class=RichHelpFormatter,
)
scene_parser = subparsers.add_parser(
"scene",
aliases=["scenes"],
parents=[_common],
formatter_class=RichHelpFormatter,
)
scene_parser.add_argument(
"-e", "--exact", action="store_true", default=False, help="Exact match"
)
scene_parser.add_argument(
"-i",
"--ignorecase",
action="store_true",
default=False,
help="Exact match",
)
scene_parser.add_argument(
"action",
choices=["list", "switch", "current", "screenshot"],
default="list",
nargs="?",
help="list/switch/current/screenshot",
)
scene_parser.add_argument("SCENE", nargs="?", help="Scene name")
scene_parser.add_argument(
"-o",
"--output",
default=None,
help="Output file (required without --raw/--json)",
)
scene_parser.add_argument(
"--raw",
action="store_true",
default=False,
help="Write raw screenshot bytes to stdout",
)
scene_parser.add_argument(
"-f",
"--format",
default=None,
help="Image format: png, jpg, bmp (default: from filename ext or png)",
)
scene_parser.add_argument(
"--width", type=int, default=None, help="Screenshot width"
)
scene_parser.add_argument(
"--height", type=int, default=None, help="Screenshot height"
)
scene_parser.add_argument(
"--compression-quality",
type=int,
default=-1,
help="Compression quality -1 to 100 (-1 = OBS default)",
)
group_parser = subparsers.add_parser(
"group",
aliases=["groups"],
parents=[_common],
formatter_class=RichHelpFormatter,
)
group_parser.add_argument(
"-s", "--scene", required=False, help="Scene name (default: current)"
)
group_parser.add_argument(
"action",
choices=["list", "show", "hide", "toggle"],
default="list",
nargs="?",
help="list/show/hide/toggle",
)
group_parser.add_argument(
"group", nargs="?", help="group to interact with"
)
item_parser = subparsers.add_parser(
"item",
aliases=["items"],
parents=[_common],
formatter_class=RichHelpFormatter,
)
item_parser.add_argument(
"-s", "--scene", required=False, help="Scene name (default: current)"
)
item_parser.add_argument(
"action",
choices=["list", "show", "hide", "toggle", "screenshot"],
default="list",
nargs="?",
help="list/show/hide/toggle/screenshot",
)
item_parser.add_argument("ITEM", nargs="?", help="Item to interact with")
item_parser.add_argument(
"-o",
"--output",
default=None,
help="Output file (required without --raw/--json)",
)
item_parser.add_argument(
"--raw",
action="store_true",
default=False,
help="Write raw screenshot bytes to stdout",
)
item_parser.add_argument(
"-f",
"--format",
default=None,
help="Image format: png, jpg, bmp (default: from filename ext or png)",
)
item_parser.add_argument(
"--width", type=int, default=None, help="Screenshot width"
)
item_parser.add_argument(
"--height", type=int, default=None, help="Screenshot height"
)
item_parser.add_argument(
"--compression-quality",
type=int,
default=-1,
help="Compression quality -1 to 100 (-1 = OBS default)",
)
input_parser = subparsers.add_parser(
"input",
aliases=["inputs"],
parents=[_common],
formatter_class=RichHelpFormatter,
)
input_parser.add_argument(
"action",
choices=[
"list",
"show",
"get",
"set",
"mute",
"unmute",
"toggle-mute",
"is-muted",
],
default="list",
nargs="?",
help="list/show/get/set/mute/unmute/toggle-mute/is-muted",
)
input_parser.add_argument("INPUT", nargs="?", help="Input name")
input_parser.add_argument("PROPERTY", nargs="?", help="Property name")
input_parser.add_argument("VALUE", nargs="?", help="Property value")
filter_parser = subparsers.add_parser(
"filter",
aliases=["filters"],
parents=[_common],
formatter_class=RichHelpFormatter,
)
filter_parser.add_argument(
"action",
choices=["list", "toggle", "enable", "disable", "status"],
default="list",
nargs="?",
help="list/toggle/enable/disable/status",
)
filter_parser.add_argument("INPUT", nargs="?", help="Input name")
filter_parser.add_argument("FILTER", nargs="?", help="Filter name")
hotkey_parser = subparsers.add_parser(
"hotkey",
aliases=["hotkeys"],
parents=[_common],
formatter_class=RichHelpFormatter,
)
hotkey_parser.add_argument(
"action",
choices=["list", "trigger"],
default="list",
nargs="?",
help="list/trigger",
)
hotkey_parser.add_argument("HOTKEY", nargs="?", help="Hotkey name")
source_parser = subparsers.add_parser(
"source",
aliases=["sources"],
parents=[_common],
formatter_class=RichHelpFormatter,
)
source_parser.add_argument(
"action",
choices=["list", "screenshot", "active"],
default="list",
nargs="?",
help="list/screenshot/active",
)
source_parser.add_argument("SOURCE", nargs="?", help="Source name")
source_parser.add_argument(
"-o",
"--output",
default=None,
help="Output file (required without --raw/--json)",
)
source_parser.add_argument(
"--raw",
action="store_true",
default=False,
help="Write raw screenshot bytes to stdout",
)
source_parser.add_argument(
"-f",
"--format",
default=None,
help="Image format: png, jpg, bmp (default: from filename ext or png)",
)
source_parser.add_argument(
"--width", type=int, default=None, help="Screenshot width"
)
source_parser.add_argument(
"--height", type=int, default=None, help="Screenshot height"
)
source_parser.add_argument(
"--compression-quality",
type=int,
default=-1,
help="Compression quality -1 to 100 (-1 = OBS default)",
)
virtualcam_parser = subparsers.add_parser(
"virtualcam", parents=[_common], formatter_class=RichHelpFormatter
)
virtualcam_parser.add_argument(
"action",
choices=["status", "start", "stop", "toggle"],
default="status",
nargs="?",
help="status/start/stop/toggle",
)
stream_parser = subparsers.add_parser(
"stream", parents=[_common], formatter_class=RichHelpFormatter
)
stream_parser.add_argument(
"action",
choices=["status", "start", "stop", "toggle"],
default="status",
nargs="?",
help="status/start/stop/toggle",
)
record_parser = subparsers.add_parser(
"record", parents=[_common], formatter_class=RichHelpFormatter
)
record_parser.add_argument(
"action",
choices=["status", "start", "stop", "toggle"],
default="status",
nargs="?",
help="status/start/stop/toggle",
)
replay_parser = subparsers.add_parser(
"replay", parents=[_common], formatter_class=RichHelpFormatter
)
replay_parser.add_argument(
"action",
choices=["status", "start", "stop", "toggle", "save"],
default="status",
nargs="?",
help="status/start/stop/toggle",
)
return parser.parse_args()
class ObsItemNotFoundException(ValueError):
pass
class ObsSceneNotFoundException(ValueError):
pass
def get_scene_names(cl):
return sorted(
(scene.get("sceneName") for scene in cl.get_scene_list().scenes)
)
def switch_to_scene(cl, scene, exact=False, ignorecase=True):
if not scene:
raise ValueError("Missing scene name")
regex = re.compile(
(f"^{re.escape(scene)}$" if exact else re.escape(scene)),
re.IGNORECASE if ignorecase else re.NOFLAG,
)
scene_names = get_scene_names(cl)
for scene_name in scene_names:
if re.search(regex, scene_name):
cl.set_current_program_scene(scene_name)
return True
available_scenes = "\n".join(f" - '{name}'" for name in scene_names)
raise ObsSceneNotFoundException(
f"Scene not found: '{scene}'\nAvailable scenes:\n{available_scenes}"
)
def get_items(
cl, scene=None, names_only=False, recurse=True, include_groups=False
):
scene = scene or get_current_scene_name(cl)
items = cl.get_scene_item_list(scene).scene_items
if recurse:
all_items = []
for it in items:
if it.get("isGroup"):
if include_groups:
all_items.append(it)
for grp_it in cl.get_group_scene_item_list(
it.get("sourceName")
).scene_items:
# Inject parent group attribute
grp_it["parentGroup"] = it
all_items.append(grp_it)
else:
all_items.append(it)
items = all_items
items = sorted(
items,
key=lambda x: (
x.get("parentGroup") is None, # Items with parentGroup come first
(
x.get("parentGroup", {}).get("sourceName")
if x.get("parentGroup")
else None
), # Then sort by parentGroup.sourceName
x.get("sourceName"), # Finally, sort by sourceName
),
)
return [x.get("sourceName") for x in items] if names_only else items
def get_groups(cl, scene=None, names_only=False):
scene = scene or get_current_scene_name(cl)
groups = sorted(
[
x
for x in cl.get_scene_item_list(scene).scene_items
if x.get("isGroup", False)
],
key=lambda x: x.get("sourceName"),
)
return [x.get("sourceName") for x in groups] if names_only else groups
def get_item_by_name(
cl, item, ignorecase=True, exact=False, scene=None, is_group=False
):
items = get_items(cl, scene) if not is_group else get_groups(cl, scene)
regex = re.compile(
item if not exact else f"^{item}$",
re.IGNORECASE if ignorecase else re.NOFLAG,
)
for it in items:
if re.search(regex, it.get("sourceName")):
return it
raise ObsItemNotFoundException(
f"Item not found: '{item}' (Scene: '{scene}')"
)
def get_item_id(cl, item, scene=None, is_group=False):
data = get_item_by_name(cl, item, scene=scene, is_group=is_group)
return data.get("sceneItemId", -1)
def get_item_parent(cl, item, scene=None):
data = get_item_by_name(cl, item, scene=scene)
parent_group = data.get("parentGroup")
return parent_group.get("sourceName") if parent_group else scene
def is_item_enabled(cl, item, scene=None, is_group=False):
data = get_item_by_name(cl, item=item, is_group=is_group, scene=scene)
return data.get("sceneItemEnabled")
def show_item(cl, item, scene=None, is_group=False):
scene = scene or get_current_scene_name(cl)
item_id = get_item_id(cl, item=item, scene=scene, is_group=is_group)
parent = scene if is_group else get_item_parent(cl, item, scene)
return cl.set_scene_item_enabled(parent, item_id, True)
def hide_item(cl, item, scene=None, is_group=False):
scene = scene or get_current_scene_name(cl)
item_id = get_item_id(cl, item=item, scene=scene, is_group=is_group)
parent = scene if is_group else get_item_parent(cl, item, scene)
return cl.set_scene_item_enabled(parent, item_id, False)
def toggle_item(cl, item, scene=None, is_group=False):
scene = scene or get_current_scene_name(cl)
item_id = get_item_id(cl, item=item, scene=scene, is_group=is_group)
parent = scene if is_group else get_item_parent(cl, item, scene)
enabled = not is_item_enabled(
cl, item=item, scene=scene, is_group=is_group
)
return cl.set_scene_item_enabled(parent, item_id, enabled)
def get_current_scene_name(cl):
return cl.get_current_program_scene().current_program_scene_name
def get_inputs(cl):
return sorted(cl.get_input_list().inputs, key=lambda x: x.get("inputName"))
def get_input_settings(cl, input):
return cl.get_input_settings(input).input_settings
def set_input_setting(cl, input, key, value):
try:
value = json.loads(value)
except (ValueError, TypeError):
pass
LOGGER.debug(f"Setting {key} to {value} ({type(value)})")
return cl.set_input_settings(input, {key: value}, overlay=True)
def get_mute_state(cl, input):
return cl.get_input_mute(input).input_muted
def mute_input(cl, input):
cl.set_input_mute(input, True)
def unmute_input(cl, input):
cl.set_input_mute(input, False)
def toggle_mute_input(cl, input):
cl.toggle_input_mute(input)
def get_filters(cl, input):
return cl.get_source_filter_list(input).filters
def is_filter_enabled(cl, source, filter):
return cl.get_source_filter(source, filter).filter_enabled
def enable_filter(cl, source, filter):
return cl.set_source_filter_enabled(source, filter, True)
def disable_filter(cl, source, filter):
return cl.set_source_filter_enabled(source, filter, False)
def toggle_filter(cl, source, filter):
enabled = is_filter_enabled(cl, source, filter)
return cl.set_source_filter_enabled(source, filter, not enabled)
def get_hotkeys(cl):
return cl.get_hot_key_list().hotkeys
def trigger_hotkey(cl, hotkey):
return cl.trigger_hot_key_by_name(hotkey)
def virtual_camera_status(cl):
return cl.get_virtual_cam_status().output_active
def virtual_camera_start(cl):
return cl.start_virtual_cam()
def virtual_camera_stop(cl):
return cl.stop_virtual_cam()
def virtual_camera_toggle(cl):
return cl.toggle_virtual_cam()
def stream_status(cl):
return cl.get_stream_status().output_active
def stream_start(cl):
return cl.start_stream()
def stream_stop(cl):
return cl.stop_stream()
def stream_toggle(cl):
return cl.toggle_stream()
def replay_start(cl):
return cl.start_replay_buffer()
def replay_stop(cl):
return cl.stop_replay_buffer()
def replay_save(cl):
return cl.save_replay_buffer()
def replay_toggle(cl):
return cl.toggle_replay_buffer()
def replay_status(cl):
return cl.get_replay_buffer_status().output_active
def record_status(cl):
return cl.get_record_status().output_active
def record_start(cl):
return cl.start_record()
def record_stop(cl):
return cl.stop_record()
def record_toggle(cl):
return cl.toggle_record()
def source_active(cl, source):
res = cl.send("GetSourceActive", {"sourceName": source}, raw=True)
return res.get("videoActive", False), res.get("videoShowing", False)
def take_screenshot(
cl,
source,
image_format="png",
width=None,
height=None,
compression_quality=-1,
):
payload = {
"sourceName": source,
"imageFormat": image_format,
"imageCompressionQuality": compression_quality,
}
if width:
payload["imageWidth"] = width
if height:
payload["imageHeight"] = height
res = cl.send("GetSourceScreenshot", payload)
image_data = res.image_data
# Strip data URI prefix (e.g. "data:image/png;base64,")
if "," in image_data:
image_data = image_data.split(",", 1)[1]
return base64.b64decode(image_data)
_NA = Text("N/A", style="bright_black italic")
_COLUMN_STYLES = (
"cyan",
"green",
"magenta",
"white",
"yellow",
"blue",
"bright_black",
"red",
)
def make_table(*headers):
table = Table(
box=None,
show_edge=False,
pad_edge=False,
padding=(0, 2, 0, 0),
header_style="bold",
)
for i, header in enumerate(headers):
table.add_column(
header.upper(), style=_COLUMN_STYLES[i % len(_COLUMN_STYLES)]
)
return table
def format_info_value(value, suffix=None):
if value is None:
return _NA
if isinstance(value, bool):
if value:
return Text("enabled", style="bold green")
return Text("disabled", style="bold red")
if isinstance(value, float):
value = f"{value:.2f}".rstrip("0").rstrip(".")
if isinstance(value, Text):
return value
text = str(value)
if suffix:
text = f"{text} {suffix}"
return Text(text)
def make_info_panel(title, rows, border_style):
table = Table.grid(expand=True)
table.add_column(style="cyan", no_wrap=True)
table.add_column(style="white")
for key, value, *rest in rows:
suffix = rest[0] if rest else None
table.add_row(key, format_info_value(value, suffix=suffix))
return Panel(
table,
title=title,
border_style=border_style,
padding=(0, 1),
)
def use_pretty_output(args):
return bool(getattr(args, "pretty", False)) and not args.json
def render_pretty_panels(console, panels):
if not panels:
return
console.print(Columns(panels, expand=True, equal=True))
def render_pretty_hotkeys(console, hotkeys):
rows = tuple(
(str(index + 1), hotkey) for index, hotkey in enumerate(hotkeys)
)
console.print(make_info_panel("Hotkeys", rows, "yellow"))
def print_error(console, message):
console.print(f"[bold red]ERROR:[/bold red] {message}")
def main():
console = Console()
error_console = Console(stderr=True)
logging.basicConfig()
args = parse_args()
LOGGER.setLevel(logging.DEBUG if args.debug else logging.INFO)
LOGGER.debug(args)
try:
cl = obs.ReqClient(
host=args.host,
port=args.port,
password=args.password,
)
_aliases = {
"scenes": "scene",
"groups": "group",
"items": "item",
"inputs": "input",
"filters": "filter",
"hotkeys": "hotkey",
"sources": "source",
}
cmd = _aliases.get(args.command, args.command)
if cmd == "info":
data = get_obs_info(cl)
if args.json:
print_json(data=data)
return
if use_pretty_output(args):
obs_panel = make_info_panel(
"OBS Studio",
(
("version", data["obs"].get("version")),
(
"websocket",
data["obs"].get("websocket_version"),
),
("rpc", data["obs"].get("rpc_version")),
("platform", data["obs"].get("platform")),
(
"platform desc",
data["obs"].get("platform_description"),
),
(
"studio mode",
data["obs"].get("studio_mode_enabled"),
),
),
"green",
)
video_panel = make_info_panel(
"Video",
(
(
"base res",
data["video"].get("base_resolution"),
),
(
"output res",
data["video"].get("output_resolution"),
),
("fps", data["video"].get("fps")),
(
"fps ratio",
(
(
f"{data['video'].get('fps_numerator')}/"
f"{data['video'].get('fps_denominator')}"
)
if data["video"].get("fps_numerator")
is not None
and data["video"].get("fps_denominator")
is not None
else None
),
),
),
"cyan",
)
stats_panel = make_info_panel(
"Runtime Stats",
(
("active fps", data["stats"].get("active_fps")),
("cpu usage", data["stats"].get("cpu_usage"), "%"),
("memory", data["stats"].get("memory_usage"), "MB"),
(
"disk free",
data["stats"].get("available_disk_space"),
"GB",
),
(
"render skipped",
data["stats"].get("render_skipped_frames"),
),
(
"render total",
data["stats"].get("render_total_frames"),
),
(
"output skipped",
data["stats"].get("output_skipped_frames"),
),
(
"output total",
data["stats"].get("output_total_frames"),
),
(
"frame render",
data["stats"].get("average_frame_render_time"),
"ms",
),
),
"magenta",
)
console.print(Columns((obs_panel, video_panel), expand=True))
console.print(stats_panel)
return
table = make_table("property", "value")
rows = (
("obs version", data["obs"].get("version")),
(
"websocket version",
data["obs"].get("websocket_version"),
),
("rpc version", data["obs"].get("rpc_version")),
("platform", data["obs"].get("platform")),
(
"platform description",
data["obs"].get("platform_description"),
),
(
"studio mode",
str(data["obs"].get("studio_mode_enabled")).lower(),
),
(
"base resolution",
data["video"].get("base_resolution"),
),