"""Stage part: does Jarvis make a video stutter, and does the 95 % GPU cap help? User decision (2026-11-11): the cap's default is off, because gamemode_tune showed it did not lower nvidia-smi's utilisation and cost 6 to 10 % of the LLM's output. What the user cared about is a video next to Jarvis, so that is measured directly: a YouTube video plays in a throwaway Chrome/Edge profile (never the user's) and the kit counts its dropped frames and long gaps between shown frames with Jarvis off, Jarvis loaded and idle, and Jarvis busy (the LLM answering, the STT transcribing ten speakers back to back) without and with the cap. The busy rows run in the order A B B A (no cap, cap, cap, no cap) so a slow drift does not count for one side. The browser is driven through the Chrome DevTools Protocol with a small standard-library WebSocket client (the kit's venvs are already built, so no package is added). Nothing from the page is saved except the video's own counters, its quality and whether an ad was showing. """ from __future__ import annotations import base64 import json import os import re import shutil import socket import struct import subprocess import time import urllib.parse from pathlib import Path from typing import Any, Callable from m0lib import gpucap, llm from m0lib.common import IS_WINDOWS, StageResult, gpu_memory_mib, say from m0lib.llm_client import ChatClient, http_json # Blender's own upload (CC BY 3.0, 10:34, 4K and 1080p at 60 fps): no music claim, rarely ads. VIDEO_URL = "https://www.youtube.com/watch?v=aqz-KE-bpKQ" QUALITY = "hd1080" # What a counted window must have played: the asked quality at its height and the source's 60 fps (the # player's frame counter includes dropped frames, so a busy GPU does not lower it; a 30 fps format does). WANT = {"quality": QUALITY, "height": 1080, "fps": 60} MIN_FPS_SHARE = 0.8 QUIET_S = 60 # the video alone, and Jarvis loaded but idle SETTLE_S = 5 # after a quality change or a seek, before a window starts MIN_LEFT_S = 240 # a window that could reach the end starts the video again first GAP_MS = (50, 100) # a gap between shown frames this long is a visible hitch at 60 fps ROUNDS = ("busy", "busy_cap95", "busy_cap95_2", "busy_2") # A window spoilt by the player (an error, a reload, a pause, an ad, buffering) is measured again, at most # this many times in all; one spoilt by a lower quality or frame rate is not (a busy GPU can cause that). ATTEMPTS = 3 REPLAY_S = 30 # pressing play on a stopped player, before the page is loaded again RELOAD_S = 120 # the page loaded again, until its video plays # -------------------------------------------------------------------------- # A minimal WebSocket client (RFC 6455) for one DevTools page. def encode_frame(payload: bytes, opcode: int = 1, mask: bytes | None = None) -> bytes: """One final client frame; a client must mask what it sends.""" mask = mask or os.urandom(4) n = len(payload) if n < 126: head = bytes([0x80 | opcode, 0x80 | n]) elif n < 1 << 16: head = bytes([0x80 | opcode, 0x80 | 126]) + struct.pack(">H", n) else: head = bytes([0x80 | opcode, 0x80 | 127]) + struct.pack(">Q", n) return head + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(payload)) class Cdp: """One DevTools WebSocket: ``call`` sends a command and returns its result, skipping events.""" def __init__(self, ws_url: str, timeout: float = 60, sock: socket.socket | None = None): self._buf = b"" self._id = 0 if sock is not None: # tests hand in one end of a socket pair, already "upgraded" self.sock = sock return u = urllib.parse.urlparse(ws_url) self.sock = socket.create_connection((u.hostname, u.port), timeout=timeout) key = base64.b64encode(os.urandom(16)).decode() # No Origin header: Chrome only checks --remote-allow-origins when one is sent. self.sock.sendall((f"GET {u.path} HTTP/1.1\r\nHost: {u.hostname}:{u.port}\r\nUpgrade: websocket\r\n" f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n" ).encode()) while b"\r\n\r\n" not in self._buf: self._more() head, self._buf = self._buf.split(b"\r\n\r\n", 1) if b" 101 " not in head.split(b"\r\n", 1)[0]: raise ConnectionError(f"DevTools refused the WebSocket: {head[:200]!r}") def _more(self) -> None: got = self.sock.recv(65536) if not got: raise ConnectionError("DevTools closed the connection") self._buf += got def _take(self, n: int) -> bytes: while len(self._buf) < n: self._more() out, self._buf = self._buf[:n], self._buf[n:] return out def _frame(self) -> tuple[bool, int, bytes]: b0, b1 = self._take(2) n = b1 & 0x7F if n == 126: n = struct.unpack(">H", self._take(2))[0] elif n == 127: n = struct.unpack(">Q", self._take(8))[0] mask = self._take(4) if b1 & 0x80 else None data = self._take(n) if mask: data = bytes(b ^ mask[i % 4] for i, b in enumerate(data)) return bool(b0 & 0x80), b0 & 0x0F, data def recv(self) -> str: """The next whole text message; answers pings, raises on close.""" parts: list[bytes] = [] while True: fin, op, data = self._frame() if op == 8: raise ConnectionError("DevTools closed the WebSocket") if op == 9: self.sock.sendall(encode_frame(data, opcode=10)) continue if op == 10: continue parts.append(data) if fin: return b"".join(parts).decode("utf-8", "replace") def call(self, method: str, params: dict | None = None) -> dict: self._id += 1 mine = self._id self.sock.sendall(encode_frame(json.dumps({"id": mine, "method": method, "params": params or {}}).encode())) while True: msg = json.loads(self.recv()) if msg.get("id") != mine: continue # an event, or the answer to a command that timed out earlier if "error" in msg: raise RuntimeError(f"{method}: {msg['error']}") return msg.get("result") or {} def evaluate(self, expression: str) -> Any: res = self.call("Runtime.evaluate", {"expression": expression, "returnByValue": True}) if res.get("exceptionDetails"): d = res["exceptionDetails"] raise RuntimeError(f"page script failed: {(d.get('exception') or {}).get('description') or d.get('text')}") return (res.get("result") or {}).get("value") def close(self) -> None: try: self.sock.close() except OSError: pass # -------------------------------------------------------------------------- # The page: what runs inside YouTube's watch page. # Counts shown frames (requestVideoFrameCallback runs once per frame put on screen), the long gaps # between them, buffering and ads; installed again if YouTube swaps the