import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1])) import pytest def test_video_protocol_rejects_duplicate_people(tmp_path): from llm_services.video_edit.protocol import validate src = tmp_path / "source.mp4" src.touch() ref = tmp_path / "ref.png" ref.touch() payload = { "video_path": str(src), "analysis_id": "abc", "analysis_token": "a" * 64, "prompt": "replace", "replacements": [{"person_id": "person_0001", "image_path": str(ref)}] * 2, } with pytest.raises(ValueError, match="Duplicate"): validate("video.replace", payload, {}, tmp_path) def test_tracking_rejects_ambiguous_crossing(): from llm_services.video_edit.tracking import Tracker tracker = Tracker() tracker.update([(0, 0, 10, 10), (20, 0, 30, 10)]) with pytest.raises(ValueError, match="ambiguous"): tracker.update([(9, 0, 19, 10), (11, 0, 21, 10)]) def test_protected_composite_preserves_unselected_pixels(): import numpy as np from llm_services.video_edit.tracking import composite source = np.zeros((8, 8, 3), dtype=np.uint8) generated = np.full_like(source, 255) selected = np.zeros((8, 8), dtype=bool) selected[1:5, 1:5] = True protected = np.zeros_like(selected) protected[3:7, 3:7] = True result = composite(source, generated, selected, protected, feather=2) assert not result[~selected].any() assert not result[protected].any() assert result[2, 2].any() def test_binding_checks_principal_source_and_manifest(): from llm_services.video_edit.protocol import verify_binding binding = { "principal": "a", "source_sha256": "s", "profile": "wan-animate-replace-v1", "manifest_sha256": "m", } with pytest.raises(ValueError, match="binding"): verify_binding(binding, principal="b", source_sha256="s", manifest_sha256="m") def test_registry_and_square_reference(tmp_path): from llm_services.runner import validate_request from llm_services.store import TASK_TYPES, Settings assert {"video.people.analyze", "video.replace"} <= TASK_TYPES settings = Settings(tmp_path, tmp_path) assert settings.memory_estimates_gib["video.replace"] >= 160 ref = tmp_path / "ref.png" ref.touch() result = validate_request( { "task_type": "image.reference.generate", "input": {"prompt": "edit", "image_paths": [str(ref)]}, "parameters": { "profile": "qwen-image-edit-2511-v1", "width": 1024, "height": 1024, }, "output_dir": str(tmp_path / "outputs" / "job"), }, workspace=tmp_path, ) assert result["parameters"]["width"] == 1024 def test_video_capability_is_disabled_until_certified(tmp_path): from llm_services.store import Settings from llm_services.video_edit.profiles import capabilities assert capabilities(Settings(tmp_path, tmp_path))["available"] is False def test_replacement_conditioning_uses_both_prompts_and_reference(tmp_path): from llm_services.video_edit.replace import conditioning result = conditioning( {"prompt": "global", "negative_prompt": "bad"}, {"prompt": "actor", "image_path": "reference.png"}, ) assert result == { "prompt": "global\nactor", "negative_prompt": "bad", "reference_path": "reference.png", } def test_decode_dimensions_preserve_portrait_and_budget(): from llm_services.video_edit.media import dimensions width, height = dimensions(1080, 1920, 399360) assert width % 16 == height % 16 == 0 assert width * height <= 399360 and height > width def test_analysis_binding_rejects_source_change_and_wrong_owner(tmp_path): from llm_services.store import Settings, atomic_json, initialize_store from llm_services.video_edit.bindings import analysis_manifest, principal from llm_services.video_edit.protocol import PROFILE, sha256, token settings = Settings(tmp_path / "app", tmp_path) settings.key_file.parent.mkdir(parents=True) settings.key_file.write_text("secret") store = initialize_store(settings) source = tmp_path / "video.mp4" source.write_bytes(b"original") p = {"profile": PROFILE, "fps": 24, "max_pixels": 399360} job = store.submit( "video.people.analyze", {"video_path": str(source)}, p, scheduling={"principal_id": "alice"}, ) root = settings.outputs_dir / job["id"] / ".private" root.mkdir(parents=True) atomic_json(root / "manifest.json", {"people": {"person_0001": {}}}) binding = { "profile": PROFILE, "source_sha256": sha256(source), "principal": principal(settings, {"principal_id": "alice"}), "manifest_sha256": sha256(root / "manifest.json"), } atomic_json(root / "binding.json", binding) # The resolver consumes the actual persisted job success, never a client assertion. with store._connection() as db: db.execute("UPDATE jobs SET state='succeeded' WHERE id=?", (job["id"],)) inputs = { "analysis_id": job["id"], "analysis_token": token(binding), "video_path": str(source), "replacements": [{"person_id": "person_0001"}], } assert analysis_manifest(settings, store, inputs, p, binding["principal"]) == str( root / "manifest.json" ) with pytest.raises(ValueError, match="principal"): analysis_manifest( settings, store, inputs, p, principal(settings, {"principal_id": "bob"}) ) source.write_bytes(b"changed") with pytest.raises(ValueError, match="binding"): analysis_manifest(settings, store, inputs, p, binding["principal"]) def test_tracker_retains_ids_when_detector_order_changes(): from llm_services.video_edit.tracking import Tracker tracker = Tracker() tracker.update([(0, 0, 10, 30), (30, 0, 40, 30)]) result = tracker.update([(31, 0, 41, 30), (1, 0, 11, 30)]) assert result["person_0001"] == (1, 0, 11, 30) assert result["person_0002"] == (31, 0, 41, 30) def test_composition_accumulates_two_people_without_changing_background(): import numpy as np from llm_services.video_edit.tracking import composite original = np.zeros((4, 6, 3), dtype="uint8") first = np.zeros((4, 6), bool) first[:, :2] = True second = np.zeros_like(first) second[:, 4:] = True one = composite(original, np.full_like(original, 70), first, second, 0) both = composite(one, np.full_like(original, 190), second, first, 0) assert (both[first] == 70).all() assert (both[second] == 190).all() assert (both[~(first | second)] == 0).all() def test_cfr_mux_preserves_frames_and_source_audio(tmp_path): import shutil from llm_services.video_edit.media import command, decode, mux, probe if not shutil.which("ffmpeg") or not shutil.which("ffprobe"): pytest.skip("FFmpeg/ffprobe required for real CPU media verification") source = tmp_path / "source.mp4" command( [ "ffmpeg", "-v", "error", "-f", "lavfi", "-i", "testsrc2=size=96x64:rate=30:duration=1", "-f", "lavfi", "-i", "sine=frequency=440:duration=1", "-c:v", "libx264", "-c:a", "aac", "-shortest", str(source), ] ) video = decode(source, tmp_path / "frames", 399360, 120) assert video["frames"] == 24 and video["source_has_audio"] output = tmp_path / "out.mp4" mux(tmp_path / "frames", source, output, video, True) media = probe(output) assert any(stream["codec_type"] == "audio" for stream in media["streams"]) assert abs(float(media["format"]["duration"]) - 1) < 0.05 def test_bounded_windows_carry_previous_generated_frame_and_no_duplicates(): from llm_services.video_edit.temporal import generate_windows calls = [] def generate(start, end, previous): calls.append((start, end, previous)) return list(range(start, end)) assert list(generate_windows(160, generate)) == list(enumerate(range(160))) assert calls == [(0, 77, None), (76, 153, 76), (152, 160, 152)] assert max(end - start for start, end, _ in calls) == 77 def test_native_previous_conditioning_is_injected_only_for_first_segment(): from llm_services.video_edit.temporal import CarryConditioningMixin class Frame: def to(self, **kwargs): return self class Native: def prepare_prev_segment_cond_latents( self, prev_segment_cond_video=None, **kwargs ): return prev_segment_cond_video, kwargs["start_frame"] class Pipeline(CarryConditioningMixin, Native): pass pipe = Pipeline() carried = Frame() pipe.carried_frame = carried assert pipe.prepare_prev_segment_cond_latents(start_frame=0, device="cpu") == ( carried, 1, ) native = object() assert pipe.prepare_prev_segment_cond_latents( native, start_frame=76, device="cpu" ) == (native, 76) @pytest.mark.parametrize( ("stream", "expected"), [ ({"width": 192, "height": 96, "side_data_list": [{"rotation": 90}]}, (96, 192)), ( {"width": 192, "height": 96, "side_data_list": [{"rotation": -90}]}, (96, 192), ), ({"width": 192, "height": 96, "tags": {"rotate": "90"}}, (96, 192)), ({"width": 192, "height": 96, "sample_aspect_ratio": "2:1"}, (384, 96)), ( { "width": 192, "height": 96, "sample_aspect_ratio": "2:1", "side_data_list": [{"rotation": 90}], }, (96, 384), ), ], ) def test_display_dimensions_follow_rotation_and_sample_aspect(stream, expected): from llm_services.video_edit.media import display_dimensions assert display_dimensions(stream) == expected def test_detector_wrapper_preserves_rgb_through_official_read_img(): import numpy as np from llm_services.video_edit.preprocess import prepare_detector_frame from wan_read_img_fixture import read_img class Detector: def preprocess(self, image): return read_img(image) rgb = np.array([[[230, 45, 17], [5, 91, 210]]], dtype="uint8") original = rgb.copy() assert np.array_equal(prepare_detector_frame(Detector(), rgb), original) assert np.array_equal(rgb, original) def test_video_pixel_cap_is_explicit_and_limits_submissions(tmp_path, monkeypatch): from llm_services.store import Settings from llm_services.video_edit import profiles settings = Settings( tmp_path, tmp_path, video_edit_max_pixels=921600, video_edit_poc_enabled=True ) monkeypatch.setattr(profiles, "deployment", lambda settings: {"validated": True}) assert profiles.capabilities(settings)["max_pixels"] == 921600 profiles.validate_submission(settings, {}, {"max_pixels": 921600}) settings.video_edit_max_pixels = 399360 with pytest.raises(ValueError, match="pixel"): profiles.validate_submission(settings, {}, {"max_pixels": 921600}) @pytest.mark.parametrize( ("rotation", "sar", "expected"), [(90, "1/1", (96, 192)), (0, "2/1", (384, 96)), (90, "2/1", (96, 384))], ) def test_real_decode_preserves_display_geometry(tmp_path, rotation, sar, expected): import shutil from llm_services.video_edit.media import command, decode, mux, probe from PIL import Image if not shutil.which("ffmpeg") or not shutil.which("ffprobe"): pytest.skip("FFmpeg/ffprobe required for rotation/SAR CPU regression") raw = tmp_path / "raw.mp4" command( [ "ffmpeg", "-v", "error", "-f", "lavfi", "-i", "testsrc2=size=192x96:rate=24:duration=1", "-vf", f"setsar={sar}", "-c:v", "libx264", str(raw), ] ) source = tmp_path / "source.mp4" command( [ "ffmpeg", "-v", "error", "-display_rotation", str(rotation), "-i", str(raw), "-c", "copy", str(source), ] ) source_stream = next( s for s in probe(source)["streams"] if s["codec_type"] == "video" ) actual_rotation = next( ( item["rotation"] for item in source_stream.get("side_data_list", []) if "rotation" in item ), 0, ) assert actual_rotation == rotation, ( "Fixture must carry the requested display matrix" ) assert source_stream["sample_aspect_ratio"] == sar.replace("/", ":") video = decode(source, tmp_path / "frames", 399360, 120) assert (video["width"], video["height"]) == expected with Image.open(tmp_path / "frames" / "000000.png") as frame: assert frame.size == expected output = tmp_path / "normalized.mp4" mux(tmp_path / "frames", source, output, video, False) stream = next(s for s in probe(output)["streams"] if s["codec_type"] == "video") assert (stream["width"], stream["height"]) == expected assert stream.get("sample_aspect_ratio", "1:1") == "1:1" @pytest.mark.parametrize("video_seconds", [1, 1.5]) def test_mkv_video_timeline_ignores_longer_audio(tmp_path, video_seconds): import shutil from llm_services.video_edit.media import command, decode, probe if not shutil.which("ffmpeg") or not shutil.which("ffprobe"): pytest.skip("FFmpeg/ffprobe required for real MKV timeline regression") source = tmp_path / "source.mkv" command( [ "ffmpeg", "-v", "error", "-f", "lavfi", "-i", f"testsrc2=size=96x64:rate=24:duration={video_seconds}", "-f", "lavfi", "-i", "sine=frequency=440:duration=2", "-c:v", "ffv1", "-c:a", "pcm_s16le", str(source), ] ) media = probe(source) stream = next(s for s in media["streams"] if s["codec_type"] == "video") assert "duration" not in stream assert float(media["format"]["duration"]) == 2 if video_seconds > 1: with pytest.raises(ValueError, match="budget"): decode(source, tmp_path / "frames", 399360, 1) else: video = decode(source, tmp_path / "frames", 399360, 1) assert video["duration_seconds"] == 1 and video["frames"] == 24 assert video["source_has_audio"] is True