"""Credential-free conversion worker; caller bounds CPU, memory and wall time.""" from __future__ import annotations import gzip import io import math import resource import shutil import subprocess import sys from pathlib import Path from typing import ClassVar, Final, Literal, assert_never from lottie.exporters.cairo import export_png from lottie.objects import Animation from PIL import Image from PIL.PngImagePlugin import PngInfo from pydantic import BaseModel, ConfigDict, Field, JsonValue, TypeAdapter from models import ASSET_BYTES, FailureReason, ImportFailureError CELL: Final = 128 SOURCE_SIDE: Final = 512 TGS_BYTES: Final = 2_097_152 TGS_DEPTH: Final = 32 TGS_NODES: Final = 50_000 TEXT_LAYER: Final = 5 Format = Literal["webp", "tgs", "webm"] JSON_VALUE: Final = TypeAdapter[JsonValue](JsonValue) class Timing(BaseModel): """Bounded vector dimensions and finite animation interval.""" model_config: ClassVar[ConfigDict] = ConfigDict(strict=True) w: int = Field(ge=1, le=512) h: int = Field(ge=1, le=512) fr: float = Field(gt=0, le=120, allow_inf_nan=False) ip: float = Field(ge=0, le=7200, allow_inf_nan=False) op: float = Field(gt=0, le=7200, allow_inf_nan=False) def check_vector(value: JsonValue, depth: int = 0) -> int: """Reject resources and excessive nesting before rendering vector JSON.""" if depth > TGS_DEPTH: raise ImportFailureError(FailureReason.TGS_NESTING_LIMIT) nodes = 1 match value: case dict(): if isinstance(value.get("p"), str) or isinstance(value.get("u"), str): raise ImportFailureError(FailureReason.TGS_IMAGE_RESOURCES_UNSUPPORTED) if "fonts" in value or "chars" in value or value.get("ty") == TEXT_LAYER: raise ImportFailureError(FailureReason.TGS_TEXT_RESOURCES_UNSUPPORTED) if isinstance(value.get("x"), str): raise ImportFailureError(FailureReason.TGS_EXPRESSIONS_UNSUPPORTED) children = value.values() case list(): children = value case str() | int() | float() | None: return nodes case _: assert_never(value) for child in children: nodes += check_vector(child, depth + 1) if nodes > TGS_NODES: raise ImportFailureError(FailureReason.TGS_COMPLEXITY_LIMIT) return nodes def normalize(image: Image.Image) -> Image.Image: """Fit a bounded source into one transparent client atlas cell.""" if not (1 <= image.width <= SOURCE_SIDE and 1 <= image.height <= SOURCE_SIDE): raise ImportFailureError(FailureReason.SOURCE_IMAGE_DIMENSIONS_EXCEED_512) frame = image.convert("RGBA") frame.thumbnail((CELL, CELL), Image.Resampling.LANCZOS) cell = Image.new("RGBA", (CELL, CELL)) cell.alpha_composite(frame, ((CELL - frame.width) // 2, (CELL - frame.height) // 2)) return cell def vector_frames(source: Path) -> list[Image.Image]: """Render bounded TGS input at 20 FPS for at most 60 frames.""" with gzip.open(source, "rb") as compressed: raw = compressed.read(TGS_BYTES + 1) if len(raw) > TGS_BYTES: raise ImportFailureError(FailureReason.TGS_EXPANSION_EXCEEDS_2_MIB) value = JSON_VALUE.validate_json(raw) _ = check_vector(value) timing = Timing.model_validate(value) if timing.op <= timing.ip: raise ImportFailureError(FailureReason.INVALID_TGS_FRAME_INTERVAL) if not isinstance(value, dict): raise ImportFailureError(FailureReason.INVALID_TGS_ROOT) animation = Animation.load(value) count = min(60, math.ceil((timing.op - timing.ip) * 20 / timing.fr)) frames: list[Image.Image] = [] for index in range(count): with io.BytesIO() as png: export_png(animation, png, timing.ip + index * timing.fr / 20) _ = png.seek(0) with Image.open(png) as image: frames.append(normalize(image)) return frames class VideoStream(BaseModel): """Accepted WebM video stream dimensions and decoder family.""" model_config: ClassVar[ConfigDict] = ConfigDict(strict=True) width: int = Field(ge=1, le=512) height: int = Field(ge=1, le=512) codec_name: Literal["vp8", "vp9"] class VideoProbe(BaseModel): """Require exactly one selected video stream from ffprobe.""" streams: list[VideoStream] = Field(min_length=1, max_length=1) def executable(name: Literal["ffmpeg", "ffprobe"]) -> str: """Resolve required decoders on the wrapper's configured runtime path.""" path = shutil.which(name) if path is None: raise ImportFailureError(FailureReason.CONVERSION_FAILED) return path def video_frames(source: Path) -> list[Image.Image]: """Decode bounded local WebM frames without enabling network protocols.""" probe = subprocess.run( [ executable("ffprobe"), "-v", "error", "-protocol_whitelist", "file", "-f", "matroska", "-select_streams", "v:0", "-show_entries", "stream=width,height,codec_name", "-of", "json", str(source), ], capture_output=True, check=True, timeout=10, ) stream = VideoProbe.model_validate_json(probe.stdout).streams[0] match stream.codec_name: case "vp8": decoder = "libvpx" case "vp9": decoder = "libvpx-vp9" case _: assert_never(stream.codec_name) result = subprocess.run( [ executable("ffmpeg"), "-v", "error", "-nostdin", "-threads", "1", "-protocol_whitelist", "file", "-c:v", decoder, "-f", "matroska", "-i", str(source), "-an", "-sn", "-dn", "-vf", ",".join( ( "fps=20", f"scale={CELL}:{CELL}:force_original_aspect_ratio=decrease", f"pad={CELL}:{CELL}:(ow-iw)/2:(oh-ih)/2:color=black@0", "format=rgba", ) ), "-frames:v", "60", "-threads", "1", "-f", "rawvideo", "-pix_fmt", "rgba", "pipe:1", ], capture_output=True, check=True, timeout=30, ) stride = CELL * CELL * 4 if ( not result.stdout or len(result.stdout) % stride or len(result.stdout) > stride * 60 ): raise ImportFailureError(FailureReason.INVALID_DECODED_VIDEO_FRAMES) return [ Image.frombytes("RGBA", (CELL, CELL), result.stdout[start : start + stride]) for start in range(0, len(result.stdout), stride) ] def convert(source: Path, kind: Format, destination: Path) -> int: """Write an atlas whose PNG identity includes its frame count.""" match kind: case "webp": with Image.open(source) as image: if image.format != "WEBP" or getattr(image, "n_frames", 1) != 1: raise ImportFailureError(FailureReason.EXPECTED_STATIC_WEBP) frames = [normalize(image)] case "tgs": frames = vector_frames(source) case "webm": frames = video_frames(source) case _: assert_never(kind) columns = min(8, len(frames)) atlas = Image.new("RGBA", (columns * CELL, math.ceil(len(frames) / columns) * CELL)) for index, frame in enumerate(frames): atlas.paste(frame, ((index % columns) * CELL, (index // columns) * CELL)) metadata = PngInfo() metadata.add_text("wowmine_frames", str(len(frames))) atlas.save(destination, format="PNG", optimize=False, pnginfo=metadata) if destination.stat().st_size > ASSET_BYTES: raise ImportFailureError(FailureReason.PNG_EXCEEDS_2_MIB) return len(frames) def worker() -> None: """Only validated format literals enter conversion.""" resource.setrlimit(resource.RLIMIT_AS, (805306368, 805306368)) resource.setrlimit(resource.RLIMIT_CPU, (35, 35)) resource.setrlimit(resource.RLIMIT_FSIZE, (8388608, 8388608)) kind = TypeAdapter[Format](Format).validate_python(sys.argv[2]) _ = sys.stdout.write(f"{convert(Path(sys.argv[1]), kind, Path(sys.argv[3]))}\n") if __name__ == "__main__": worker()