Update app.py
Browse files
app.py
CHANGED
|
@@ -9,10 +9,7 @@ import concurrent.futures
|
|
| 9 |
import threading
|
| 10 |
import numpy as np
|
| 11 |
import uuid
|
| 12 |
-
import
|
| 13 |
-
import fcntl
|
| 14 |
-
import termios
|
| 15 |
-
import struct
|
| 16 |
from aiohttp import web
|
| 17 |
from aiortc import RTCPeerConnection, RTCSessionDescription, VideoStreamTrack, RTCIceServer, RTCConfiguration
|
| 18 |
from av import VideoFrame
|
|
@@ -32,7 +29,7 @@ TURN_USER = "g08abe68c81a07f098bb5f0914549bb32440e5aad0b216c7fba2b61e76fd62c6"
|
|
| 32 |
TURN_PASS = "aed1a10dd10eba9401ad9d99e5c66036d8a970eab5ba8e6dc9845ab57c771a7d"
|
| 33 |
|
| 34 |
logging.basicConfig(level=logging.WARNING)
|
| 35 |
-
logger = logging.getLogger("WebRTC-
|
| 36 |
|
| 37 |
executor = concurrent.futures.ThreadPoolExecutor(max_workers=16)
|
| 38 |
thread_local_storage = threading.local()
|
|
@@ -42,139 +39,6 @@ config = {
|
|
| 42 |
"height": DEFAULT_HEIGHT
|
| 43 |
}
|
| 44 |
|
| 45 |
-
class ClipboardManager:
|
| 46 |
-
def __init__(self):
|
| 47 |
-
self.last_content = ""
|
| 48 |
-
self.channels = set()
|
| 49 |
-
self.lock = threading.Lock()
|
| 50 |
-
self.running = True
|
| 51 |
-
self.thread = threading.Thread(target=self.monitor_loop, daemon=True)
|
| 52 |
-
self.thread.start()
|
| 53 |
-
|
| 54 |
-
def add_channel(self, channel):
|
| 55 |
-
with self.lock:
|
| 56 |
-
self.channels.add(channel)
|
| 57 |
-
|
| 58 |
-
def remove_channel(self, channel):
|
| 59 |
-
with self.lock:
|
| 60 |
-
self.channels.discard(channel)
|
| 61 |
-
|
| 62 |
-
def update_x11(self, content):
|
| 63 |
-
if content == self.last_content:
|
| 64 |
-
return
|
| 65 |
-
|
| 66 |
-
self.last_content = content
|
| 67 |
-
try:
|
| 68 |
-
env = os.environ.copy()
|
| 69 |
-
env["DISPLAY"] = DISPLAY_NUM
|
| 70 |
-
|
| 71 |
-
p = subprocess.Popen(
|
| 72 |
-
['xclip', '-i', '-selection', 'clipboard'],
|
| 73 |
-
stdin=subprocess.PIPE,
|
| 74 |
-
env=env
|
| 75 |
-
)
|
| 76 |
-
p.communicate(input=content.encode('utf-8'))
|
| 77 |
-
except Exception as e:
|
| 78 |
-
logger.error(f"Clipboard Write Error: {e}")
|
| 79 |
-
|
| 80 |
-
def monitor_loop(self):
|
| 81 |
-
while self.running:
|
| 82 |
-
try:
|
| 83 |
-
if not os.environ.get("DISPLAY"):
|
| 84 |
-
os.environ["DISPLAY"] = DISPLAY_NUM
|
| 85 |
-
|
| 86 |
-
try:
|
| 87 |
-
curr = subprocess.check_output(
|
| 88 |
-
['xclip', '-o', '-selection', 'clipboard'],
|
| 89 |
-
stderr=subprocess.DEVNULL,
|
| 90 |
-
timeout=0.5
|
| 91 |
-
).decode('utf-8')
|
| 92 |
-
except:
|
| 93 |
-
curr = ""
|
| 94 |
-
|
| 95 |
-
if curr and curr != self.last_content:
|
| 96 |
-
self.last_content = curr
|
| 97 |
-
self.broadcast(curr)
|
| 98 |
-
|
| 99 |
-
except Exception:
|
| 100 |
-
pass
|
| 101 |
-
time.sleep(1.0)
|
| 102 |
-
|
| 103 |
-
def broadcast(self, content):
|
| 104 |
-
msg = json.dumps({"type": "clipboard", "content": content})
|
| 105 |
-
with self.lock:
|
| 106 |
-
for ch in list(self.channels):
|
| 107 |
-
try:
|
| 108 |
-
if ch.readyState == "open":
|
| 109 |
-
ch.send(msg)
|
| 110 |
-
else:
|
| 111 |
-
self.channels.discard(ch)
|
| 112 |
-
except:
|
| 113 |
-
self.channels.discard(ch)
|
| 114 |
-
|
| 115 |
-
clipboard_manager = ClipboardManager()
|
| 116 |
-
|
| 117 |
-
class Terminal:
|
| 118 |
-
def __init__(self, channel):
|
| 119 |
-
self.channel = channel
|
| 120 |
-
self.master_fd, self.slave_fd = pty.openpty()
|
| 121 |
-
self.pid = os.fork()
|
| 122 |
-
|
| 123 |
-
if self.pid == 0:
|
| 124 |
-
os.close(self.master_fd)
|
| 125 |
-
os.setsid()
|
| 126 |
-
os.dup2(self.slave_fd, 0)
|
| 127 |
-
os.dup2(self.slave_fd, 1)
|
| 128 |
-
os.dup2(self.slave_fd, 2)
|
| 129 |
-
if self.slave_fd > 2:
|
| 130 |
-
os.close(self.slave_fd)
|
| 131 |
-
|
| 132 |
-
os.environ["TERM"] = "xterm-256color"
|
| 133 |
-
os.environ["DISPLAY"] = DISPLAY_NUM
|
| 134 |
-
os.environ["HOME"] = "/home/user"
|
| 135 |
-
|
| 136 |
-
shell = "/bin/bash"
|
| 137 |
-
os.execl(shell, shell)
|
| 138 |
-
else:
|
| 139 |
-
os.close(self.slave_fd)
|
| 140 |
-
self.loop = asyncio.get_running_loop()
|
| 141 |
-
self.loop.add_reader(self.master_fd, self.read_output)
|
| 142 |
-
self.channel.on("close", self.close)
|
| 143 |
-
|
| 144 |
-
def read_output(self):
|
| 145 |
-
try:
|
| 146 |
-
data = os.read(self.master_fd, 4096)
|
| 147 |
-
if data:
|
| 148 |
-
self.channel.send(data.decode('utf-8', 'ignore'))
|
| 149 |
-
except OSError:
|
| 150 |
-
self.close()
|
| 151 |
-
|
| 152 |
-
def write_input(self, data):
|
| 153 |
-
if self.master_fd:
|
| 154 |
-
try:
|
| 155 |
-
if data.startswith('{"type":"resize"'):
|
| 156 |
-
try:
|
| 157 |
-
cmd = json.loads(data)
|
| 158 |
-
self.resize(cmd.get("rows", 24), cmd.get("cols", 80))
|
| 159 |
-
except: pass
|
| 160 |
-
else:
|
| 161 |
-
os.write(self.master_fd, data.encode('utf-8'))
|
| 162 |
-
except Exception as e:
|
| 163 |
-
logger.error(f"PTY Write Error: {e}")
|
| 164 |
-
|
| 165 |
-
def resize(self, rows, cols):
|
| 166 |
-
try:
|
| 167 |
-
winsize = struct.pack("HHHH", rows, cols, 0, 0)
|
| 168 |
-
fcntl.ioctl(self.master_fd, termios.TIOCSWINSZ, winsize)
|
| 169 |
-
except: pass
|
| 170 |
-
|
| 171 |
-
def close(self):
|
| 172 |
-
try:
|
| 173 |
-
self.loop.remove_reader(self.master_fd)
|
| 174 |
-
os.close(self.master_fd)
|
| 175 |
-
os.kill(self.pid, 9)
|
| 176 |
-
except: pass
|
| 177 |
-
|
| 178 |
class InputManager:
|
| 179 |
def __init__(self):
|
| 180 |
self.process = None
|
|
@@ -182,30 +46,36 @@ class InputManager:
|
|
| 182 |
self.scroll_accum = 0
|
| 183 |
|
| 184 |
def start_process(self):
|
| 185 |
-
if not os.environ.get("DISPLAY"):
|
|
|
|
|
|
|
| 186 |
try:
|
| 187 |
-
self.process = subprocess.Popen(
|
| 188 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
|
| 190 |
def _send_raw(self, command):
|
| 191 |
-
if self.process is None or self.process.poll() is not None:
|
|
|
|
|
|
|
| 192 |
if self.process:
|
| 193 |
try:
|
| 194 |
self.process.stdin.write(command + "\n")
|
| 195 |
self.process.stdin.flush()
|
| 196 |
-
except:
|
| 197 |
try: self.process.kill()
|
| 198 |
except: pass
|
| 199 |
self.process = None
|
| 200 |
|
| 201 |
def send(self, command):
|
| 202 |
-
with self.lock:
|
|
|
|
| 203 |
|
| 204 |
-
def mouse_move(self, x, y): self.send(f"mousemove {x} {y}")
|
| 205 |
-
def mouse_down(self, btn): self.send(f"mousedown {btn}")
|
| 206 |
-
def mouse_up(self, btn): self.send(f"mouseup {btn}")
|
| 207 |
-
def key_down(self, key): self.send(f"keydown {key}")
|
| 208 |
-
def key_up(self, key): self.send(f"keyup {key}")
|
| 209 |
def scroll(self, dy):
|
| 210 |
with self.lock:
|
| 211 |
self.scroll_accum += dy
|
|
@@ -217,85 +87,205 @@ class InputManager:
|
|
| 217 |
self._send_raw("click 4")
|
| 218 |
self.scroll_accum += THRESHOLD
|
| 219 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
input_manager = InputManager()
|
| 221 |
|
| 222 |
def start_system():
|
| 223 |
os.environ["DISPLAY"] = DISPLAY_NUM
|
|
|
|
| 224 |
if not shutil.which("Xvfb"): raise FileNotFoundError("Xvfb missing")
|
| 225 |
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
input_manager.start_process()
|
|
|
|
| 230 |
set_resolution(DEFAULT_WIDTH, DEFAULT_HEIGHT)
|
| 231 |
-
|
| 232 |
if shutil.which("matchbox-window-manager"):
|
| 233 |
subprocess.Popen("matchbox-window-manager -use_titlebar no", shell=True)
|
| 234 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
def set_resolution(w, h):
|
| 236 |
try:
|
| 237 |
if w % 2 != 0: w += 1
|
| 238 |
if h % 2 != 0: h += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
config["width"] = w
|
| 240 |
config["height"] = h
|
| 241 |
-
except
|
|
|
|
| 242 |
|
| 243 |
class VirtualScreenTrack(VideoStreamTrack):
|
| 244 |
kind = "video"
|
| 245 |
def __init__(self):
|
| 246 |
super().__init__()
|
| 247 |
self.last_frame_time = 0
|
|
|
|
| 248 |
|
| 249 |
def _capture(self):
|
| 250 |
try:
|
| 251 |
if not hasattr(thread_local_storage, "sct"):
|
| 252 |
thread_local_storage.sct = mss.mss()
|
|
|
|
| 253 |
monitor = {"top": 0, "left": 0, "width": config["width"], "height": config["height"]}
|
| 254 |
-
|
|
|
|
|
|
|
| 255 |
except: return None
|
| 256 |
|
| 257 |
async def recv(self):
|
| 258 |
FPS = 30
|
| 259 |
FRAME_TIME = 1.0 / FPS
|
|
|
|
| 260 |
pts, time_base = await self.next_timestamp()
|
| 261 |
|
| 262 |
current_time = time.time()
|
| 263 |
wait = FRAME_TIME - (current_time - self.last_frame_time)
|
| 264 |
-
if wait > 0:
|
|
|
|
|
|
|
| 265 |
self.last_frame_time = time.time()
|
| 266 |
|
| 267 |
frame = await asyncio.get_event_loop().run_in_executor(executor, self._capture)
|
|
|
|
| 268 |
if frame is None:
|
| 269 |
blank = np.zeros((config["height"], config["width"], 3), dtype=np.uint8)
|
| 270 |
av_frame = VideoFrame.from_ndarray(blank, format="bgr24")
|
| 271 |
else:
|
| 272 |
av_frame = VideoFrame.from_ndarray(frame, format="bgr24")
|
| 273 |
-
|
| 274 |
av_frame.pts = pts
|
| 275 |
av_frame.time_base = time_base
|
| 276 |
return av_frame
|
| 277 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
def process_input(data):
|
| 279 |
try:
|
| 280 |
msg = json.loads(data)
|
| 281 |
t = msg.get("type")
|
| 282 |
-
w, h = config["width"], config["height"]
|
| 283 |
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
input_manager.mouse_down({0:1, 1:2, 2:3}.get(msg.get("button"), 1))
|
| 290 |
-
elif t == "mouseup":
|
| 291 |
input_manager.mouse_up({0:1, 1:2, 2:3}.get(msg.get("button"), 1))
|
| 292 |
-
elif t == "keydown":
|
| 293 |
-
input_manager.key_down(msg.get("key"))
|
| 294 |
-
elif t == "keyup":
|
| 295 |
-
input_manager.key_up(msg.get("key"))
|
| 296 |
elif t == "wheel":
|
| 297 |
input_manager.scroll(msg.get("deltaY", 0))
|
| 298 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
|
| 300 |
async def offer(request):
|
| 301 |
try:
|
|
@@ -305,7 +295,7 @@ async def offer(request):
|
|
| 305 |
|
| 306 |
pc = RTCPeerConnection(RTCConfiguration(iceServers=[
|
| 307 |
RTCIceServer(urls=["turns:turn.cloudflare.com:443?transport=tcp", "turn:turn.cloudflare.com:3478?transport=udp"], username=TURN_USER, credential=TURN_PASS),
|
| 308 |
-
RTCIceServer(urls=["stun:stun.l.google.com:19302"])
|
| 309 |
]))
|
| 310 |
pcs.add(pc)
|
| 311 |
|
|
@@ -317,21 +307,17 @@ async def offer(request):
|
|
| 317 |
|
| 318 |
@pc.on("datachannel")
|
| 319 |
def on_dc(channel):
|
| 320 |
-
|
| 321 |
-
clipboard_manager.add_channel(channel)
|
| 322 |
-
channel.on("message", lambda m: asyncio.get_event_loop().run_in_executor(executor, process_input, m))
|
| 323 |
-
channel.on("close", lambda: clipboard_manager.remove_channel(channel))
|
| 324 |
-
elif channel.label == "terminal":
|
| 325 |
-
term = Terminal(channel)
|
| 326 |
-
channel.on("message", term.write_input)
|
| 327 |
|
| 328 |
pc.addTrack(VirtualScreenTrack())
|
| 329 |
await pc.setRemoteDescription(offer)
|
| 330 |
answer = await pc.createAnswer()
|
| 331 |
await pc.setLocalDescription(answer)
|
| 332 |
-
return web.Response(content_type="application/json", text=json.dumps({"sdp": pc.localDescription.sdp, "type": pc.localDescription.type}), headers={"Access-Control-Allow-Origin": "*"})
|
| 333 |
|
| 334 |
-
|
|
|
|
|
|
|
|
|
|
| 335 |
async def options(r): return web.Response(headers={"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type"})
|
| 336 |
|
| 337 |
pcs = set()
|
|
|
|
| 9 |
import threading
|
| 10 |
import numpy as np
|
| 11 |
import uuid
|
| 12 |
+
import psutil
|
|
|
|
|
|
|
|
|
|
| 13 |
from aiohttp import web
|
| 14 |
from aiortc import RTCPeerConnection, RTCSessionDescription, VideoStreamTrack, RTCIceServer, RTCConfiguration
|
| 15 |
from av import VideoFrame
|
|
|
|
| 29 |
TURN_PASS = "aed1a10dd10eba9401ad9d99e5c66036d8a970eab5ba8e6dc9845ab57c771a7d"
|
| 30 |
|
| 31 |
logging.basicConfig(level=logging.WARNING)
|
| 32 |
+
logger = logging.getLogger("WebRTC-Antigravity")
|
| 33 |
|
| 34 |
executor = concurrent.futures.ThreadPoolExecutor(max_workers=16)
|
| 35 |
thread_local_storage = threading.local()
|
|
|
|
| 39 |
"height": DEFAULT_HEIGHT
|
| 40 |
}
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
class InputManager:
|
| 43 |
def __init__(self):
|
| 44 |
self.process = None
|
|
|
|
| 46 |
self.scroll_accum = 0
|
| 47 |
|
| 48 |
def start_process(self):
|
| 49 |
+
if not os.environ.get("DISPLAY"):
|
| 50 |
+
return
|
| 51 |
+
|
| 52 |
try:
|
| 53 |
+
self.process = subprocess.Popen(
|
| 54 |
+
['xdotool', '-'],
|
| 55 |
+
stdin=subprocess.PIPE,
|
| 56 |
+
encoding='utf-8',
|
| 57 |
+
bufsize=0
|
| 58 |
+
)
|
| 59 |
+
except Exception as e:
|
| 60 |
+
logger.error(f"Failed to start xdotool: {e}")
|
| 61 |
|
| 62 |
def _send_raw(self, command):
|
| 63 |
+
if self.process is None or self.process.poll() is not None:
|
| 64 |
+
self.start_process()
|
| 65 |
+
|
| 66 |
if self.process:
|
| 67 |
try:
|
| 68 |
self.process.stdin.write(command + "\n")
|
| 69 |
self.process.stdin.flush()
|
| 70 |
+
except Exception:
|
| 71 |
try: self.process.kill()
|
| 72 |
except: pass
|
| 73 |
self.process = None
|
| 74 |
|
| 75 |
def send(self, command):
|
| 76 |
+
with self.lock:
|
| 77 |
+
self._send_raw(command)
|
| 78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
def scroll(self, dy):
|
| 80 |
with self.lock:
|
| 81 |
self.scroll_accum += dy
|
|
|
|
| 87 |
self._send_raw("click 4")
|
| 88 |
self.scroll_accum += THRESHOLD
|
| 89 |
|
| 90 |
+
def mouse_move(self, x, y): self.send(f"mousemove {x} {y}")
|
| 91 |
+
def mouse_down(self, btn): self.send(f"mousedown {btn}")
|
| 92 |
+
def mouse_up(self, btn): self.send(f"mouseup {btn}")
|
| 93 |
+
def click(self, btn, repeat=1): self.send(f"click --repeat {repeat} {btn}")
|
| 94 |
+
def key_down(self, key): self.send(f"keydown {key}")
|
| 95 |
+
def key_up(self, key): self.send(f"keyup {key}")
|
| 96 |
+
|
| 97 |
input_manager = InputManager()
|
| 98 |
|
| 99 |
def start_system():
|
| 100 |
os.environ["DISPLAY"] = DISPLAY_NUM
|
| 101 |
+
|
| 102 |
if not shutil.which("Xvfb"): raise FileNotFoundError("Xvfb missing")
|
| 103 |
|
| 104 |
+
subprocess.Popen([
|
| 105 |
+
"Xvfb", DISPLAY_NUM,
|
| 106 |
+
"-screen", "0", f"{MAX_WIDTH}x{MAX_HEIGHT}x24",
|
| 107 |
+
"-ac", "-noreset"
|
| 108 |
+
])
|
| 109 |
+
|
| 110 |
+
time.sleep(3)
|
| 111 |
+
|
| 112 |
input_manager.start_process()
|
| 113 |
+
|
| 114 |
set_resolution(DEFAULT_WIDTH, DEFAULT_HEIGHT)
|
| 115 |
+
|
| 116 |
if shutil.which("matchbox-window-manager"):
|
| 117 |
subprocess.Popen("matchbox-window-manager -use_titlebar no", shell=True)
|
| 118 |
|
| 119 |
+
threading.Thread(target=maintain_antigravity, daemon=True).start()
|
| 120 |
+
|
| 121 |
+
def maintain_antigravity():
|
| 122 |
+
while True:
|
| 123 |
+
chrome_running = False
|
| 124 |
+
for proc in psutil.process_iter(['name']):
|
| 125 |
+
try:
|
| 126 |
+
if 'chrome' in proc.info['name']:
|
| 127 |
+
chrome_running = True
|
| 128 |
+
break
|
| 129 |
+
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
|
| 130 |
+
pass
|
| 131 |
+
|
| 132 |
+
if not chrome_running:
|
| 133 |
+
subprocess.Popen(["python", "-m", "antigravity"])
|
| 134 |
+
time.sleep(5)
|
| 135 |
+
|
| 136 |
+
time.sleep(2)
|
| 137 |
+
|
| 138 |
+
def get_xrandr_output_name():
|
| 139 |
+
try:
|
| 140 |
+
out = subprocess.check_output(["xrandr"]).decode()
|
| 141 |
+
for line in out.splitlines():
|
| 142 |
+
if " connected" in line:
|
| 143 |
+
return line.split()[0]
|
| 144 |
+
except: pass
|
| 145 |
+
return "screen"
|
| 146 |
+
|
| 147 |
+
def get_cvt_modeline(width, height, rate=60):
|
| 148 |
+
H_BLANK = 160
|
| 149 |
+
H_SYNC = 32
|
| 150 |
+
H_FRONT_PORCH = 48
|
| 151 |
+
V_FRONT_PORCH = 3
|
| 152 |
+
V_SYNC = 5
|
| 153 |
+
MIN_V_BLANK = 460
|
| 154 |
+
|
| 155 |
+
frame_time_us = 1000000.0 / rate
|
| 156 |
+
active_time_us = frame_time_us - MIN_V_BLANK
|
| 157 |
+
if active_time_us <= 0: return None
|
| 158 |
+
|
| 159 |
+
h_period_us = active_time_us / height
|
| 160 |
+
v_blank_lines = int(MIN_V_BLANK / h_period_us) + 1
|
| 161 |
+
v_total = height + v_blank_lines
|
| 162 |
+
h_total = width + H_BLANK
|
| 163 |
+
pclk = (h_total * v_total * rate) / 1000000.0
|
| 164 |
+
|
| 165 |
+
h_sync_start = width + H_FRONT_PORCH
|
| 166 |
+
h_sync_end = h_sync_start + H_SYNC
|
| 167 |
+
v_sync_start = height + V_FRONT_PORCH
|
| 168 |
+
v_sync_end = v_sync_start + V_SYNC
|
| 169 |
+
|
| 170 |
+
return f'"{width}x{height}_60.00" {pclk:.2f} {width} {h_sync_start} {h_sync_end} {h_total} {height} {v_sync_start} {v_sync_end} {v_total} +hsync -vsync'
|
| 171 |
+
|
| 172 |
def set_resolution(w, h):
|
| 173 |
try:
|
| 174 |
if w % 2 != 0: w += 1
|
| 175 |
if h % 2 != 0: h += 1
|
| 176 |
+
|
| 177 |
+
output = get_xrandr_output_name()
|
| 178 |
+
mode_name = f"WEB_{w}x{h}_{str(uuid.uuid4())[:4]}"
|
| 179 |
+
modeline_str = get_cvt_modeline(w, h)
|
| 180 |
+
if not modeline_str: return
|
| 181 |
+
|
| 182 |
+
parts = modeline_str.split()
|
| 183 |
+
mode_params = parts[1:]
|
| 184 |
+
|
| 185 |
+
subprocess.run(["xrandr", "--newmode", mode_name] + mode_params, check=True)
|
| 186 |
+
subprocess.run(["xrandr", "--addmode", output, mode_name], check=True)
|
| 187 |
+
subprocess.run(["xrandr", "--output", output, "--mode", mode_name], check=True)
|
| 188 |
+
|
| 189 |
config["width"] = w
|
| 190 |
config["height"] = h
|
| 191 |
+
except Exception as e:
|
| 192 |
+
logger.error(f"Resolution setup failed: {e}")
|
| 193 |
|
| 194 |
class VirtualScreenTrack(VideoStreamTrack):
|
| 195 |
kind = "video"
|
| 196 |
def __init__(self):
|
| 197 |
super().__init__()
|
| 198 |
self.last_frame_time = 0
|
| 199 |
+
self.frame_count = 0
|
| 200 |
|
| 201 |
def _capture(self):
|
| 202 |
try:
|
| 203 |
if not hasattr(thread_local_storage, "sct"):
|
| 204 |
thread_local_storage.sct = mss.mss()
|
| 205 |
+
|
| 206 |
monitor = {"top": 0, "left": 0, "width": config["width"], "height": config["height"]}
|
| 207 |
+
sct_img = thread_local_storage.sct.grab(monitor)
|
| 208 |
+
img = np.array(sct_img)
|
| 209 |
+
return img[..., :3]
|
| 210 |
except: return None
|
| 211 |
|
| 212 |
async def recv(self):
|
| 213 |
FPS = 30
|
| 214 |
FRAME_TIME = 1.0 / FPS
|
| 215 |
+
|
| 216 |
pts, time_base = await self.next_timestamp()
|
| 217 |
|
| 218 |
current_time = time.time()
|
| 219 |
wait = FRAME_TIME - (current_time - self.last_frame_time)
|
| 220 |
+
if wait > 0:
|
| 221 |
+
await asyncio.sleep(wait)
|
| 222 |
+
|
| 223 |
self.last_frame_time = time.time()
|
| 224 |
|
| 225 |
frame = await asyncio.get_event_loop().run_in_executor(executor, self._capture)
|
| 226 |
+
|
| 227 |
if frame is None:
|
| 228 |
blank = np.zeros((config["height"], config["width"], 3), dtype=np.uint8)
|
| 229 |
av_frame = VideoFrame.from_ndarray(blank, format="bgr24")
|
| 230 |
else:
|
| 231 |
av_frame = VideoFrame.from_ndarray(frame, format="bgr24")
|
| 232 |
+
|
| 233 |
av_frame.pts = pts
|
| 234 |
av_frame.time_base = time_base
|
| 235 |
return av_frame
|
| 236 |
|
| 237 |
+
def map_key(key):
|
| 238 |
+
if key == " ": return "space"
|
| 239 |
+
k = key.lower()
|
| 240 |
+
charmap = {
|
| 241 |
+
"control": "ctrl", "shift": "shift", "alt": "alt", "meta": "super", "cmd": "super",
|
| 242 |
+
"enter": "Return", "backspace": "BackSpace", "tab": "Tab", "escape": "Escape",
|
| 243 |
+
"arrowup": "Up", "arrowdown": "Down", "arrowleft": "Left", "arrowright": "Right",
|
| 244 |
+
"home": "Home", "end": "End", "pageup": "Page_Up", "pagedown": "Page_Down",
|
| 245 |
+
"delete": "Delete", "insert": "Insert",
|
| 246 |
+
"f1": "F1", "f2": "F2", "f3": "F3", "f4": "F4", "f5": "F5", "f6": "F6",
|
| 247 |
+
"f7": "F7", "f8": "F8", "f9": "F9", "f10": "F10", "f11": "F11", "f12": "F12",
|
| 248 |
+
"!": "exclam", "@": "at", "#": "numbersign", "$": "dollar", "%": "percent",
|
| 249 |
+
"^": "asciicircum", "&": "ampersand", "*": "asterisk", "(": "parenleft",
|
| 250 |
+
")": "parenright", "-": "minus", "_": "underscore", "=": "equal", "+": "plus",
|
| 251 |
+
"[": "bracketleft", "{": "braceleft", "]": "bracketright", "}": "braceright",
|
| 252 |
+
";": "semicolon", ":": "colon", "'": "apostrophe", "\"": "quotedbl",
|
| 253 |
+
",": "comma", "<": "less", ".": "period", ">": "greater", "/": "slash",
|
| 254 |
+
"?": "question", "\\": "backslash", "|": "bar", "`": "grave", "~": "asciitilde",
|
| 255 |
+
" ": "space"
|
| 256 |
+
}
|
| 257 |
+
return charmap.get(k, k)
|
| 258 |
+
|
| 259 |
def process_input(data):
|
| 260 |
try:
|
| 261 |
msg = json.loads(data)
|
| 262 |
t = msg.get("type")
|
|
|
|
| 263 |
|
| 264 |
+
current_w = config["width"]
|
| 265 |
+
current_h = config["height"]
|
| 266 |
+
|
| 267 |
+
if t == "resize":
|
| 268 |
+
target_w = int(msg.get("width"))
|
| 269 |
+
target_h = int(msg.get("height"))
|
| 270 |
+
set_resolution(target_w, target_h)
|
| 271 |
+
|
| 272 |
+
elif t == "mousemove":
|
| 273 |
+
input_manager.mouse_move(int(msg["x"] * current_w), int(msg["y"] * current_h))
|
| 274 |
+
elif t == "mousedown":
|
| 275 |
input_manager.mouse_down({0:1, 1:2, 2:3}.get(msg.get("button"), 1))
|
| 276 |
+
elif t == "mouseup":
|
| 277 |
input_manager.mouse_up({0:1, 1:2, 2:3}.get(msg.get("button"), 1))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
elif t == "wheel":
|
| 279 |
input_manager.scroll(msg.get("deltaY", 0))
|
| 280 |
+
elif t == "keydown":
|
| 281 |
+
k = map_key(msg.get("key"))
|
| 282 |
+
if k: input_manager.key_down(k)
|
| 283 |
+
elif t == "keyup":
|
| 284 |
+
k = map_key(msg.get("key"))
|
| 285 |
+
if k: input_manager.key_up(k)
|
| 286 |
+
|
| 287 |
+
except Exception:
|
| 288 |
+
pass
|
| 289 |
|
| 290 |
async def offer(request):
|
| 291 |
try:
|
|
|
|
| 295 |
|
| 296 |
pc = RTCPeerConnection(RTCConfiguration(iceServers=[
|
| 297 |
RTCIceServer(urls=["turns:turn.cloudflare.com:443?transport=tcp", "turn:turn.cloudflare.com:3478?transport=udp"], username=TURN_USER, credential=TURN_PASS),
|
| 298 |
+
RTCIceServer(urls=["stun:stun.l.google.com:19302"])
|
| 299 |
]))
|
| 300 |
pcs.add(pc)
|
| 301 |
|
|
|
|
| 307 |
|
| 308 |
@pc.on("datachannel")
|
| 309 |
def on_dc(channel):
|
| 310 |
+
channel.on("message", lambda m: asyncio.get_event_loop().run_in_executor(executor, process_input, m))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
|
| 312 |
pc.addTrack(VirtualScreenTrack())
|
| 313 |
await pc.setRemoteDescription(offer)
|
| 314 |
answer = await pc.createAnswer()
|
| 315 |
await pc.setLocalDescription(answer)
|
|
|
|
| 316 |
|
| 317 |
+
sdp = "\r\n".join([l for l in pc.localDescription.sdp.splitlines() if "a=candidate" not in l or "typ relay" in l]) + "\r\n"
|
| 318 |
+
return web.Response(content_type="application/json", text=json.dumps({"sdp": sdp, "type": pc.localDescription.type}), headers={"Access-Control-Allow-Origin": "*"})
|
| 319 |
+
|
| 320 |
+
async def index(r): return web.Response(text="helloworld")
|
| 321 |
async def options(r): return web.Response(headers={"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type"})
|
| 322 |
|
| 323 |
pcs = set()
|