from __future__ import annotations import asyncio import base64 import io import ipaddress import os import re import shutil import time from collections.abc import AsyncIterator from fractions import Fraction from pathlib import Path from typing import Any from fastapi import HTTPException, Request, WebSocket from app.adb_lan.fmp4_muxer import AnnexBAccessUnitFramer, ZeroLatencyFmp4Muxer from app.storage.db import PulseWallDB _SAFE_PACKAGE_RE = re.compile(r"^[A-Za-z0-9_.-]+(/[A-Za-z0-9_.$]+)?$") _REPO_ROOT = Path(__file__).resolve().parents[3] def is_private_ip(host: str | None) -> bool: if not host: return False cleaned = host.strip() if cleaned in ("localhost", "testclient"): return True if cleaned.startswith("::ffff:"): cleaned = cleaned[len("::ffff:") :] try: ip = ipaddress.ip_address(cleaned) return ip.is_loopback or ip.is_private or ip.is_link_local except ValueError: return False def assert_lan_only_request(request: Request) -> None: """Hard security guard: LAN Developer Debug API MUST reject any non-LAN client or public proxy hop.""" client_host = request.client.host if request.client else None if not is_private_ip(client_host): raise HTTPException( status_code=403, detail=f"LAN Developer Debug API is strictly restricted to private LAN clients (got {client_host}).", ) for hdr in ("x-forwarded-for", "x-real-ip", "cf-connecting-ip"): val = request.headers.get(hdr) if val: parts = [p.strip() for p in val.split(",") if p.strip()] if any(not is_private_ip(p) for p in parts): raise HTTPException( status_code=403, detail=f"LAN Developer Debug API rejected public forwarded header '{hdr}'.", ) def _norm_model(s: str) -> str: return re.sub(r"[^a-z0-9]+", "", (s or "").lower()) def _extract_h264_codec_str(data: bytes) -> str | None: idx = 0 n = len(data) while idx < n - 4: pos = data.find(b"\x00\x00\x01", idx) if pos < 0: return None nal_start = pos + 3 if nal_start + 3 < n and (data[nal_start] & 0x1F) == 7: return f"avc1.{data[nal_start + 1]:02x}{data[nal_start + 2]:02x}{data[nal_start + 3]:02x}" idx = nal_start return None def _packet_has_idr(data: bytes) -> bool: idx = 0 n = len(data) while idx < n - 4: pos = data.find(b"\x00\x00\x01", idx) if pos < 0: return False nal_start = pos + 3 if nal_start < n and (data[nal_start] & 0x1F) == 5: return True idx = nal_start return False class _ChunkSink(io.RawIOBase): def __init__(self) -> None: self._chunks: list[bytes] = [] def writable(self) -> bool: return True def write(self, b: Any) -> int: raw = bytes(b) self._chunks.append(raw) return len(raw) def drain(self) -> bytes: if not self._chunks: return b"" out = b"".join(self._chunks) self._chunks.clear() return out class _Fmp4StreamBroadcaster: """Zero-transcode, ZERO-BUFFERING H.264 broadcaster (1 hardware encoder per device). Simultaneously fans out: - Raw Annex-B H.264 Access Units (`format=h264`) for direct browser WebCodecs GPU decoding - Zero-buffering fMP4 fragments (`format=fmp4`) for HTML5