feat(video): recover camera previews and reduce encoding and playout cost

Improve camera recovery, shared preview lifecycle and receiver playout diagnostics. Preserve qualified X4 runtime changes and restore async admission in loopback media tests.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:10:01 +03:00
parent e06ff9a214
commit fa8bde584f
94 changed files with 8892 additions and 375 deletions
+84 -10
View File
@@ -16,6 +16,8 @@ from fractions import Fraction
import aioice.ice
import av
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,
@@ -26,7 +28,7 @@ from aiortc import (
from aiortc.mediastreams import MediaStreamError
from .errors import failure
from .frames import decode
from .frames import START_CODE, decode
from .http import request
NETWORKS = tuple(
@@ -65,6 +67,10 @@ def admit_sdp(sdp):
raise ValueError("Camera preview requires a private network")
class PreviewCapacityError(ValueError):
"""No peer was admitted; retrying cannot repeat a camera action."""
class Source:
def __init__(self, path, session):
self.path, self.session = path, session
@@ -75,11 +81,28 @@ class Source:
self.started = time.monotonic()
self.closed = threading.Event()
self.thread = threading.Thread(target=self.pump, daemon=True)
self.packets = self.gaps = self.resets = self.decode_errors = self.keyframes = 0
self.packet_at = self.keyframe_at = None
self.generation = None
self.failure = None
def current(self):
with self.lock:
return self.sequence, self.frame, self.observed
def health(self):
"""Bounded in-memory counters; no encoded media or monitoring history."""
with self.lock:
now = time.monotonic()
return {
"packets": self.packets, "frames": self.sequence,
"packet_age_ms": round((now - self.packet_at) * 1000) if self.packet_at is not None else None,
"keyframes": self.keyframes,
"keyframe_age_ms": round((now - self.keyframe_at) * 1000) if self.keyframe_at is not None else None,
"gaps": self.gaps, "resets": self.resets, "decode_errors": self.decode_errors,
"generation": self.generation, "closed": self.closed.is_set(), "failure": self.failure,
}
def pump(self):
cursor, key, decoder, resized_at = 0, None, None, 0.0
try:
@@ -98,13 +121,38 @@ class Source:
cursor = header["cursor"]
if header["stream_index"] != 0:
continue
now = time.monotonic()
keyframe = any(
(data[marker.end()] & 31) == 5 if header["codec"] == 0
else ((data[marker.end()] >> 1) & 63) in (16, 17, 18, 19, 20, 21)
for marker in START_CODE.finditer(data) if marker.end() < len(data)
)
with self.lock:
self.packets += 1
self.packet_at = now
self.generation = header["generation"]
self.gaps += int(header["gap"])
if keyframe:
self.keyframes += 1
self.keyframe_at = now
current = (header["generation"], header["codec"])
if decoder is None or key != current or header["gap"]:
if key != current or header["gap"]:
decoder = None
key = current
if decoder is None:
# Parsing dependent NALs after a gap can fail while the
# next IDR is still buffered in the parser. Recreating the
# decoder then discards that IDR forever. Feed replays this
# generation's parameter sets on keyframes, so resume only
# from an independently decodable packet.
if not keyframe:
continue
decoder = av.CodecContext.create(
"h264" if header["codec"] == 0 else "hevc", "r"
)
decoder.thread_count = 1
key = current
with self.lock:
self.resets += 1
try:
for packet in decoder.parse(data):
for frame in decoder.decode(packet):
@@ -124,7 +172,11 @@ class Source:
resized_at = now
except av.error.FFmpegError:
decoder = None
with self.lock:
self.decode_errors += 1
except (OSError, ValueError, RuntimeError) as error:
with self.lock:
self.failure = type(error).__name__
logging.getLogger(__name__).warning(
"X4 preview source stopped (%s)", type(error).__name__
)
@@ -138,17 +190,25 @@ class Source:
class Track(VideoStreamTrack):
def __init__(self, source):
def __init__(self, source, budget=None):
super().__init__()
self.budget = budget
self.source, self.sequence, self.next_at = source, 0, 0.0
async def recv(self):
while self.readyState == "live" and not self.source.closed.is_set():
await asyncio.sleep(max(0, self.next_at - time.monotonic()))
width, fps = self.budget.video() if self.budget else (1280, 15)
if not fps:
await asyncio.sleep(.1)
continue
sequence, frame, observed = self.source.current()
if frame is not None and sequence > self.sequence and time.monotonic() - observed < 2:
self.sequence = sequence
self.next_at = time.monotonic() + 1 / 15
self.next_at = time.monotonic() + 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")
# Distinct AV frames per encoder: force-keyframe decisions in
# one browser must not mutate another browser's frame object.
copy = av.VideoFrame(frame.width, frame.height, "yuv420p")
@@ -235,7 +295,7 @@ class Peers:
# competing decoder or accept a retained frame as fresh evidence.
source = self.sources.get(key)
if source is None or source.closed.is_set():
return failure("preview_restart_required")
return dict(failure("preview_restart_required"), result={"decoder": source.health() if source else None})
initial = source.current()[0]
started = time.monotonic()
while time.monotonic() - started < timeout:
@@ -259,13 +319,14 @@ class Peers:
},
}
await asyncio.sleep(0.02)
return failure("preview_restart_required")
return dict(failure("preview_restart_required"), result={"decoder": source.health()})
async def offer(self, key, path, params):
admit_sdp(params["sdp"])
if type(params.get("primary",False)) is not bool:raise ValueError("Invalid preview role")
# Inventory remains independent; these limits bound active media only.
if len(self.items) >= 4 or sum(item["key"] == key for item in self.items.values()) >= 2:
raise ValueError("Закройте лишний просмотр камеры.")
raise PreviewCapacityError("preview_capacity")
source = self.source(key, path)
pc = RTCPeerConnection(RTCConfiguration(iceServers=[]))
identifier = "peer_" + uuid.uuid4().hex
@@ -284,6 +345,8 @@ class Peers:
if frame
else None,
"fresh": frame is not None and time.monotonic() - observed < 2,
"decoder": source.health(),
"media_budget": entry["budget"].snapshot() if "budget" in entry else None,
}
)
)
@@ -302,6 +365,8 @@ class Peers:
@channel.on("message")
def message(value):
if value in ("view:primary", "view:secondary") and "budget" in entry:
entry["budget"].primary = value == "view:primary"
if value == "keepalive":
entry["seen"] = time.monotonic()
@@ -320,16 +385,23 @@ class Peers:
await asyncio.sleep(1)
try:
sender = pc.addTrack(Track(source))
allocation = await adapt_peer(pc, "video", primary=params.get("primary",False))
entry["budget"] = allocation
sender = pc.addTrack(Track(source, allocation))
cap_video_sender(sender, allocation)
transceiver = next(item for item in pc.getTransceivers() if item.sender == sender)
transceiver.setCodecPreferences(
[
codec
for codec in RTCRtpSender.getCapabilities("video").codecs
if codec.mimeType.lower() == "video/h264"
# Keep H264's standard repair transport. Omitting RTX
# forces NACK retries onto the primary SSRC, where old
# primary frames are deliberately rejected by admission.
if codec.mimeType.lower() in ("video/h264", "video/rtx")
]
)
await pc.setRemoteDescription(RTCSessionDescription(sdp=params["sdp"], type="offer"))
budget_peer(pc, "video", producer_id=allocation.id)
await pc.setLocalDescription(await pc.createAnswer())
task(watchdog())
return {"peer_id": identifier, "sdp": pc.localDescription.sdp, "type": "answer"}
@@ -381,6 +453,8 @@ class Engine:
future = asyncio.run_coroutine_threadsafe(work, self.loop)
try:
return {"state": "complete", "result": future.result(timeout=20)}
except PreviewCapacityError:
return failure("preview_capacity")
except FutureTimeout as error:
future.cancel()
raise RuntimeError("Camera preview timed out") from error