"""Preview decoding/adaptation never acquires a physical camera or a recorder.""" import asyncio import io import queue import threading import time from fractions import Fraction from types import SimpleNamespace import av import numpy as np import pytest from k1link.viewer.node_camera import CameraSource, CameraTrack, LeaseReader, open_live_camera from k1link.viewer.node_media import admit_sdp def test_mp4_lease_decodes_to_one_latest_frame_without_network_or_capture_change(): output = io.BytesIO() with av.open( output, "w", format="mp4", options={"movflags": "frag_keyframe+empty_moov+default_base_moof"}, ) as mux: stream = mux.add_stream("libx264", rate=15) stream.width, stream.height, stream.pix_fmt = 64, 48, "yuv420p" for index in range(10): frame = av.VideoFrame.from_ndarray( np.full((48, 64, 3), index * 10, dtype=np.uint8), format="rgb24" ) for packet in stream.encode(frame): mux.mux(packet) for packet in stream.encode(): mux.mux(packet) segments = queue.Queue() data = output.getvalue() for offset in range(0, len(data), 113): segments.put(("media", data[offset : offset + 113])) segments.put(None) lease = SimpleNamespace(segments=segments) class Camera: opened = 0 released = 0 streamed = 0 def snapshot(self): return { "generation": 7, "recording": { "source_end_expected": self.released > 0, "active": True, "producer_alive": True, "media_ready": True, "active_epoch": 7, }, } def open_delivery(self, generation, *, require_recording): assert generation == 7 and require_recording self.opened += 1 return lease def release_delivery(self, value, *, client_closed): assert value is lease and client_closed self.released += 1 def mark_streaming(self, value): assert value is lease self.streamed += 1 camera = Camera() source = CameraSource(camera) source.thread.join(3) source.close() source.thread.join(1) assert not source.thread.is_alive() assert source.sequence >= 1 and camera.streamed >= 1 assert camera.opened == camera.released == 1 def test_closing_consumer_unblocks_mp4_reader(): stopped = threading.Event() reader = LeaseReader(SimpleNamespace(segments=queue.Queue()), stopped) result = [] worker = threading.Thread(target=lambda: result.append(reader.read(12))) worker.start() stopped.set() worker.join(1) assert not worker.is_alive() and result == [b""] def test_live_fragment_is_decoded_without_waiting_for_future_frames_or_eof(): output = io.BytesIO() with av.open(output, "w", format="mp4", options={ "movflags": "empty_moov+default_base_moof+frag_every_frame", }) as mux: stream = mux.add_stream("libx264", rate=15) stream.width, stream.height, stream.pix_fmt = 64, 48, "yuv420p" stream.options = {"tune": "zerolatency", "g": "1"} for index in range(3): frame = av.VideoFrame.from_ndarray( np.full((48, 64, 3), index * 50, dtype=np.uint8), format="rgb24" ) for packet in stream.encode(frame): mux.mux(packet) # Capture while the producer remains live: no trailer or EOF. live = output.getvalue() segments = queue.Queue() segments.put(("media", live)) stopped, decoded = threading.Event(), threading.Event() def consume(): reader = LeaseReader(SimpleNamespace(segments=segments), stopped) with open_live_camera(reader) as container: for _frame in container.decode(video=0): decoded.set() break worker = threading.Thread(target=consume, daemon=True) worker.start() try: assert decoded.wait(1), "live preview waited for future data or EOF" finally: stopped.set() worker.join(2) assert not worker.is_alive() def test_camera_track_obeys_shared_budget_and_never_mutates_source_frame(): frame = av.VideoFrame(1280, 720, "yuv420p") frame.pts, frame.time_base = 123, Fraction(1, 90000) source = SimpleNamespace(closed=threading.Event(), current=lambda: (1, frame, time.monotonic())) budget = SimpleNamespace(video=lambda: (320, 4)) async def run(): track = CameraTrack(source, budget) try: result = await asyncio.wait_for(track.recv(), 1) assert result.width == 320 and result.height == 180 assert result.pts == 123 and result is not frame and frame.width == 1280 finally: track.stop() asyncio.run(run()) def test_camera_sdp_requires_exact_video_and_control_channel_and_private_ice(): invitation = ( "v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\n" "m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n" ) admit_sdp(invitation, camera=True) with pytest.raises(ValueError): admit_sdp(invitation) with pytest.raises(ValueError): admit_sdp(invitation + "m=audio 9 UDP/TLS/RTP/SAVPF 0\r\n", camera=True) with pytest.raises(ValueError): admit_sdp(invitation + "a=candidate:1 1 udp 1 8.8.8.8 1234 typ host\r\n", camera=True)