Improve camera recovery, shared preview lifecycle and receiver playout diagnostics. Preserve qualified X4 runtime changes and restore async admission in loopback media tests.
174 lines
7.7 KiB
Python
174 lines
7.7 KiB
Python
"""Private WebRTC preview. No capture ownership, relay, STUN or public candidates."""
|
|
|
|
import asyncio
|
|
import ipaddress
|
|
import json
|
|
import time
|
|
import uuid
|
|
from fractions import Fraction
|
|
|
|
import aioice.ice
|
|
from missioncore_plugin_sdk.link_budget import budget_peer
|
|
from missioncore_plugin_sdk.media_budget import adapt_peer, cap_video_sender
|
|
from aiortc import RTCConfiguration, RTCPeerConnection, RTCSessionDescription, VideoStreamTrack
|
|
from av import VideoFrame
|
|
|
|
|
|
def private(address):
|
|
try:
|
|
value = ipaddress.ip_address(address)
|
|
return value.version == 4 and (
|
|
value.is_loopback
|
|
or any(
|
|
value in ipaddress.ip_network(n)
|
|
for n in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "100.64.0.0/10")
|
|
)
|
|
)
|
|
except ValueError:
|
|
return False
|
|
|
|
|
|
host_addresses = aioice.ice.get_host_addresses
|
|
aioice.ice.get_host_addresses = lambda use_ipv4, use_ipv6: [
|
|
v for v in host_addresses(use_ipv4=True, use_ipv6=False) if private(v)
|
|
]
|
|
|
|
|
|
class CameraTrack(VideoStreamTrack):
|
|
def __init__(self, device, layer, budget=None):
|
|
super().__init__()
|
|
self.device, self.layer, self.budget = device, layer, budget
|
|
self.next_at = 0.0
|
|
self.started = None
|
|
self.sequence = 0
|
|
|
|
async def recv(self):
|
|
if self.started is None:
|
|
self.started = time.monotonic()
|
|
while True:
|
|
width, fps = self.budget.video() if self.budget else (1280, 15)
|
|
now = time.monotonic()
|
|
sequence = self.device.frames.get(self.layer, 0)
|
|
fresh = now - self.device.last_frame.get("monotonic_ns", 0) / 1e9 < 2
|
|
if (fps and now >= self.next_at and fresh and sequence != self.sequence
|
|
and self.layer in self.device.images):
|
|
# One latest hardware image; no replay of a stalled source.
|
|
frame = VideoFrame.from_ndarray(self.device.images[self.layer], format="rgb24")
|
|
self.sequence = sequence
|
|
self.next_at = now + 1 / fps
|
|
if frame.width > width:
|
|
height = max(2, round(frame.height * width / frame.width) // 2 * 2)
|
|
frame = frame.reformat(width=width, height=height, format="yuv420p")
|
|
frame.pts, frame.time_base = round((now-self.started)*90000), Fraction(1,90000)
|
|
return frame
|
|
await asyncio.sleep(.02)
|
|
|
|
|
|
|
|
class Peers:
|
|
def __init__(self):
|
|
self.items = {}
|
|
|
|
async def offer(self, device, params):
|
|
layer = params.get("layer", "color")
|
|
if type(params.get("primary", False)) is not bool:
|
|
raise ValueError("Invalid preview role")
|
|
if layer not in ("color", "depth", "infrared1", "infrared2", "points", "motion"):
|
|
raise ValueError("Неизвестный слой камеры.")
|
|
if len(self.items) >= 4:
|
|
raise ValueError("Закройте лишние окна просмотра камеры.")
|
|
sdp = params.get("sdp", "")
|
|
if not isinstance(sdp, str) or len(sdp) > 32768:
|
|
raise ValueError("Некорректное приглашение просмотра.")
|
|
for line in sdp.splitlines():
|
|
if line.startswith("a=candidate:"):
|
|
fields = line.split()
|
|
if len(fields) < 8 or (not private(fields[4]) and not fields[4].endswith(".local")):
|
|
raise ValueError("Просмотр доступен только в частной сети.")
|
|
pc = RTCPeerConnection(RTCConfiguration(iceServers=[]))
|
|
ident = "peer_" + uuid.uuid4().hex
|
|
self.items[ident] = {"pc": pc, "seen": time.monotonic(), "tasks": set(), "channel": None}
|
|
allocation = None
|
|
|
|
async def telemetry(channel):
|
|
try:
|
|
while pc.connectionState not in ("failed", "closed"):
|
|
if time.monotonic() - self.items.get(ident, {}).get("seen", 0) > 30:
|
|
break
|
|
interval = .25
|
|
pending = getattr(pc, "_missioncore_pending_media", lambda: 0)()
|
|
if channel.readyState == "open" and channel.bufferedAmount < 16384 and pending < 16384 and allocation and allocation.bps:
|
|
payload = {
|
|
"layer": layer,
|
|
"motion": device.motion,
|
|
"frame": device.last_frame,
|
|
"acquisition": device.acquisition,
|
|
}
|
|
if layer == "points":
|
|
count, interval = allocation.cloud(2000, 48)
|
|
payload["points"] = await asyncio.to_thread(device.points, count)
|
|
payload["media_budget"] = allocation.snapshot()
|
|
raw = json.dumps(payload, allow_nan=False)
|
|
# A single JSON message must fit the bounded SCTP burst.
|
|
while len(raw.encode()) > 16384 and payload.get("points"):
|
|
values = payload["points"]
|
|
payload["points"] = [v for i in range(0,len(values),6) for v in values[i:i+3]]
|
|
raw = json.dumps(payload, allow_nan=False)
|
|
if len(raw.encode()) <= 16384:
|
|
channel.send(raw)
|
|
await asyncio.sleep(interval)
|
|
finally:
|
|
await self.close(ident)
|
|
|
|
@pc.on("datachannel")
|
|
def datachannel(channel):
|
|
entry = self.items.get(ident)
|
|
if entry is None or entry["channel"] is not None:
|
|
channel.close()
|
|
return
|
|
entry["channel"] = channel
|
|
@channel.on("message")
|
|
def message(value):
|
|
if value in ("view:primary", "view:secondary") and allocation and layer not in ("points", "motion"):
|
|
allocation.primary = value == "view:primary"
|
|
if value == "keepalive" and ident in self.items:
|
|
self.items[ident]["seen"] = time.monotonic()
|
|
|
|
task = asyncio.create_task(telemetry(channel))
|
|
self.items[ident]["tasks"].add(task)
|
|
|
|
@pc.on("connectionstatechange")
|
|
async def changed():
|
|
if pc.connectionState in ("failed", "closed"):
|
|
await self.close(ident)
|
|
|
|
try:
|
|
await pc.setRemoteDescription(RTCSessionDescription(sdp=sdp, type="offer"))
|
|
allocation = await adapt_peer(pc, "cloud" if layer in ("points", "motion") else "video", primary=params.get("primary", False) and layer not in ("points", "motion"))
|
|
if layer not in ("points", "motion"):
|
|
sender = pc.addTrack(CameraTrack(device, layer, allocation))
|
|
cap_video_sender(sender, allocation)
|
|
budget_peer(pc, "cloud" if layer in ("points", "motion") else "video", producer_id=allocation.id)
|
|
await pc.setLocalDescription(await pc.createAnswer())
|
|
|
|
async def expiry():
|
|
await asyncio.sleep(30)
|
|
if ident in self.items and pc.connectionState != "connected":
|
|
await self.close(ident)
|
|
|
|
self.items[ident]["tasks"].add(asyncio.create_task(expiry()))
|
|
return {"peer_id": ident, "sdp": pc.localDescription.sdp, "type": "answer"}
|
|
except Exception:
|
|
await self.close(ident)
|
|
raise
|
|
|
|
async def close(self, ident):
|
|
entry = self.items.pop(ident, None)
|
|
if entry:
|
|
tasks = [t for t in entry["tasks"] if t is not asyncio.current_task()]
|
|
for task in tasks:
|
|
task.cancel()
|
|
await asyncio.gather(*tasks, return_exceptions=True)
|
|
await entry["pc"].close()
|
|
return {"ok": True}
|