fix(video): recover encoder capacity, pace RTP and isolate preview sessions

This commit is contained in:
DCCONSTRUCTIONS
2026-11-21 20:58:25 +03:00
parent 3d04fa45d3
commit bed1db3508
29 changed files with 1534 additions and 141 deletions
@@ -1,27 +1,88 @@
"""Debounce expensive codec upgrades; never enlarge the caller's bitrate ceiling."""
"""Coalesce codec upgrades without delaying reductions or exceeding either cap."""
from collections import deque
from math import sqrt
class SpatialQuality:
"""Bound live H264 pixel count by its applied rate, without reducing cadence.
A 0.04 bits/pixel/frame starting envelope avoids feeding HD motion into a
tens-of-kbit encoder. It is a sizing policy, not a guaranteed image-quality
score. Keep native aspect ratio and the producer's upper size bound. The
codec owns this state; Track/Node allocation and recording stay independent.
"""
BITS_PER_PIXEL_FRAME = 0.04
WIDTHS = (160, 320, 480, 640, 960, 1280)
def __init__(self, clock):
self.clock = clock
self.width = None
self.aspect = None
self.pending = None
def select(self, width, height, fps, bitrate):
aspect = width / height
limit = sqrt(max(1, bitrate) * aspect / (max(1, fps) * self.BITS_PER_PIXEL_FRAME))
choices = sorted({min(width, w) for w in self.WIDTHS} | {width})
desired = max((w for w in choices if w <= limit), default=choices[0])
now = self.clock()
if self.width is None or self.aspect != aspect:
self.width, self.aspect, self.pending = desired, aspect, None
# Never upscale a smaller source/Node profile, even during debounce.
self.width = min(self.width, width)
if desired <= self.width:
# Rate cuts apply on this frame. Holding HD for another second at
# 32k only manufactures gray frames; reduce size at the same reset.
self.width = desired
self.pending = None
else:
if self.pending is None:
self.pending = now
# A moving recovery ramp does not restart continuous improvement.
if now - self.pending >= 2:
self.width, self.pending = desired, None
out_width = max(2, int(self.width) // 2 * 2)
out_height = max(2, int(out_width / aspect) // 2 * 2)
return out_width, out_height
class CodecRecovery:
# libx264 requires a new context for our pinned VBV configuration. A moving
# REMB ramp is one recovery, not a new stream every 10% of bitrate. Wait for
# an unchanged 2 s target, with a 6 s bound so continuous growth cannot pin quality.
SETTLE_SECONDS = 2.0
MAX_WAIT_SECONDS = 6.0
def __init__(self, clock):
self.clock = clock
self.pending = None
self.samples = deque(maxlen=128)
def select(self, requested, applied):
# aiortc recreates libx264 above a 10% change. Every reduction and initial
# creation retain the original path; brief gains need not restart a GOP.
if applied is None or requested * 10 <= applied * 11:
self.pending = None
self.samples.clear()
return requested
now = self.clock()
if self.pending is None:
self.pending = (now, requested)
started, floor = self.pending
floor = min(floor, requested)
self.pending = (started, floor)
if now - started >= 2:
# This sustained floor completes one upgrade. A later, higher
# request must earn its own window instead of inheriting this floor
# forever after the encoder applies it.
self.pending = (now, now, requested)
started, settled, anchor = self.pending
# Every target change restarts settling. The encoder already has a 10%
# recreation threshold; reusing that threshold here treats a slow REMB
# ramp as stable and keeps recreating the codec every few seconds.
# The overall deadline still guarantees progress during continuous growth.
if requested != anchor:
settled, anchor = now, requested
self.pending = (started, settled, anchor)
self.samples.append((now, requested))
while len(self.samples) > 1 and self.samples[1][0] <= now - self.SETTLE_SECONDS:
self.samples.popleft()
if (now - settled >= self.SETTLE_SECONDS
or now - started >= self.MAX_WAIT_SECONDS):
floor = min(rate for _, rate in self.samples)
self.pending = None
return floor
self.samples.clear()
return min(requested, floor)
return applied
@@ -9,7 +9,9 @@ import importlib.metadata
import json
import socket
import time
from contextvars import ContextVar
from .rtp_send_clock import restamp
from .runtime_metrics import LatencyStats
SOCKET = "/run/mission-core-node/budget.sock"
@@ -54,11 +56,14 @@ class BudgetClient:
self.requests += 1
try:
if self.writer is None:
self.reader, self.writer = await asyncio.open_unix_connection(SOCKET, limit=4096)
self.reader, self.writer = await asyncio.open_unix_connection(
SOCKET, limit=4096)
request = {"class": self.traffic_class, "bytes": size}
if self.producer_id: request["producer_id"] = self.producer_id
if self.producer_id:
request["producer_id"] = self.producer_id
body = json.dumps(request).encode()
self.writer.write(b"POST /permit HTTP/1.1\r\nHost: local\r\nContent-Type: application/json\r\nContent-Length: "
self.writer.write(b"POST /permit HTTP/1.1\r\nHost: local\r\n"
b"Content-Type: application/json\r\nContent-Length: "
+ str(len(body)).encode() + b"\r\n\r\n" + body)
await self.writer.drain()
header = await self.reader.readuntil(b"\r\n\r\n")
@@ -137,8 +142,10 @@ def budget_peer(pc, traffic_class, *, client=None, clock=time.monotonic, produce
if importlib.metadata.version("aiortc") != "1.14.0":
raise RuntimeError("Qualify the media budget adapter for this aiortc version")
client = client or BudgetClient(traffic_class, producer_id)
transports = {t.sender.transport.transport for t in pc.getTransceivers()}
dtls_transports = {t.sender.transport for t in pc.getTransceivers()}
transports = {dtls.transport for dtls in dtls_transports}
if pc.sctp is not None:
dtls_transports.add(pc.sctp.transport)
transports.add(pc.sctp.transport.transport)
if not transports:
raise ValueError("Peer has no admitted transport")
@@ -152,9 +159,12 @@ def budget_peer(pc, traffic_class, *, client=None, clock=time.monotonic, produce
frame_sources[retry.to_bytes(4, "big")] = primary.to_bytes(4, "big")
workers, counters = [], []
metrics = {"sent_bytes": 0, "expired_frames": 0, "expired_datagrams": 0,
"queue_dropped": 0, "stale_rtp_packets": 0, "protocol_bytes": 0, "protocol_dropped": 0,
"queue_dropped": 0, "stale_rtp_packets": 0, "protocol_bytes": 0,
"protocol_dropped": 0,
"max_permit_wait_ms": 0.0, "close_reason": None, "keyframe_requests": 0,
"retransmitted_packets": 0, "retained_frame_deadlines": 0}
"retransmitted_packets": 0, "retained_frame_deadlines": 0,
"pacing_boundary": "before_srtp/v1", "send_clock_updates": 0,
"max_send_clock_correction_ms": 0.0}
pc._missioncore_admission_metrics = getattr(client, "snapshot", lambda: {})
pc._missioncore_egress_metrics = metrics
pc._missioncore_pending_media = lambda: sum(value[0] for value in counters)
@@ -183,6 +193,9 @@ def budget_peer(pc, traffic_class, *, client=None, clock=time.monotonic, produce
raise ValueError("Peer already has an egress budget")
transport._missioncore_budget = True
original, frames, history = transport._send, {}, {}
# A permit belongs to one task and one encryption call. The ICE layer
# consumes it exactly once; unrelated/SCTP writes cannot inherit credit.
admitted = ContextVar("missioncore_rtp_credit", default=None)
queue, pending = asyncio.Queue(maxsize=64), [0]
protocol = [8192.0, clock()]
counters.append(pending)
@@ -216,7 +229,17 @@ def budget_peer(pc, traffic_class, *, client=None, clock=time.monotonic, produce
workers.append(asyncio.create_task(drain()))
async def send(data, queue=queue, pending=pending, frames=frames, history=history, protocol=protocol, deliver=deliver):
async def send(data, queue=queue, pending=pending, frames=frames, history=history,
protocol=protocol, deliver=deliver, admitted=admitted, rtp_deliver=None):
credit = admitted.get()
if credit is not None:
admitted.set(None)
if len(data) > credit:
retire("invalid_srtp_size")
raise BudgetProtocolError("SRTP exceeds its admission")
await deliver(data, clock() + MEDIA_LIFETIME)
metrics["sent_bytes"] += len(data)
return
if _essential(data):
# A bounded protocol allowance bypasses disposable SCTP backlog.
# ICE connectivity checks use their existing transport path.
@@ -239,6 +262,15 @@ def budget_peer(pc, traffic_class, *, client=None, clock=time.monotonic, produce
retire("oversized_datagram")
raise BudgetProtocolError("Media datagram exceeds budget contract")
if len(data) >= 12 and 128 <= data[0] <= 191:
if rtp_deliver is None:
retire("unadmitted_rtp")
raise BudgetProtocolError("RTP must be admitted before encryption")
# Pinned SRTP profiles append at most 16 authentication bytes.
# Charge that upper bound; count actual wire bytes at ICE.
wire_limit = len(data) + 16
if wire_limit > MAX_PACKET:
retire("oversized_datagram")
raise BudgetProtocolError("RTP exceeds budget contract")
ssrc, stamp = data[8:12], int.from_bytes(data[4:8], "big")
retry = ssrc in frame_sources
ssrc = frame_sources.get(ssrc, ssrc)
@@ -247,8 +279,10 @@ def budget_peer(pc, traffic_class, *, client=None, clock=time.monotonic, produce
# NACK commonly arrives after the next primary frame. Keep
# only deadline metadata (never payload) for known frames;
# RTX cannot create or renew a lease, or roll back latest.
known = current if current is not None and current[0] == stamp else history.get((ssrc, stamp))
if known is None or (known is not current and (known[2] or clock() >= known[1])):
known = (current if current is not None and current[0] == stamp
else history.get((ssrc, stamp)))
if (known is None
or (known is not current and (known[2] or clock() >= known[1]))):
metrics["stale_rtp_packets"] += 1
return
current = known
@@ -273,9 +307,8 @@ def budget_peer(pc, traffic_class, *, client=None, clock=time.monotonic, produce
try:
if started >= current[1]:
raise BudgetDeferred("Frame expired")
await client.acquire(len(data), deadline=current[1])
await deliver(data, current[1])
metrics["sent_bytes"] += len(data)
await client.acquire(wire_limit, deadline=current[1])
await rtp_deliver(data, current[1], wire_limit)
if retry:
metrics["retransmitted_packets"] += 1
except BudgetDeferred:
@@ -286,7 +319,8 @@ def budget_peer(pc, traffic_class, *, client=None, clock=time.monotonic, produce
retire("admission_or_transport_error")
raise ConnectionError("Media egress unavailable") from None
finally:
metrics["max_permit_wait_ms"] = max(metrics["max_permit_wait_ms"], (clock() - started) * 1000)
metrics["max_permit_wait_ms"] = max(
metrics["max_permit_wait_ms"], (clock() - started) * 1000)
return
# SCTP sees ordinary bounded datagram loss and can retransmit within
# its own protocol. Overflow cannot tear down an otherwise live peer.
@@ -297,6 +331,40 @@ def budget_peer(pc, traffic_class, *, client=None, clock=time.monotonic, produce
queue.put_nowait((data, clock() + MEDIA_LIFETIME))
transport._send = send
for dtls in dtls_transports:
if dtls.transport is not transport:
continue
original_rtp = dtls._send_rtp
senders = [t.sender for t in pc.getTransceivers() if t.sender.transport is dtls]
async def encrypt(data, expires, wire_limit, original_rtp=original_rtp,
senders=senders, admitted=admitted):
remaining = expires - clock()
if remaining <= 0:
raise BudgetDeferred("Frame expired before encryption")
data, correction = restamp(data, senders)
if correction is not None:
metrics["send_clock_updates"] += 1
metrics["max_send_clock_correction_ms"] = max(
metrics["max_send_clock_correction_ms"], correction)
token = admitted.set(wire_limit)
try:
# The send stamp describes actual egress, after our wait.
# Encryption/authentication and ICE remain aiortc-owned.
await asyncio.wait_for(original_rtp(data), remaining)
except TimeoutError:
raise BudgetDeferred("Media send expired") from None
finally:
admitted.reset(token)
async def send_rtp(data, original_rtp=original_rtp, send=send, encrypt=encrypt):
from aiortc.rtp import is_rtcp
if is_rtcp(data):
await original_rtp(data)
else:
await send(data, rtp_deliver=encrypt)
dtls._send_rtp = send_rtp
@pc.on("connectionstatechange")
async def changed():
@@ -13,7 +13,7 @@ import threading
import time
import uuid
from .codec_recovery import CodecRecovery
from .codec_recovery import CodecRecovery, SpatialQuality
from .h264_packetizer import RTP_PAYLOAD_BYTES, packetize_h264
from .link_budget import BudgetProtocolError, _Connection
from .runtime_metrics import LATENCY_BOUNDS_MS, LatencyStats
@@ -30,8 +30,11 @@ class MediaBudget:
self.allocation = 0
self.profile = self.candidate = (0, 0)
self.candidate_at = 0
self.profile_mode = None
self.degrading_at = None
self.encoder_bps = self.receiver_bps = self.encode_ms = 0
self.encoder_fps = None
self.encoder_size = None
self.encoder_rate_control = None
self.egress = lambda: {}
self.admission = lambda: {}
@@ -100,29 +103,52 @@ class MediaBudget:
return int(self.target) if not self.closed and self.clock() < self.valid_until else 0
def video(self):
# Source-limited bitrate / REMB cannot determine spatial quality. A quiet
# scene must retain detail. Observation trades FPS before resolution.
# Node owns the source cadence and maximum size. Receiver congestion
# may further constrain encoder size, but must not pin Track at 1–2 FPS
# merely because a quiet scene produces little traffic.
driving = ((1_800_000, 1280, 15), (900_000, 960, 12), (450_000, 640, 10),
(180_000, 480, 6), (70_000, 320, 4), (16_000, 160, 2))
observing = ((1_800_000, 1280, 15), (900_000, 1280, 8), (450_000, 960, 6),
(180_000, 640, 4), (70_000, 480, 2), (16_000, 320, 1))
ladder = observing if self.mode == "observing" else driving
desired = next(((w, fps) for threshold, w, fps in ladder if self.bps >= threshold), (0, 0))
rate = self.bps
desired = next(((w, fps) for threshold, w, fps in ladder if rate >= threshold), (0, 0))
now = self.clock()
if self.bps <= 0:
if desired == (0, 0):
# Pausing payload must not turn the next grant into a fresh start
# that bypasses the existing spatial-upgrade debounce.
self.candidate, self.candidate_at = self.profile, now
self.degrading_at = None
return (0, 0)
if (self.profile == (0, 0) or desired[0] < self.profile[0]
or (desired[0] == self.profile[0] and desired[1] <= self.profile[1])):
if self.profile == (0, 0) or self.profile_mode != self.mode:
self.profile = desired
self.candidate = desired
self.candidate_at = now
elif desired != self.candidate:
self.candidate, self.candidate_at = desired, now
elif now - self.candidate_at >= 2:
self.profile = desired
self.degrading_at = None
self.profile_mode = self.mode
elif desired < self.profile:
# The bitrate and per-packet gate shrink immediately. Resolution
# and cadence need a sustained lower allocation (two normal 0.5 s
# refresh periods), not the first tiny grant after a short pause.
self.candidate, self.candidate_at = self.profile, now
if self.degrading_at is None:
self.degrading_at = now
if now - self.degrading_at >= 1:
self.profile = self.candidate = desired
self.degrading_at = None
elif desired > self.profile:
self.degrading_at = None
if self.candidate <= self.profile:
self.candidate_at = now
# Higher grants during recovery are still continuous improvement.
# Restarting for each rung held a recorded 0.5 s recovery ramp at
# 2 FPS for five seconds. A relapse or pause resets this interval.
self.candidate = desired
if now - self.candidate_at >= 2:
self.profile = desired
else:
self.candidate, self.candidate_at = self.profile, now
self.degrading_at = None
return self.profile
def cloud(self, maximum=5000, bytes_per_point=32):
@@ -142,6 +168,7 @@ class MediaBudget:
"max_width": width, "max_fps": fps, "mode": self.mode, "reason": self.reason,
"encoder_bps": self.encoder_bps, "receiver_bps": self.receiver_bps,
"encoder_fps": self.encoder_fps, "encoder_rate_control": self.encoder_rate_control,
"encoder_size": self.encoder_size,
"encode_ms": self.encode_ms, "egress": dict(self.egress()),
"encoder_frames": self.encoder_frames, "encoder_reinitializations": self.encoder_reinitializations,
"encoder_paused_frames": self.encoder_paused_frames,
@@ -219,6 +246,7 @@ def cap_video_sender(sender, budget):
raise RuntimeError("Qualify adaptive media for this aiortc version")
from aiortc.codecs import h264, vpx
from aiortc.mediastreams import VIDEO_TIME_BASE, convert_timebase
from .preview_h264 import encode_preview_frame
class Capped:
@@ -245,7 +273,16 @@ def cap_video_sender(sender, budget):
budget.encoder_frames += 1
if before is not None and before is not getattr(self, "codec", None):
budget.encoder_reinitializations += 1
budget.last_encoder_reset = {"reason": "encoder_recreated", "frame": budget.encoder_frames,
budget.last_encoder_reset = {"reason": "+".join(
reason for reason, changed in (
("size", (before.width, before.height)
!= (self.codec.width, self.codec.height)),
("cadence", before.framerate != self.codec.framerate),
("bitrate", before.bit_rate != self.codec.bit_rate),
) if changed) or "encoder_recreated", "frame": budget.encoder_frames,
"before_bps": before.bit_rate, "after_bps": self.codec.bit_rate,
"before_fps": float(before.framerate) if before.framerate else None,
"after_fps": float(self.codec.framerate) if self.codec.framerate else None,
"mono_ms": round(budget.clock() * 1000, 3),
"before_size": [getattr(before, "width", None), getattr(before, "height", None)],
"after_size": [getattr(self.codec, "width", None), getattr(self.codec, "height", None)]}
@@ -256,6 +293,7 @@ def cap_video_sender(sender, budget):
budget.encode_timing.observe(elapsed)
budget.encode_ms = round(elapsed * 1000, 3)
budget.encoder_bps = getattr(self.codec, "bit_rate", self.target_bitrate)
budget.encoder_size = [getattr(self.codec, "width", None), getattr(self.codec, "height", None)]
rate = getattr(getattr(self, "codec", None), "framerate", None)
budget.encoder_fps = float(rate) if rate is not None else None
return result
@@ -271,24 +309,36 @@ def cap_video_sender(sender, budget):
@target_bitrate.setter
def target_bitrate(self, value):
budget.receiver_bps = int(value)
self.network_target = max(self.receiver_min, min(int(value), self.receiver_max))
# This adapter already qualifies low-rate encoding. The stock
# H264 floor (500 kbit/s) would otherwise overrule receiver REMB
# during congestion, even when Node's own allocation is high.
self.network_target = max(16000, min(int(value), self.receiver_max))
class H264(Capped, h264.H264Encoder):
def __init__(self):
super().__init__()
self.recovery = CodecRecovery(budget.clock)
self.spatial_quality = SpatialQuality(budget.clock)
self.encoding_target = None
budget.encoder_rate_control = "paced-h264-vbv/v2"
budget.encoder_rate_control = "coalesced-h264-vbv/v5"
def _encode_frame(self, frame, force_keyframe):
# profile retains the last cadence while a zero grant pauses Track.
# Read its tuple only: spatial adaptation belongs to Track's event
# loop, not this encoder executor thread.
# Read its tuple only: Node profile adaptation belongs to Track's
# event loop. Additional codec sizing is local to this encoder.
requested = Capped.target_bitrate.fget(self)
applied = self.codec.bit_rate if self.codec is not None else None
self.encoding_target = self.recovery.select(requested, applied)
try:
yield from encode_preview_frame(self, frame, force_keyframe, budget.profile[1] or 15)
fps = budget.profile[1] or 15
# Use the actual coalesced encoder rate, not only Node's grant.
# A receiver REMB of 32k with a 5M Node grant previously left HD
# at 15 FPS: valid decoded frames, but almost entirely gray.
width, height = self.spatial_quality.select(
frame.width, frame.height, fps, self.target_bitrate)
if (frame.width, frame.height) != (width, height):
frame = frame.reformat(width=width, height=height, format="yuv420p")
yield from encode_preview_frame(self, frame, force_keyframe, fps)
finally:
self.encoding_target = None
@@ -0,0 +1,24 @@
"""Send-time extension at the qualified aiortc 1.14 plaintext boundary."""
from aiortc import clock
from aiortc.rtp import RtpPacket
def restamp(data, senders):
ssrc = int.from_bytes(data[8:12], "big")
for sender in senders:
if ssrc not in (getattr(sender, "_ssrc", None), getattr(sender, "_rtx_ssrc", None)):
continue
mapping = sender._RTCRtpSender__rtp_header_extensions_map
packet = RtpPacket.parse(data, mapping)
previous = packet.extensions.abs_send_time
if previous is None:
return data, None
current = (clock.current_ntp_time() >> 14) & 0xFFFFFF
packet.extensions.abs_send_time = current
# 24-bit, 6.18 seconds: wrap at 64 s. Diagnostic only, never a lease.
correction_ms = ((current - previous) & 0xFFFFFF) * 1000 / 2**18
return packet.serialize(mapping), correction_ms
# Sender registration precedes any aiortc RTP send. An unknown sender is
# an adapter/qualification error; do not silently send a false timestamp.
raise ValueError("RTP sender was not registered")