"""Precomputed projection-video conditioning. The converter (`scripts/convert_mine_blender.py`) already z-buffer-splats the coloured point cloud through every camera and writes: - ``bg_projection.mp4`` : static scene projection (frame-0 colours) - ``fg_projection.mp4`` : dynamic foreground projection (time-propagated) Re-rendering the same projection at inference time (LiveWorld's ``render_projection`` per iter) is redundant — the MP4 frames already ARE the scene/fg conditioning. This module loads those videos and VAE-encodes any subset of frames into the latent format the State Adapter expects, exactly mirroring ``generate_scene_projection_from_pointcloud``'s normalization so the distilled backbone sees the same statistics. """ from __future__ import annotations from pathlib import Path from typing import List, Optional, Tuple import cv2 import numpy as np import torch from liveworld.pipelines.pipeline_unified_backbone import _safe_frame_index def read_video_frames(path: str | Path, target_hw: Optional[Tuple[int, int]] = None) -> np.ndarray: """Read an MP4 into a ``(T, H, W, 3) uint8`` RGB array. If ``target_hw`` is given and differs from the video resolution, every frame is resized (linear) to ``(H, W)``. """ p = Path(path) if not p.exists(): raise FileNotFoundError(f"projection video not found: {p}") cap = cv2.VideoCapture(str(p)) if not cap.isOpened(): raise RuntimeError(f"cannot open video: {p}") frames: List[np.ndarray] = [] while True: ok, bgr = cap.read() if not ok: break rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) if target_hw is not None and rgb.shape[:2] != tuple(target_hw): H, W = target_hw rgb = cv2.resize(rgb, (W, H), interpolation=cv2.INTER_LINEAR) frames.append(rgb) cap.release() if not frames: raise RuntimeError(f"video had no frames: {p}") return np.stack(frames, axis=0) def subset_video_frames(frames_all: np.ndarray, frame_indices: List[int], output_size: Tuple[int, int]) -> np.ndarray: """Pick frames at ``frame_indices`` from a video and resize to ``output_size``. ``frames_all`` is ``(T_all, H, W, 3) uint8``. ``frame_indices`` are global indices clamped via ``_safe_frame_index``. Returns ``(T, H, W, 3) uint8``. """ H, W = output_size T_all = len(frames_all) sub = np.stack( [frames_all[_safe_frame_index(idx, T_all)] for idx in frame_indices], axis=0, ) if sub.shape[1:3] != (H, W): sub = np.stack( [cv2.resize(f, (W, H), interpolation=cv2.INTER_LINEAR) for f in sub], axis=0, ) return sub def encode_proj_frames_to_latent(frames_all: np.ndarray, frame_indices: List[int], output_size: Tuple[int, int], vae, device, dtype) -> torch.Tensor: """VAE-encode the frames at ``frame_indices`` into a scene/fg-proj latent. ``frames_all`` is the full ``(T_all, H, W, 3) uint8`` video. ``frame_indices`` are global frame indices (clamped to the video range, mirroring the point-cloud path's ``_safe_frame_index``). Returns a ``[C=16, T_latent, h, w]`` tensor — the same layout ``generate_scene_projection_from_pointcloud`` and ``encode_first_frame_fg_to_latent`` produce. """ sub = subset_video_frames(frames_all, frame_indices, output_size) # (T, H, W, 3) -> (T, 3, H, W), to [-1, 1] projections = sub.transpose(0, 3, 1, 2) proj_tensor = torch.from_numpy(projections).float() / 127.5 - 1.0 vae_device = next(vae.model.parameters()).device if vae_device != device: vae.model.to(device) vae.mean = vae.mean.to(device) vae.std = vae.std.to(device) with torch.no_grad(): # (T, 3, H, W) -> (1, 3, T, H, W) proj_tensor = proj_tensor.to(device=device, dtype=dtype) proj_tensor = proj_tensor.permute(1, 0, 2, 3).unsqueeze(0) latent = vae.encode_to_latent(proj_tensor) # [1, T_latent, 16, h, w] latent = latent.squeeze(0).permute(1, 0, 2, 3) # [16, T_latent, h, w] return latent