#!/usr/bin/env python3
"""Hardware H.264 screen stream over one WebSocket.

Same idea as noVNC: the work browser opens an HTTPS page and nothing else
is installed there. The picture is a video encoded on the Mac, not a
remote-desktop framebuffer.
"""

import asyncio
import base64
import ctypes
import email.utils
import http
import json
import os
import queue
import re
import socket
import struct
import subprocess
import threading
import time
import urllib.request
import zlib
from pathlib import Path

import websockets
from websockets.datastructures import Headers
from websockets.http11 import Response

PORT = int(os.environ.get("HEIMSTREAM_PORT", "6090"))
FPS = int(os.environ.get("HEIMSTREAM_FPS", "60"))
WIDTH = int(os.environ.get("HEIMSTREAM_WIDTH", "1280"))
HEIGHT = int(os.environ.get("HEIMSTREAM_HEIGHT", "720"))
BITRATE = os.environ.get("HEIMSTREAM_BITRATE", "3000k")
VIDEO_DEVICE = os.environ.get("HEIMSTREAM_VIDEO_DEVICE", "1")
FFMPEG = os.environ.get("HEIMSTREAM_FFMPEG", "/opt/homebrew/bin/ffmpeg")
CAPTURE = os.environ.get("HEIMSTREAM_CAPTURE", str(Path(__file__).resolve().with_name("capture")))
WEBRTC = os.environ.get("HEIMSTREAM_WEBRTC", str(Path(__file__).resolve().with_name("webrtc-send")))
RTC_URL = os.environ.get("HEIMSTREAM_RTC_URL", "http://127.0.0.1:6091/offer")
USER_RE = re.compile(r"^[A-Za-z0-9._-]{1,32}$")
failures = 0
lock_until = 0.0

KEYCODES = {
    "KeyA": 0, "KeyS": 1, "KeyD": 2, "KeyF": 3, "KeyH": 4, "KeyG": 5,
    "KeyZ": 6, "KeyX": 7, "KeyC": 8, "KeyV": 9, "KeyB": 11, "KeyQ": 12,
    "KeyW": 13, "KeyE": 14, "KeyR": 15, "KeyY": 16, "KeyT": 17,
    "Digit1": 18, "Digit2": 19, "Digit3": 20, "Digit4": 21, "Digit6": 22,
    "Digit5": 23, "Equal": 24, "Digit9": 25, "Digit7": 26, "Minus": 27,
    "Digit8": 28, "Digit0": 29, "BracketRight": 30, "KeyO": 31, "KeyU": 32,
    "BracketLeft": 33, "KeyI": 34, "KeyP": 35, "Enter": 36, "KeyL": 37,
    "KeyJ": 38, "Quote": 39, "KeyK": 40, "Semicolon": 41, "Backslash": 42,
    "Comma": 43, "Slash": 44, "KeyN": 45, "KeyM": 46, "Period": 47,
    "Tab": 48, "Space": 49, "Backquote": 50, "Backspace": 51, "Escape": 53,
    "MetaLeft": 55, "ShiftLeft": 56, "AltLeft": 58, "ControlLeft": 59,
    "ShiftRight": 60, "AltRight": 61, "ControlRight": 62,
    "ArrowLeft": 123, "ArrowRight": 124, "ArrowDown": 125, "ArrowUp": 126,
    "F1": 122, "F2": 120, "F3": 99, "F4": 118, "F5": 96, "F6": 97,
    "F7": 98, "F8": 100, "F9": 101, "F10": 109, "F11": 103, "F12": 111,
}


class CGPoint(ctypes.Structure):
    _fields_ = [("x", ctypes.c_double), ("y", ctypes.c_double)]


class Input:
    def __init__(self):
        cg = ctypes.cdll.LoadLibrary(
            "/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics"
        )
        cg.CGEventCreateMouseEvent.restype = ctypes.c_void_p
        cg.CGEventCreateMouseEvent.argtypes = [
            ctypes.c_void_p, ctypes.c_uint32, CGPoint, ctypes.c_uint32
        ]
        cg.CGEventPost.argtypes = [ctypes.c_uint32, ctypes.c_void_p]
        cg.CFRelease.argtypes = [ctypes.c_void_p]
        cg.CGEventCreateKeyboardEvent.restype = ctypes.c_void_p
        cg.CGEventCreateKeyboardEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint16, ctypes.c_bool]
        cg.CGEventCreateScrollWheelEvent.restype = ctypes.c_void_p
        cg.CGEventCreateScrollWheelEvent.argtypes = [
            ctypes.c_void_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_int32
        ]
        cg.CGMainDisplayID.restype = ctypes.c_uint32
        cg.CGDisplayPixelsWide.restype = ctypes.c_size_t
        cg.CGDisplayPixelsWide.argtypes = [ctypes.c_uint32]
        cg.CGDisplayPixelsHigh.restype = ctypes.c_size_t
        cg.CGDisplayPixelsHigh.argtypes = [ctypes.c_uint32]
        cg.CGEventSetIntegerValueField.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_int64]
        cg.CGEventKeyboardSetUnicodeString.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.POINTER(ctypes.c_uint16)]
        cg.CGAssociateMouseAndMouseCursorPosition.argtypes = [ctypes.c_uint]
        cg.CGAssociateMouseAndMouseCursorPosition.restype = ctypes.c_int32
        cg.CGEventSourceCreate.restype = ctypes.c_void_p
        cg.CGEventSourceCreate.argtypes = [ctypes.c_int32]
        self.cg = cg
        self.source = cg.CGEventSourceCreate(1) or None
        display = cg.CGMainDisplayID()
        self.width = int(cg.CGDisplayPixelsWide(display)) or 1920
        self.height = int(cg.CGDisplayPixelsHigh(display)) or 1080
        self.buttons = 0
        self.mx = self.width / 2
        self.my = self.height / 2
        self.relative = False
        self.looking = False
        self._look_saved = None
        self.down_keys = set()

    def _post(self, event):
        if event:
            self.cg.CGEventPost(0, event)
            self.cg.CFRelease(event)

    def _xy(self, nx, ny):
        return (
            max(0, min(self.width - 1, float(nx) * self.width)),
            max(0, min(self.height - 1, float(ny) * self.height)),
        )

    def _begin_relative(self):
        if not self.relative:
            self.cg.CGAssociateMouseAndMouseCursorPosition(0)
            self.relative = True

    def _end_relative(self):
        if self.relative:
            self.cg.CGAssociateMouseAndMouseCursorPosition(1)
            self.relative = False

    def _button_xy(self, x, y, button, down, dx=0, dy=0):
        kind = {0: (1, 2), 1: (25, 26), 2: (3, 4)}.get(button, (1, 2))
        mac_button = {0: 0, 2: 1, 1: 2}.get(button, 0)
        event = self.cg.CGEventCreateMouseEvent(
            self.source, kind[0] if down else kind[1], CGPoint(x, y), mac_button
        )
        if event:
            self.cg.CGEventSetIntegerValueField(event, 4, int(dx))
            self.cg.CGEventSetIntegerValueField(event, 5, int(dy))
            self._post(event)
        if down:
            self.buttons |= 1 << button
        else:
            self.buttons &= ~(1 << button)

    def _warp(self, x, y):
        self.mx, self.my = x, y
        self._post(self.cg.CGEventCreateMouseEvent(self.source, 5, CGPoint(x, y), 0))

    def _stop_look(self):
        if not self.looking and not (self.buttons & 4):
            return
        self.looking = False
        if self.buttons & 4:
            self._button_xy(self.mx, self.my, 2, False)
        self._end_relative()
        if self._look_saved:
            x, y = self._look_saved
            self._look_saved = None
            self._warp(x, y)

    def move(self, nx, ny):
        self._stop_look()
        self._end_relative()
        x, y = self._xy(nx, ny)
        self.mx, self.my = x, y
        kind = 6 if self.buttons else 5
        self._post(self.cg.CGEventCreateMouseEvent(self.source, kind, CGPoint(x, y), 0))

    def button(self, nx, ny, button, down):
        self._stop_look()
        self._end_relative()
        x, y = self._xy(nx, ny)
        self.mx, self.my = x, y
        self._button_xy(x, y, int(button), bool(down))

    def rel(self, dx, dy):
        dx = max(-200, min(200, int(dx)))
        dy = max(-200, min(200, int(dy)))
        if dx == 0 and dy == 0:
            return
        if self.looking:
            self._begin_relative()
            if not (self.buttons & 4):
                self._button_xy(self.mx, self.my, 2, True)
            kind, mac_button = 7, 1
        elif self.buttons & 1:
            kind, mac_button = 6, 0
            self.mx = min(self.width - 1, max(0, self.mx + dx))
            self.my = min(self.height - 1, max(0, self.my + dy))
        elif self.buttons & 4:
            kind, mac_button = 7, 1
        elif self.buttons & 2:
            kind, mac_button = 27, 2
        else:
            kind, mac_button = 5, 0
            self.mx = min(self.width - 1, max(0, self.mx + dx))
            self.my = min(self.height - 1, max(0, self.my + dy))
        event = self.cg.CGEventCreateMouseEvent(self.source, kind, CGPoint(self.mx, self.my), mac_button)
        if event:
            self.cg.CGEventSetIntegerValueField(event, 4, dx)
            self.cg.CGEventSetIntegerValueField(event, 5, dy)
            self._post(event)

    def look(self, down):
        if down:
            if self.looking:
                return
            self.looking = True
            self._look_saved = (self.mx, self.my)
            self._end_relative()
            self._warp(self.width * 0.72, self.height * 0.42)
            self._button_xy(self.mx, self.my, 2, True)
            self._begin_relative()
            return
        self._stop_look()

    def button_here(self, button, down):
        if button not in (0, 1, 2):
            button = 0
        if self.looking:
            self._stop_look()
        self._button_xy(self.mx, self.my, button, bool(down))

    def click_at(self, nx, ny, button):
        if button not in (0, 1, 2):
            button = 0
        self._stop_look()
        self._end_relative()
        if nx is None or ny is None:
            x, y = self.mx, self.my
        else:
            x, y = self._xy(nx, ny)
            self.mx, self.my = x, y
        self._button_xy(x, y, button, True)
        time.sleep(0.07)
        self._button_xy(x, y, button, False)

    def click_here(self, button):
        self.click_at(None, None, button)

    def wheel(self, dy):
        self._post(self.cg.CGEventCreateScrollWheelEvent(None, 1, 1, int(-dy)))

    def key(self, code, down):
        keycode = KEYCODES.get(code)
        if keycode is None:
            return
        self._post(self.cg.CGEventCreateKeyboardEvent(None, keycode, bool(down)))
        if down:
            self.down_keys.add(keycode)
        else:
            self.down_keys.discard(keycode)

    def _unicode_char(self, char):
        units = (ctypes.c_uint16 * 1)(ord(char))
        for down in (True, False):
            event = self.cg.CGEventCreateKeyboardEvent(None, 0, down)
            if not event:
                continue
            self.cg.CGEventKeyboardSetUnicodeString(event, 1, units)
            self._post(event)

    def type_text(self, text, chat=False):
        if not isinstance(text, str):
            return
        clean = []
        for char in text[:180]:
            code = ord(char)
            if char in "\r\n" or code < 32 or code > 0xFFFF:
                continue
            clean.append(char)
        if not clean:
            return
        if chat:
            self.key("Enter", True)
            self.key("Enter", False)
            time.sleep(0.15)
        for char in clean:
            self._unicode_char(char)
            time.sleep(0.02)
        time.sleep(0.05)
        self.key("Enter", True)
        self.key("Enter", False)

    def release_all(self):
        self.looking = False
        self._look_saved = None
        for button in (0, 1, 2):
            if self.buttons & (1 << button):
                self._button_xy(self.mx, self.my, button, False)
        for keycode in list(self.down_keys):
            self._post(self.cg.CGEventCreateKeyboardEvent(None, keycode, False))
        self.down_keys.clear()
        self._end_relative()


def avcc(sps, pps):
    return bytes([1, sps[1], sps[2], sps[3], 0xFF, 0xE1]) + len(sps).to_bytes(2, "big") + sps + bytes([1]) + len(pps).to_bytes(2, "big") + pps


def extract_nals(buf):
    marks = []
    index = 0
    while index + 3 < len(buf):
        if buf[index:index + 4] == b"\x00\x00\x00\x01":
            marks.append((index, 4))
            index += 4
        elif buf[index:index + 3] == b"\x00\x00\x01":
            marks.append((index, 3))
            index += 3
        else:
            index += 1
    if len(marks) < 2:
        return [], buf
    nals = []
    for pos in range(len(marks) - 1):
        start, size = marks[pos]
        nal = buf[start + size:marks[pos + 1][0]]
        if nal:
            nals.append(nal)
    return nals, buf[marks[-1][0]:]


def length_prefixed(nals):
    out = bytearray()
    for nal in nals:
        out += len(nal).to_bytes(4, "big") + nal
    return bytes(out)


def mac_login_ok(username, password):
    global failures, lock_until
    if not isinstance(username, str) or not isinstance(password, str):
        return False
    if not USER_RE.fullmatch(username) or not password or len(password) > 200:
        return False
    now = time.time()
    if now < lock_until:
        return False
    result = subprocess.run(
        ["/usr/bin/dscl", "/Search", "-authonly", username, password],
        capture_output=True,
        timeout=8,
    )
    if result.returncode == 0:
        failures = 0
        return True
    failures += 1
    if failures >= 5:
        failures = 0
        lock_until = now + 60
    return False


class Encoder(threading.Thread):
    def __init__(self, loop):
        super().__init__(daemon=True)
        self.loop = loop
        self.proc = None
        self.clients = set()
        self.hold_for_key = set()
        self.latest_config = None
        self.latest_key = None
        self.last_key_request = 0.0
        self.stat_frames = 0
        self.stat_keys = 0
        self.stat_bytes = 0
        self.stat_time = time.time()

    def run(self):
        command = [CAPTURE, str(WIDTH), str(HEIGHT), str(FPS), "3000000"]
        self.proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None)
        buf = b""
        sps = pps = None
        while True:
            chunk = self.proc.stdout.read(65536)
            if not chunk:
                print("ffmpeg ended", self.proc.poll(), flush=True)
                break
            buf += chunk
            nals, buf = extract_nals(buf)
            for nal in nals:
                nal_type = nal[0] & 0x1F
                if nal_type == 7:
                    sps = nal
                elif nal_type == 8:
                    pps = nal
                elif nal_type in (1, 5) and sps and pps:
                    key = nal_type == 5
                    if self.latest_config is None:
                        self.latest_config = {
                            "type": "config",
                            "codec": f"avc1.{sps[1]:02X}{sps[2]:02X}{sps[3]:02X}",
                            "description": base64.b64encode(avcc(sps, pps)).decode(),
                            "width": WIDTH,
                            "height": HEIGHT,
                            "fps": FPS,
                        }
                        self._emit(("config", self.latest_config))
                    units = [sps, pps, nal] if key else [nal]
                    ms = int(time.time() * 1000) & 0xFFFFFFFF
                    frame = bytes((
                        1 if key else 0,
                        (ms >> 24) & 255,
                        (ms >> 16) & 255,
                        (ms >> 8) & 255,
                        ms & 255,
                    )) + length_prefixed(units)
                    self.stat_frames += 1
                    self.stat_bytes += len(frame)
                    if key:
                        self.stat_keys += 1
                        self.latest_key = frame
                    now = time.time()
                    if now - self.stat_time >= 1:
                        print(
                            f"stream {self.stat_frames} frames, {self.stat_keys} key, {self.stat_bytes // 1024} KB/s",
                            flush=True,
                        )
                        self.stat_frames = self.stat_keys = self.stat_bytes = 0
                        self.stat_time = now
                    self._emit(("frame", frame, key))

    def _emit(self, item):
        self.loop.call_soon_threadsafe(self._put, item)

    def _put(self, item):
        kind = item[0]
        if kind == "config":
            self.latest_config = item[1]
        is_key = kind == "frame" and item[2]
        dead = []
        for queue in list(self.clients):
            if kind == "frame" and queue in self.hold_for_key and not is_key:
                continue
            if is_key:
                self.hold_for_key.discard(queue)
            try:
                queue.put_nowait(item)
            except asyncio.QueueFull:
                dead.append(queue)
        for queue in dead:
            self.clients.discard(queue)
            self.hold_for_key.discard(queue)

    def request_key(self):
        now = time.time()
        if now - self.last_key_request < 0.05:
            return
        self.last_key_request = now
        if self.proc is None or self.proc.stdin is None:
            return
        try:
            self.proc.stdin.write(b"k\n")
            self.proc.stdin.flush()
        except Exception:
            pass

    def stop(self):
        if self.proc and self.proc.poll() is None:
            self.proc.terminate()


async def pump(websocket, queue, encoder):
    inflight = 0
    need_key = False
    pending = []
    while True:
        try:
            item = await asyncio.wait_for(queue.get(), timeout=0.4)
        except asyncio.TimeoutError:
            if inflight and len(pending) > 1:
                last_key = next((index for index in range(len(pending) - 1, -1, -1) if pending[index][2]), None)
                if last_key is None:
                    pending.clear()
                    need_key = True
                    encoder.request_key()
                else:
                    pending = pending[last_key:]
            if inflight:
                inflight = 0
            item = None
        batch = []
        if item is not None:
            batch.append(item)
            while True:
                try:
                    batch.append(queue.get_nowait())
                except asyncio.QueueEmpty:
                    break
        for piece in batch:
            kind = piece[0]
            if kind == "text":
                await websocket.send(piece[1])
            elif kind == "config":
                await websocket.send(json.dumps(piece[1]))
            elif kind == "ack":
                if inflight:
                    inflight -= 1
            elif kind == "frame":
                if piece[2]:
                    pending = [piece]
                    need_key = False
                elif need_key:
                    continue
                else:
                    pending.append(piece)
                    if inflight + len(pending) > 3:
                        pending.clear()
                        need_key = True
                        encoder.request_key()
        while pending and inflight < 3:
            frame = pending.pop(0)
            await websocket.send(frame[1])
            inflight += 1


def text_field_focused():
    try:
        app = ctypes.cdll.LoadLibrary("/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices")
        cf = ctypes.cdll.LoadLibrary("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")
        app.AXUIElementCreateSystemWide.restype = ctypes.c_void_p
        app.AXUIElementCopyAttributeValue.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p)]
        app.AXUIElementCopyAttributeValue.restype = ctypes.c_int
        cf.CFStringCreateWithCString.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_uint32]
        cf.CFStringCreateWithCString.restype = ctypes.c_void_p
        cf.CFStringGetCString.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_long, ctypes.c_uint32]
        cf.CFStringGetCString.restype = ctypes.c_bool
        cf.CFRelease.argtypes = [ctypes.c_void_p]

        def make(label):
            return cf.CFStringCreateWithCString(None, label.encode(), 0x08000100)

        system = app.AXUIElementCreateSystemWide()
        if not system:
            return False
        focused_name = make("AXFocusedUIElement")
        focused = ctypes.c_void_p()
        err = app.AXUIElementCopyAttributeValue(system, focused_name, ctypes.byref(focused))
        cf.CFRelease(focused_name)
        cf.CFRelease(system)
        if err != 0 or not focused.value:
            return False
        role_name = make("AXRole")
        role = ctypes.c_void_p()
        err = app.AXUIElementCopyAttributeValue(focused, role_name, ctypes.byref(role))
        cf.CFRelease(role_name)
        cf.CFRelease(focused)
        if err != 0 or not role.value:
            return False
        buf = ctypes.create_string_buffer(128)
        cf.CFStringGetCString(role, buf, 128, 0x08000100)
        cf.CFRelease(role)
        return buf.value.decode() in {"AXTextField", "AXTextArea", "AXComboBox", "AXSearchField"}
    except Exception:
        return False


INPUTS = queue.Queue(maxsize=300)


def _input_worker():
    while True:
        fn, args = INPUTS.get()
        try:
            fn(*args)
        except Exception:
            pass


def enqueue(fn, *args, droppable=False):
    item = (fn, args)
    try:
        INPUTS.put_nowait(item)
    except queue.Full:
        if droppable:
            return
        try:
            INPUTS.get_nowait()
        except queue.Empty:
            return
        try:
            INPUTS.put_nowait(item)
        except queue.Full:
            pass


async def handler(websocket, inputs):
    sock = websocket.transport.get_extra_info("socket") if websocket.transport else None
    if sock is not None:
        try:
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        except OSError:
            pass
    authed = False
    try:
        async for raw in websocket:
            try:
                msg = json.loads(raw)
            except json.JSONDecodeError:
                continue
            kind = msg.get("t")
            if not authed:
                if kind != "login":
                    continue
                if await asyncio.to_thread(mac_login_ok, msg.get("user"), msg.get("pass")):
                    authed = True
                    await websocket.send(json.dumps({"type": "ok"}))
                else:
                    await asyncio.sleep(1.5)
                    await websocket.send(json.dumps({"type": "deny"}))
                continue
            if kind == "move":
                enqueue(inputs.move, _num(msg.get("x")), _num(msg.get("y")), droppable=True)
            elif kind == "down":
                enqueue(inputs.button, _num(msg.get("x")), _num(msg.get("y")), int(msg.get("b") or 0), True)
            elif kind == "up":
                enqueue(inputs.button, _num(msg.get("x")), _num(msg.get("y")), int(msg.get("b") or 0), False)
            elif kind == "wheel":
                enqueue(inputs.wheel, int(_num(msg.get("dy"))))
            elif kind == "key" and "code" in msg:
                enqueue(inputs.key, msg.get("code", ""), bool(msg.get("down")))
            elif kind == "rel":
                enqueue(inputs.rel, _num(msg.get("dx")), _num(msg.get("dy")))
            elif kind == "look":
                enqueue(inputs.look, bool(msg.get("down")))
            elif kind == "btn":
                enqueue(inputs.button_here, int(msg.get("b") or 0), bool(msg.get("down")))
            elif kind == "click":
                button = int(msg.get("b") or 0)
                if "x" in msg and "y" in msg:
                    enqueue(inputs.click_at, _num(msg.get("x")), _num(msg.get("y")), button)
                else:
                    enqueue(inputs.click_here, button)
            elif kind == "type" and isinstance(msg.get("text"), str):
                enqueue(inputs.type_text, msg.get("text"), bool(msg.get("chat")))
            elif kind == "probe":
                await asyncio.sleep(0.25)
                try:
                    focused = await asyncio.to_thread(text_field_focused)
                except Exception:
                    focused = False
                if focused:
                    await websocket.send(json.dumps({"type": "edit"}))
            elif kind == "offer":
                try:
                    answer = await asyncio.to_thread(webrtc_answer, msg.get("sdp") or "")
                except Exception:
                    await websocket.send(json.dumps({"type": "video-error"}))
                else:
                    await websocket.send(json.dumps({"type": "answer", "sdp": answer}))
    finally:
        enqueue(inputs.release_all)


def webrtc_answer(sdp):
    req = urllib.request.Request(RTC_URL, data=sdp.encode(), method="POST")
    with urllib.request.urlopen(req, timeout=8) as resp:
        return resp.read().decode()


def supervise_webrtc():
    while True:
        cap = subprocess.Popen(
            [CAPTURE, str(WIDTH), str(HEIGHT), str(FPS), "2000000"],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=None,
        )
        fd = cap.stdin.fileno()
        os.set_inheritable(fd, True)
        env = os.environ.copy()
        env["HEIMSTREAM_KEY_FD"] = str(fd)
        rtc = subprocess.Popen(
            [WEBRTC],
            stdin=cap.stdout,
            stderr=None,
            pass_fds=(fd,),
            env=env,
        )
        cap.stdout.close()
        rtc.wait()
        if cap.poll() is None:
            cap.kill()
        time.sleep(3)


def _num(value):
    try:
        return float(value)
    except (TypeError, ValueError):
        return 0.0


def _png(size):
    def pixel(x, y):
        cx = cy = (size - 1) / 2
        nx = (x - cx) / (size * 0.5)
        ny = (y - cy) / (size * 0.5)
        dist = (nx * nx + ny * ny) ** 0.5
        if 0.62 < dist < 0.76:
            return (61, 255, 181)
        for ox, oy in ((0.30, -0.22), (0.30, 0.08), (0.08, -0.08), (0.08, 0.22)):
            if (nx - ox) ** 2 + (ny - oy) ** 2 < 0.012:
                return (232, 238, 244)
        if (nx + 0.38) ** 2 + (ny + 0.02) ** 2 < 0.028:
            return (61, 255, 181)
        return (12, 20, 28) if dist < 0.9 else (7, 11, 16)

    rows = []
    for y in range(size):
        row = bytearray([0])
        for x in range(size):
            row += bytes(pixel(x, y))
        rows.append(bytes(row))

    def chunk(tag, data):
        return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)

    raw = zlib.compress(b"".join(rows), 9)
    ihdr = struct.pack(">IIBBBBB", size, size, 8, 2, 0, 0, 0)
    return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", raw) + chunk(b"IEND", b"")


ICON_180 = _png(180)
ICON_512 = _png(512)
MANIFEST = json.dumps({
    "name": "HeimStream",
    "short_name": "HeimStream",
    "start_url": "/",
    "scope": "/",
    "display": "standalone",
    "background_color": "#070b10",
    "theme_color": "#070b10",
    "icons": [
        {"src": "/icon-180.png", "sizes": "180x180", "type": "image/png", "purpose": "any"},
        {"src": "/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any"},
    ],
})
SW = """self.addEventListener("install", (event) => self.skipWaiting());
self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim()));
self.addEventListener("fetch", (event) => {
  if (event.request.method === "GET") event.respondWith(fetch(event.request));
});
"""


def http_response(status, body, content_type, cache="no-store"):
    if isinstance(body, str):
        body = body.encode()
    status = http.HTTPStatus(status)
    headers = Headers([
        ("Date", email.utils.formatdate(usegmt=True)),
        ("Connection", "close"),
        ("Content-Length", str(len(body))),
        ("Content-Type", content_type),
        ("Cache-Control", cache),
    ])
    return Response(status.value, status.phrase, headers, body)


async def process_request(connection, request):
    path = request.path.split("?", 1)[0]
    if path == "/ws":
        return None
    if path == "/":
        page = (Path(__file__).resolve().parent / "page.html").read_text()
        return http_response(200, page, "text/html; charset=utf-8")
    if path == "/manifest.webmanifest":
        return http_response(200, MANIFEST, "application/manifest+json")
    if path == "/sw.js":
        return http_response(200, SW, "text/javascript; charset=utf-8")
    if path == "/icon-180.png":
        return http_response(200, ICON_180, "image/png", "public, max-age=86400")
    if path == "/icon-512.png":
        return http_response(200, ICON_512, "image/png", "public, max-age=86400")
    return connection.respond(404, "not found")


async def main():
    inputs = Input()
    threading.Thread(target=_input_worker, daemon=True).start()
    threading.Thread(target=supervise_webrtc, daemon=True).start()
    for _ in range(50):
        try:
            urllib.request.urlopen("http://127.0.0.1:6091/health", timeout=0.2)
            break
        except Exception:
            await asyncio.sleep(0.1)

    async def wrapped(websocket):
        await handler(websocket, inputs)

    subprocess.Popen(
        ["/usr/bin/caffeinate", "-dimsu", "-w", str(os.getpid())],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )
    print(f"HeimStream auf http://127.0.0.1:{PORT}/")
    async with websockets.serve(
        wrapped, "0.0.0.0", PORT,
        process_request=process_request,
        max_size=None,
        compression=None,
        ping_interval=25,
        ping_timeout=90,
    ):
        await asyncio.Future()


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        pass
