-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvirtual-camera-toggle.py
More file actions
executable file
·315 lines (264 loc) · 10.2 KB
/
virtual-camera-toggle.py
File metadata and controls
executable file
·315 lines (264 loc) · 10.2 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
#!/usr/bin/env python3
"""
Virtual Camera Toggle - System tray app to control OBS virtual camera
Toggles OBS virtual camera on/off with Super+O keybind or tray icon click
"""
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('AppIndicator3', '0.1')
from gi.repository import Gtk, GLib, AppIndicator3
import subprocess
import os
import sys
import json
import socket
import time
class VirtualCameraToggle:
def __init__(self):
self.obs_process = None
self.obs_pid = None
self.camera_active = False
self.obs_websocket_port = 4455 # Default OBS websocket port
# Create indicator
self.indicator = AppIndicator3.Indicator.new(
"virtual-camera-toggle",
"camera-web", # Icon name from theme
AppIndicator3.IndicatorCategory.APPLICATION_STATUS
)
self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
self.indicator.set_title("Virtual Camera")
# Create menu
self.menu = Gtk.Menu()
# Status item
self.status_item = Gtk.MenuItem(label="Virtual Camera: Off")
self.status_item.set_sensitive(False)
self.menu.append(self.status_item)
# Separator
separator = Gtk.SeparatorMenuItem()
self.menu.append(separator)
# Toggle item
self.toggle_item = Gtk.MenuItem(label="Start Virtual Camera")
self.toggle_item.connect("activate", self.on_toggle)
self.menu.append(self.toggle_item)
# Separator
separator2 = Gtk.SeparatorMenuItem()
self.menu.append(separator2)
# Quit item
quit_item = Gtk.MenuItem(label="Quit")
quit_item.connect("activate", self.on_quit)
self.menu.append(quit_item)
self.menu.show_all()
self.indicator.set_menu(self.menu)
# Update icon
self.update_icon()
# Check if OBS is already running
self.check_obs_running()
# Set up periodic check (every 2 seconds)
GLib.timeout_add_seconds(2, self.periodic_check)
def check_obs_running(self):
"""Check if OBS is already running"""
try:
result = subprocess.run(
["pgrep", "-x", "obs"],
capture_output=True,
text=True
)
if result.returncode == 0:
self.obs_pid = int(result.stdout.strip().split('\n')[0])
print(f"OBS already running with PID: {self.obs_pid}")
# Check if virtual camera is active
self.check_virtual_camera_status()
return True
return False
except Exception as e:
print(f"Error checking OBS status: {e}")
return False
def check_virtual_camera_status(self):
"""Check if virtual camera is currently active"""
try:
# Check if /dev/video0 is being used by OBS
result = subprocess.run(
["fuser", "/dev/video0"],
capture_output=True,
text=True,
timeout=2
)
if result.returncode == 0 and result.stdout.strip():
# Something is using the virtual camera
self.camera_active = True
self.update_status(True)
return True
else:
self.camera_active = False
self.update_status(False)
return False
except Exception as e:
print(f"Error checking virtual camera status: {e}")
return False
def periodic_check(self):
"""Periodic check of OBS and camera status"""
# Check if OBS process is still running
if self.obs_pid:
try:
os.kill(self.obs_pid, 0) # Check if process exists
except OSError:
# Process died
print("OBS process terminated")
self.obs_pid = None
self.camera_active = False
self.update_status(False)
# Check virtual camera status
if self.obs_pid:
self.check_virtual_camera_status()
return True # Continue periodic checks
def start_obs_virtual_camera(self):
"""Start OBS in background with virtual camera enabled"""
try:
# Start OBS minimized to tray with virtual camera
self.obs_process = subprocess.Popen(
["/usr/bin/obs", "--startvirtualcam", "--minimize-to-tray"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
self.obs_pid = self.obs_process.pid
print(f"Started OBS with PID: {self.obs_pid}")
# Wait a bit for OBS to start
time.sleep(2)
# Check if virtual camera started
GLib.timeout_add(1000, self.check_virtual_camera_started)
except Exception as e:
print(f"Error starting OBS: {e}")
self.show_error_notification(f"Failed to start OBS: {e}")
def check_virtual_camera_started(self):
"""Check if virtual camera actually started"""
if self.check_virtual_camera_status():
self.show_notification("Virtual Camera Started", "OBS virtual camera is now active")
return False # Don't repeat
def stop_obs_virtual_camera(self):
"""Stop OBS virtual camera"""
if self.obs_pid:
try:
# Send SIGTERM to gracefully close OBS
os.kill(self.obs_pid, 15)
print(f"Sent SIGTERM to OBS (PID: {self.obs_pid})")
# Wait for process to terminate
GLib.timeout_add(500, self.check_obs_terminated)
except Exception as e:
print(f"Error stopping OBS: {e}")
self.show_error_notification(f"Failed to stop OBS: {e}")
def check_obs_terminated(self):
"""Check if OBS terminated after stop command"""
try:
os.kill(self.obs_pid, 0)
# Still running, check again
return True
except OSError:
# Process terminated
print("OBS terminated successfully")
self.obs_pid = None
self.camera_active = False
self.update_status(False)
self.show_notification("Virtual Camera Stopped", "OBS virtual camera is now inactive")
return False
def on_toggle(self, widget=None):
"""Toggle virtual camera on/off"""
if self.camera_active or self.obs_pid:
self.stop_obs_virtual_camera()
else:
self.start_obs_virtual_camera()
def update_status(self, active):
"""Update menu items and icon based on camera status"""
self.camera_active = active
if active:
self.status_item.set_label("Virtual Camera: On")
self.toggle_item.set_label("Stop Virtual Camera")
else:
self.status_item.set_label("Virtual Camera: Off")
self.toggle_item.set_label("Start Virtual Camera")
self.update_icon()
def update_icon(self):
"""Update tray icon based on status"""
if self.camera_active:
# Camera active - use full icon
self.indicator.set_icon_full("camera-web", "Virtual Camera Active")
else:
# Camera inactive - use symbolic icon
self.indicator.set_icon_full("camera-web-symbolic", "Virtual Camera Inactive")
def show_notification(self, title, message):
"""Show desktop notification"""
try:
subprocess.run(
["notify-send", "-i", "camera-web", title, message],
timeout=2
)
except Exception as e:
print(f"Error showing notification: {e}")
def show_error_notification(self, message):
"""Show error notification"""
try:
subprocess.run(
["notify-send", "-i", "dialog-error", "Virtual Camera Error", message],
timeout=2
)
except Exception as e:
print(f"Error showing error notification: {e}")
def on_quit(self, widget):
"""Quit application"""
# Stop OBS if we started it
if self.obs_pid:
self.stop_obs_virtual_camera()
Gtk.main_quit()
def check_single_instance():
"""Check if another instance is already running"""
lock_file = "/tmp/virtual-camera-toggle.lock"
try:
# Try to create lock file
if os.path.exists(lock_file):
# Check if the process in lock file is still running
with open(lock_file, 'r') as f:
old_pid = int(f.read().strip())
try:
os.kill(old_pid, 0)
# Process is still running
print("Another instance is already running. Sending toggle signal.")
# Send SIGUSR1 to toggle the other instance
os.kill(old_pid, 10) # SIGUSR1
return False
except OSError:
# Process is dead, remove stale lock
os.remove(lock_file)
# Create new lock file with our PID
with open(lock_file, 'w') as f:
f.write(str(os.getpid()))
return True
except Exception as e:
print(f"Error checking single instance: {e}")
return True
def handle_toggle_signal(signum, frame):
"""Handle SIGUSR1 signal to toggle camera"""
if hasattr(handle_toggle_signal, 'app'):
GLib.idle_add(handle_toggle_signal.app.on_toggle)
def main():
# Check for single instance
if not check_single_instance():
print("Toggling existing instance...")
sys.exit(0)
# Create app
app = VirtualCameraToggle()
# Store app reference for signal handler
handle_toggle_signal.app = app
# Set up signal handler for toggle
import signal
signal.signal(signal.SIGUSR1, handle_toggle_signal)
# Clean up lock file on exit
import atexit
atexit.register(lambda: os.path.exists("/tmp/virtual-camera-toggle.lock") and os.remove("/tmp/virtual-camera-toggle.lock"))
print("Virtual Camera Toggle started. Press Super+O to toggle.")
# Start GTK main loop
try:
Gtk.main()
except KeyboardInterrupt:
print("Exiting...")
app.on_quit(None)
if __name__ == "__main__":
main()