Acceptance Pipeline for Feeding Video Input into a Locally Hosted Multimodal Model
A practical guide to building and validating the full pipeline that turns a local video file into model-ready input for a locally hosted multimodal LLM: metadata probing, frame sampling for CFR and VFR videos, temporal chunking, feature caching, projection and fusion, plus acceptance tests and a troubleshooting table.
End-to-End Pipeline for Feeding Video into a Local Multimodal Model: Implementation and Acceptance
1. Scope and Dependency Versions
This article covers the following scenario: a local inference service receives a video file, converts it into an input sequence that a language model can process, runs inference, and returns the result. Out of scope: model training, video understanding benchmarks, and cloud service integration.
The article assumes:
- The inference service already supports text and image inputs.
- The vision encoder and language model weights remain unchanged; only the input side is modified.
- Videos use mp4 or mov containers, with the video stream encoded in H.264 or HEVC.
The table below lists recommended starting versions. No benchmark numbers are included here; before production, re-test on your target hardware following the steps in Section 8.
| Component | Recommended version | Notes |
|---|---|---|
| Python | 3.10+ | Code uses type hints such as list[int] |
| FFmpeg and ffprobe | 6.x or 7.x | Both should be the same version |
| PyAV | 12.0+ | Must match the FFmpeg shared library version; pin the minor version |
| numpy | 1.24+ | Decoded frames are converted to arrays |
| PyTorch | 2.1+ | Projector and encoder inference |
2. Configuration Checklist
All thresholds live in a config file rather than being hardcoded. The values below are starting points; tune them after measuring VRAM usage and latency.
video:max_file_size_bytes: 209715200 # 200 MiB, starting valuemax_duration_s: 60max_width: 1920 # display dimensions, computed after rotationmax_height: 1080allowed_codecs: [h264, hevc]target_fps: 1.0 # target sampling densitymax_frames: 32 # frame cap per requesttimestamp_tol_s: 0.5 # max timing error for VFR sampling; suggest 0.5 / target_fpschunk_size: 8 # frames per temporal chunkchunk_overlap: 1 # frames shared between adjacent chunksencoder_batch: 8 # frames per encoder call, VRAM-limitedcache_entries: 256 # feature cache capacitymax_visual_tokens: 4096 # set according to the model's context length
3. Metadata Checks
Read metadata before decoding instead of decoding the whole video up front. This lets the service reject non-compliant files before spending memory. ffprobe is invoked with an argument list, so file paths are never interpolated into a shell command.
Rotation metadata comes from two sources. Newer FFmpeg versions write the rotation angle into side_data_list; older versions commonly use tags.rotate. If both are missing, the code treats rotation as 0 and logs a warning that does not include the raw path. Acceptance testing must include rotated samples, since this is exactly the kind of silent misjudgment such samples catch.
import hashlibimport jsonimport loggingimport osimport subprocessfrom dataclasses import dataclasslog = logging.getLogger("video")PROBE_ARGS = ["ffprobe", "-v", "error","-select_streams", "v:0","-show_entries","stream=codec_name,width,height,avg_frame_rate"":stream_side_data=rotation:stream_tags=rotate:format=duration","-of", "json",]class VideoError(Exception):def __init__(self, code: str, message: str):super().__init__(message)self.code = codeself.message = message@dataclassclass VideoMeta:codec: strwidth: intheight: intduration_s: floatavg_fps: floatrotation: introtation_known: booldef _rate(r: str) -> float:num, _, den = r.partition("/")d = float(den) if den else 1.0return float(num) / d if d else 0.0def probe_video(path: str, limits: dict) -> VideoMeta:try:size = os.path.getsize(path)except FileNotFoundError:raise VideoError("E_NOT_FOUND", "file does not exist")if size > limits["max_file_size_bytes"]:raise VideoError("E_SIZE", "file exceeds size limit")try:proc = subprocess.run(PROBE_ARGS + [path], capture_output=True,text=True, timeout=10, check=False)except subprocess.TimeoutExpired:raise VideoError("E_TIMEOUT", "metadata read timed out")if proc.returncode != 0:raise VideoError("E_PROBE", "file could not be parsed")try:info = json.loads(proc.stdout or "{}")except json.JSONDecodeError:raise VideoError("E_PROBE", "ffprobe output is not valid JSON")streams = info.get("streams") or []if not streams:raise VideoError("E_NO_VIDEO", "no video track in file")s = streams[0]rotation, rotation_known = 0, Falsefor item in s.get("side_data_list", []):if "rotation" in item:rotation, rotation_known = int(item["rotation"]), Trueif not rotation_known and "rotate" in s.get("tags", {}):rotation, rotation_known = int(s["tags"]["rotate"]), Trueif not rotation_known:digest = hashlib.sha256(path.encode()).hexdigest()[:12]log.warning("rotation_unknown path_sha=%s", digest)meta = VideoMeta(codec=s.get("codec_name", "unknown"),width=int(s.get("width", 0)),height=int(s.get("height", 0)),duration_s=float(info.get("format", {}).get("duration", 0) or 0),avg_fps=_rate(s.get("avg_frame_rate", "0/0")),rotation=rotation,rotation_known=rotation_known,)if meta.codec not in limits["allowed_codecs"]:raise VideoError("E_CODEC", f"unsupported codec: {meta.codec}")if not 0 < meta.duration_s <= limits["max_duration_s"]:raise VideoError("E_DURATION", "duration is empty or exceeds limit")# For 90/270-degree rotation, display and stored dimensions are swapped; judge by display sizew, h = meta.width, meta.heightif abs(meta.rotation) % 180 == 90:w, h = h, wif w > limits["max_width"] or h > limits["max_height"]:raise VideoError("E_RESOLUTION", "display resolution exceeds limit")return meta
4. Frame Sampling: Constant and Variable Frame Rate
A video’s native frame rate is usually far higher than the sampling density a model needs. Consider a 30 fps, 10-second video: 300 frames total. Feeding every frame to the model would rapidly inflate the visual token count, along with latency and VRAM usage.
Constant frame rate (CFR) videos can be sampled uniformly by index:
def sample_frame_indices(total_frames: int, src_fps: float,target_fps: float, max_frames: int) -> list[int]:if total_frames <= 0 or src_fps <= 0 or target_fps <= 0 or max_frames <= 0:raise ValueError("frame count, fps and cap must be positive")duration = total_frames / src_fpsnum = max(1, round(duration * target_fps))num = min(num, max_frames, total_frames)step = total_frames / numreturn [min(total_frames - 1, int(i * step)) for i in range(num)]
For 300 frames at 30 fps with a 1 fps target and a 32-frame cap, the function returns [0, 30, 60, ..., 270] — 10 indices.
For variable frame rate (VFR) videos, the average fps does not reflect each frame’s actual timestamp. Such videos should be sampled by time: generate target timestamps first, then pick, from the decoded stream, the frame whose timestamp is closest to each target:
import avimport numpy as npdef target_times(duration_s: float, target_fps: float, max_frames: int) -> list[float]:num = max(1, min(max_frames, round(duration_s * target_fps)))return [k / target_fps for k in range(num)]def read_frames_by_pts(path: str, times: list[float], tol_s: float) -> list[np.ndarray]:"""times is an ascending list of target timestamps (seconds). Decode sequentially,keeping only the frame closest to each target."""if not times:return []picked, errs = [], []ti, t0, prev = 0, None, Nonetry:with av.open(path) as container:stream = container.streams.video[0]for frame in container.decode(stream):if frame.time is None:raise VideoError("E_NO_PTS", "frame lacks a timestamp; cannot sample by time")if t0 is None:t0 = frame.time # zero-base on first frame, handles non-zero startt = frame.time - t0while ti < len(times) and t >= times[ti]:tgt = times[ti]if prev is not None and tgt - prev[0] <= t - tgt:pick_t, pick_f = prevelse:pick_t, pick_f = t, framepicked.append(pick_f.to_ndarray(format="rgb24"))errs.append(abs(pick_t - tgt))ti += 1prev = (t, frame)if ti == len(times):break # all targets found, stop decodingwhile ti < len(times) and prev is not None:picked.append(prev[1].to_ndarray(format="rgb24"))errs.append(abs(prev[0] - times[ti]))ti += 1except av.error.FFmpegError as e:raise VideoError("E_DECODE", f"decoding failed: {e}")if len(picked) != len(times):raise VideoError("E_DECODE_FRAME", "picked frame count does not match targets")if max(errs) > tol_s:raise VideoError("E_TIMING_GAP", f"max timing error {max(errs):.3f}s exceeds tolerance")return picked
This code still decodes sequentially, so runtime grows linearly with duration. Memory usage stays flat, however, since only the previous frame, the current frame, and the picked frames are retained.
Estimate memory in advance. A 1920×1080 RGB frame is about 6.22 MB (5.93 MiB). Thirty-two frames total roughly 190 MiB, before any model intermediates. That is why frame count and resolution per request must be capped in configuration.
5. Temporal Chunking
Sampled frames are split into temporal chunks fed to the encoder one at a time. The rules: each chunk holds chunk_size frames, adjacent chunks overlap by chunk_overlap frames, and the stride is the difference between the two. When the last chunk is short, pad it by repeating the last index and record the valid length so downstream stages ignore padded positions.
def make_chunks(indices: list[int], chunk_size: int,overlap: int) -> list[tuple[list[int], int]]:if chunk_size <= 0 or not 0 <= overlap < chunk_size:raise ValueError("chunk_size must be positive, and 0 <= overlap < chunk_size")step = chunk_size - overlapchunks = []for start in range(0, len(indices), step):part = indices[start:start + chunk_size]valid = len(part)if valid < chunk_size:part = part + [part[-1]] * (chunk_size - valid)chunks.append((part, valid))if start + chunk_size >= len(indices):breakreturn chunks
Overlapping frames give adjacent chunks shared context. During fusion, each frame is inserted only once; deduplication rules are covered in Section 7.
6. Reusing Vision Encoder Features
The encoder’s output depends only on frame content, preprocessing parameters, and encoder weights. The cache key should therefore include all three: a video digest, the frame index, a preprocessing hash, and the encoder version. Within a single request, overlapping frames are encoded once; across requests, frames from the same video can hit the cache.
The cache evicts in LRU order. A single entry uses roughly N × D_v × 2 bytes (fp16), where N is the number of image patches per frame and D_v is the encoder output dimension. Size cache_entries using this formula together with available VRAM.
from collections import OrderedDictimport torchclass FeatureCache:def __init__(self, max_entries: int):self.max_entries = max_entriesself._d: OrderedDict = OrderedDict()def get(self, key):if key in self._d:self._d.move_to_end(key)return self._d[key]return Nonedef put(self, key, value):self._d[key] = valueself._d.move_to_end(key)while len(self._d) > self.max_entries:self._d.popitem(last=False)def encode_frames(frames: list[torch.Tensor], keys: list[tuple],encoder, cache: FeatureCache, batch: int) -> list[torch.Tensor]:out: list = [None] * len(frames)todo = []for i, k in enumerate(keys):hit = cache.get(k)if hit is None:todo.append(i)else:out[i] = hitfor start in range(0, len(todo), batch):idx = todo[start:start + batch]x = torch.stack([frames[i] for i in idx])with torch.inference_mode():feats = encoder(x) # [B, N, D_v]for j, i in enumerate(idx):out[i] = feats[j].clone() # avoid the cache holding an entire batch outputcache.put(keys[i], out[i])return out
Cached features may correspond to user video content. Keep the cache in process memory only, set an expiration time, and never write it to disk after a request completes.
7. Projection and Fusion
The encoder output dimension D_v usually differs from the language model’s hidden dimension D_llm. The projector does two things: merges adjacent merge × merge image patches to reduce the visual token count, then maps the dimension to D_llm.
Example: if the encoder outputs 24 × 24 = 576 patches per frame with D_v = 1024, merge = 2, and D_llm = 4096, merging yields 144 visual tokens per frame. Use the actual values from your model’s configuration.
import torch.nn as nnclass VisualProjector(nn.Module):def __init__(self, d_vision: int, d_llm: int, merge: int = 2):super().__init__()self.merge = mergeself.proj = nn.Sequential(nn.Linear(d_vision * merge * merge, d_llm),nn.GELU(),nn.Linear(d_llm, d_llm),)def forward(self, feats: torch.Tensor) -> torch.Tensor:# feats: [T, N, D_v], N is the patch count in a square gridT, N, D = feats.shapeg = int(round(N ** 0.5))m = self.mergeassert g * g == N and g % m == 0, "patch grid must be square and divisible by merge"x = feats.reshape(T, g // m, m, g // m, m, D)x = x.permute(0, 1, 3, 2, 4, 5).reshape(T, (g // m) ** 2, D * m * m)return self.proj(x) # [T, N / m^2, D_llm]
Fusion concatenates the sequence in a fixed order: prompt prefix, then visual tokens of each frame in temporal order, then the user’s question. Each frame is inserted once; overlapping frames are deduplicated by frame index. Padded frames are not inserted.
def fuse(prefix_emb: torch.Tensor, frame_tokens: list[torch.Tensor],question_emb: torch.Tensor, max_visual_tokens: int) -> torch.Tensor:# frame_tokens is in temporal order, each item [tokens_per_frame, D_llm], already deduplicatedvisual = torch.cat(frame_tokens, dim=0)if visual.shape[0] > max_visual_tokens:raise VideoError("E_TOKEN_BUDGET", "visual tokens exceed budget")return torch.cat([prefix_emb, visual, question_emb], dim=0) # [L, D_llm]
Total visual tokens equal frame count × tokens per frame, plus text tokens. Set max_visual_tokens based on the model’s context length and your VRAM budget.
8. Acceptance Steps and Metrics
- Prepare a sample set covering: CFR H.264 and HEVC videos, VFR videos, videos rotated 90 and 270 degrees, files exceeding the size, duration, or resolution limits, files with no video track, and truncated/corrupted files. Use only videos you own or have licensed.
- Verify metadata. Each sample’s rejection error code must match expectations. Rotated samples must report
rotation_known = trueand be judged by display resolution. - Verify frame sampling. CFR samples must have evenly spaced indices. VFR samples must have a max timing error within
timestamp_tol_s. - Verify chunking. Every sampled frame must be covered by at least one chunk — 100% coverage — and every chunk must have a valid length of at least 1.
- Verify caching. Request the same video twice; the second request should trigger zero encoder calls.
- Verify projection. Output shape must be
[T, N / m², D_llm], matching the configuration. - End-to-end test. Fix the prompt and random seed, then compare against a reference output in the same environment. Record peak VRAM and end-to-end latency on the target hardware and compare against your team’s thresholds.
Acceptance metrics:
| Metric | How to compute | Criteria | ||
|---|---|---|---|---|
| Timing error | Max and P95 of | target timestamp − picked frame timestamp | Within timestamp_tol_s |
|
| Missed-frame rate | Failed decodes or failed picks ÷ total targets | Per team requirement; 0 recommended | ||
| Chunk coverage | Covered sampled frames ÷ total sampled frames | Must be 100% | ||
| Cache hit rate | Hits ÷ total frames per request | Record per scenario; no hard threshold | ||
| Visual token count | Frames × tokens per frame | Within max_visual_tokens |
||
| Peak VRAM and latency | Measured on target hardware | Thresholds set by the team |
9. Common Errors
| Error code or symptom | Likely cause | Remedy |
|---|---|---|
| E_PROBE | FFmpeg version mismatch, or corrupted file | Run ffprobe -version to check versions; reject corrupted files |
| E_NO_PTS | Container lacks timestamps | Fall back to the CFR path, or reject the file |
| E_TIMING_GAP | Sparse sampling of a VFR video, gaps beyond tolerance | Inspect the source; relax tolerance or adjust target fps if needed |
| E_DECODE_FRAME | Truncated file; decoding ended early | Reject the file and log the error code |
| E_TOKEN_BUDGET | Frame count or resolution too high | Lower max_frames or resolution |
| Rotated video has wrong orientation | Rotation metadata not read, or version differences | Check rotation_known; ensure rotated samples pass acceptance |
| Unexpected cache results | Preprocessing changed but cache key did not | Cache key must include the preprocessing hash and encoder version |
| VRAM OOM | encoder_batch too large |
Reduce batch size and re-measure peak VRAM |
| Projector shape error | D_v or D_llm inconsistent with config | Validate model config against projector parameters |
10. Compliance Notes
Videos may contain personal information such as faces, locations, and conversations. Processing should happen on the local machine without persisting raw frames; the feature cache should have an expiration time, and cached data should not outlive the request lifecycle.
