"""Actual codec caps, immutable point sampling and lease/recovery behavior.""" import asyncio import time from dataclasses import replace from fractions import Fraction import av import pytest from aiortc import RTCPeerConnection, VideoStreamTrack from aiortc.rtcrtpparameters import RTCRtpCodecParameters from missioncore_plugin_sdk.media_budget import MediaBudget, cap_video_sender from k1link.data_plane import ConsumerFrameContext, DecodedPointCloudView from k1link.viewer.node_rerun import preview_points def allocation(rate): return {"schema": "missioncore.media-budget/v1", "allocation_bps": rate, "ttl_ms": 3000} def test_profile_rate_recovery_has_no_second_hold_and_profile_debounces(): now = [100.0] b = MediaBudget("video", clock=lambda: now[0]) b.update(allocation(4_000_000)) assert b.video() == (1280, 15) b.update(allocation(100_000)) assert b.video() == (160, 2) and b.bps == 65000 now[0] = 101 b.update(allocation(4_000_000)) assert b.bps == 2_600_000 and b.video() == (160, 2) now[0] = 103 b.update(allocation(4_000_000)) assert b.video() == (1280, 15) now[0] = 107 assert b.video() == (0, 0) and b.cloud()[0] == 0 with pytest.raises(ConnectionError): b.update(allocation(True)) b.connection.close() def test_idle_observation_keeps_detail_and_zero_share_pauses_without_closing(): b = MediaBudget("video") b.update({**allocation(800_000), "mode": "observing"}) assert b.video() == (960, 6) b.update(allocation(0)) assert b.video() == (0, 0) and not b.closed b.update({**allocation(800_000), "mode": "control_reserved"}) assert b.video() == (640, 10) b.connection.close() @pytest.mark.parametrize("codec", ["H264", "VP8"]) def test_real_encoder_honors_node_below_vendor_floor_and_receiver_remb(codec): class Track(VideoStreamTrack): async def recv(self): frame = av.VideoFrame(64, 32, "yuv420p") for plane in frame.planes: plane.update(bytes(plane.buffer_size)) frame.pts = 0 frame.time_base = Fraction(1, 90000) return frame async def run(): pc = RTCPeerConnection() b = MediaBudget("video") b.update(allocation(80_000)) b.video() # Production Track selects its cadence before encoding. try: sender = pc.addTrack(Track()) cap_video_sender(sender, b) result = await sender._next_encoded_frame( RTCRtpCodecParameters(mimeType="video/" + codec, clockRate=90000, payloadType=96) ) encoder = sender._RTCRtpSender__encoder assert result and encoder.target_bitrate == 52000 if codec == "H264": assert max(map(len,result.payloads)) <= 1100 assert encoder.codec.framerate == b.video()[1] assert b.snapshot()["encoder_fps"] == b.video()[1] assert b.snapshot()["encoder_rate_control"] == "paced-h264-vbv/v2" assert b.encoder_frames == 1 and b.encoded_frame_bytes > 0 assert b.snapshot()["encode_timing"]["count"] == 1 assert sum(b.snapshot()["encode_timing"]["bins"]) == 1 assert encoder.codec.bit_rate == 52000 encoder.target_bitrate = 32000 assert encoder.target_bitrate == 52000 b.update(allocation(30_000)) assert encoder.target_bitrate == 19500 # Quiet imagery is not proof of a smaller allocation. Retain the # stock receiver floor, but allow Node's cap below it. b.target = 2_600_000 b.profile = (1280, 15) assert b.video() == (1280, 15) assert encoder.target_bitrate >= 250000 encoder.target_bitrate = 600000 assert encoder.target_bitrate == 600000 and b.video() == (1280, 15) # Node75 observation: a recovered Node allocation is only a ceiling; # receiver feedback can still keep the real encoder near its floor. b.target = 3_250_000 encoder.target_bitrate = 307644 assert encoder.target_bitrate == (500000 if codec == "H264" else 307644) assert b.bps == 3_250_000 and b.video() == (1280, 15) encoder.target_bitrate = 3_000_000 assert encoder.target_bitrate == (3_000_000 if codec == "H264" else 1_500_000) finally: await pc.close() b.connection.close() asyncio.run(run()) def test_cloud_sampling_preserves_alignment_and_never_changes_recorded_source(): now = time.monotonic_ns() frame = DecodedPointCloudView( ConsumerFrameContext(1, time.time_ns(), now, now, 100, True), "world", tuple((float(i), float(i + 1), float(i + 2)) for i in range(100)), bytes(range(100)), b"".join(bytes([i, i, i]) for i in range(100)), ) sampled = preview_points(frame, 9) assert sampled.point_count <= 9 and sampled.context is frame.context assert frame.point_count == 100 and len(frame.colors_rgb) == 300 for position, intensity, rgb in zip( sampled.positions_xyz, sampled.intensities, [sampled.colors_rgb[i : i + 3] for i in range(0, len(sampled.colors_rgb), 3)], strict=True, ): assert position[0] == intensity and rgb == bytes([intensity] * 3) assert preview_points(frame, 100) is frame assert preview_points(replace(frame, intensities=None, colors_rgb=None), 4).point_count <= 4 def test_transient_refresh_retains_lease_then_pauses_without_closing(monkeypatch): from missioncore_plugin_sdk.media_budget import adapt_peer calls=[] def exchange(self,active=True): calls.append(active) if active and calls.count(True)>1:raise ConnectionError("offline") return allocation(800_000) monkeypatch.setattr(MediaBudget,"exchange",exchange) async def run(): pc=RTCPeerConnection();b=await adapt_peer(pc,"video") try: until=b.valid_until await asyncio.sleep(.6) assert pc.connectionState!="closed" and b.bps>0 and b.valid_until==until b.clock=lambda:until+1 assert b.bps==0 and b.video()==(0,0) b.update(allocation(800_000)) assert b.bps>0 and pc.connectionState!="closed" finally:await pc.close();await b.close() assert False in calls asyncio.run(run()) def test_allocation_age_includes_request_time(): b=MediaBudget("video",clock=lambda:100.0) b.update(allocation(800_000),requested_at=96.0) assert b.bps==0 b.connection.close() @pytest.mark.parametrize("expired", [False, True]) def test_selected_frame_during_pause_preserves_codec_and_pending_keyframe(expired): from aiortc.codecs.h264 import h264_depayload async def run(): now = [100.] b = MediaBudget("video", clock=lambda: now[0]) b.update(allocation(1_000_000)) b.video() class Track(VideoStreamTrack): number = 0 async def recv(self): frame = av.VideoFrame(64, 32, "yuv420p") for plane in frame.planes: plane.update(bytes([100]) * plane.buffer_size) frame.pts, frame.time_base = self.number * 9000, Fraction(1, 90000) self.number += 1 return frame pc = RTCPeerConnection() try: sender = pc.addTrack(Track()) cap_video_sender(sender, b) codec = RTCRtpCodecParameters(mimeType="video/H264", clockRate=90000, payloadType=96) assert await sender._next_encoded_frame(codec) encoder = sender._RTCRtpSender__encoder original = encoder.codec if expired: now[0] += 4 else: b.update(allocation(0)) sender._RTCRtpSender__force_keyframe = True assert await sender._next_encoded_frame(codec) is None assert await sender._next_encoded_frame(codec) is None assert encoder.codec is original and original.bit_rate == 650_000 assert b.encoder_frames == 1 and b.encoder_paused_frames == 2 b.update(allocation(1_000_000)) resumed = await sender._next_encoded_frame(codec) assert resumed and resumed.timestamp == 27000 assert encoder.codec is original and b.encoder_reinitializations == 0 # A keyframe request consumed by aiortc during the pause must still # produce an independently decodable frame once credit returns. decoder = av.CodecContext.create("h264", "r") frame = decoder.decode(av.Packet(b"".join(h264_depayload(p) for p in resumed.payloads)))[0] assert frame.key_frame finally: await pc.close() b.connection.close() asyncio.run(run()) def test_grant_change_inside_encode_does_not_poison_codec(monkeypatch): from missioncore_plugin_sdk import preview_h264 async def run(): b = MediaBudget("video", clock=lambda: 100.) b.update(allocation(1_000_000)) b.video() original = preview_h264.encode_preview_frame def change_grant(*args): b.update(allocation(0)) return original(*args) monkeypatch.setattr(preview_h264, "encode_preview_frame", change_grant) pc = RTCPeerConnection() try: sender = pc.addTrack(VideoStreamTrack()) cap_video_sender(sender, b) result = await sender._next_encoded_frame( RTCRtpCodecParameters(mimeType="video/H264", clockRate=90000, payloadType=96) ) encoder = sender._RTCRtpSender__encoder assert result and encoder.codec.bit_rate == 650_000 assert b.bps == 0 and b.encoder_bps == 650_000 assert encoder.frame_ceiling is None # Encoding local pixels grants no network credit. The live Node # packet gate, tested separately, still refuses every zero grant. finally: await pc.close() b.connection.close() asyncio.run(run())