Adding Native Video Input to Open-Source Inference Frameworks: Engineering Practices

    Most multimodal large models now accept video through their official APIs, but teams that self-host on open-source inference frameworks often can only process text and static images. This article explains how to add a video pipeline covering decoding, frame sampling, temporal encoding, and token budgeting without changing the model architecture. It also covers how to package the result as a deployable service, along with common mistakes to avoid.

    1. Core Challenges of the Video Input Pipeline

    A video consists of multiple image frames and temporal information. Stacking images together does not capture the motion and changes within a video. A video pipeline therefore has to handle three problems: decoding and frame sampling, preserving temporal information, and managing memory and compute budgets.

    1.1 Decoding and Frame Sampling

    Formats such as MP4 and AVI use high-compression codecs, so videos must be decoded into raw frames before the model can use them. GPU memory and compute are limited, so not every frame can go through the vision encoder. There are two common sampling methods:

    Method Use Case Compute Cost Main Risk Parameter Suggestion
    Uniform sampling Scenes with stable visuals, such as surveillance footage and lecture recordings Low, fixed frame count May miss brief events Set the frame count by duration, for example 1 frame per second, with an upper limit
    Keyframe extraction Scenes with frequent shot changes, such as film clips Higher, requires motion or scene-change detection Unstable thresholds may extract too many frames Set both a minimum interval and a maximum frame count

    Uniform sampling is simple to implement and works as the default in most scenarios. Keyframe extraction preserves points where the semantic content changes sharply, but it needs an additional detection step. Both methods should set a maximum frame count, because the number of visual tokens directly determines GPU memory usage.

    1.2 Preserving Temporal Information

    A single-frame vision encoder processes each frame independently and has no built-in sense of time. If the sampled frames are fed in as unrelated images, the model cannot tell the order of actions.

    Temporal relationships must be injected through the model’s own mechanisms. There are three common approaches:

    • Insert time markers in the text, for example a text label such as “at 2.0 seconds” before each group of frame tokens.
    • Add a time dimension to the language model’s position encoding. The Multimodal Rotary Position Embedding (M-RoPE) used in the Qwen2-VL series falls into this category. It encodes time, height, and width separately.
    • Add a frame-order encoding to each frame’s features after the vision encoder output.

    Implementations differ widely across models. A plugin cannot design its own temporal encoding. It must follow the scheme the target model was trained with. Otherwise, the model receives an input distribution that differs from its training data, and the output quality drops noticeably.

    2. Building a Unified Pipeline on an Existing Vision Model

    Adding video support does not require training a vision model from scratch. The vision encoder and the language model backbone can both stay unchanged. Video data only needs to reach the model in a form the model can process.

    2.1 Converting All Inputs to a Common Format

    Text is split into tokens by a tokenizer and mapped to language vectors by the embedding layer. Images and videos first pass through the vision encoder. A feature projection module then converts their outputs into visual tokens aligned with the language model’s hidden dimension.

    In this framework, a video is treated as an ordered set of images. Each sampled frame goes through the same processing as a standalone image, so video plugs into the existing image pipeline without a separate model.

    2.2 Unified Preprocessing

    Before entering the vision encoder, both images and video frames go through the following steps:

    • Resizing and padding: Scale the image proportionally to the input size required by the vision model, and fill the remaining area with a fixed pixel value to avoid distortion. The padding value must match the model’s preprocessing configuration.
    • Normalization: Adjust pixel values using the mean and standard deviation. These parameters must match the specific weight files. Do not reuse values from other models. The model’s own preprocessing configuration file is the recommended source.
    • Patch splitting: Divide the image into fixed-size patches, such as 14×14 pixels. In models that do not merge patches, each patch maps to one visual token. For example, a 448×448 frame split into 14×14 patches yields a 32×32 grid, or 1,024 patches.

    2.3 Frame Concatenation and Token Budget

    After preprocessing, frames are sorted by timestamp and concatenated into one sequence of visual tokens. Three things must be handled during concatenation:

    • Frames need boundaries between them. Depending on the format the model was trained with, you can use frame boundary tokens or place a timestamp text label before each group of tokens.
    • The total token count equals the number of frames multiplied by the tokens per frame. For example, if each frame produces 1,024 tokens, 16 frames produce 16,384 tokens, not counting the text. If this exceeds the model’s context length or the memory budget, reduce the frame count or the resolution.
    • This pipeline handles only the visual track and ignores audio. If a video contains speech, a separate speech recognition step is required.

    2.4 Fusing Visual Features with the Language Model

    The projected visual tokens are concatenated with the text tokens and fed into the language model. Through self-attention, text tokens can attend to the visual information in the video. This enables video question answering, content description, and action analysis.

    3. Plugin Implementation

    3.1 Dependencies

    • Choose the Python version and the torch and transformers versions according to the official documentation for the target model.
    • We recommend PyAV (av) version 12.0 or later. PyAV wheels bundle FFmpeg libraries, so a system-level FFmpeg installation is usually unnecessary.
    • pillow and numpy.

    Pin every version number in requirements.txt to prevent environment drift.

    3.2 Decoding and Sampling Code

    The code below shows the core of the plugin. It includes size and duration checks, uniform frame sampling, timestamp recording, and a visual token budget check.

    1. import os
    2. import av
    3. import numpy as np
    4. MAX_VIDEO_BYTES = 200 * 1024 * 1024 # Maximum video size: 200 MB
    5. MAX_DURATION_S = 600 # Maximum duration: 10 minutes
    6. DEFAULT_MAX_FRAMES = 16
    7. def uniform_indices(total, max_frames):
    8. """Return max_frames evenly spaced frame indices in the range [0, total-1]."""
    9. if total <= max_frames:
    10. return list(range(total))
    11. return np.linspace(0, total - 1, max_frames).round().astype(int).tolist()
    12. def decode_and_sample(path, max_frames=DEFAULT_MAX_FRAMES):
    13. """Return a list of PIL images and the timestamp (in seconds) of each image."""
    14. if os.path.getsize(path) > MAX_VIDEO_BYTES:
    15. raise ValueError("Video exceeds the size limit")
    16. container = av.open(path)
    17. try:
    18. stream = container.streams.video[0]
    19. if stream.duration and stream.time_base:
    20. duration = float(stream.duration * stream.time_base)
    21. if duration > MAX_DURATION_S:
    22. raise ValueError("Video duration exceeds the limit")
    23. total = stream.frames
    24. if total <= 0:
    25. # Some containers do not record the frame count. Transcode the file first,
    26. # or use a library such as decord.
    27. raise ValueError("Container does not record the frame count")
    28. wanted = uniform_indices(total, max_frames)
    29. wanted_set = set(wanted)
    30. last = max(wanted)
    31. images, stamps = [], []
    32. for idx, frame in enumerate(container.decode(video=0)):
    33. if idx in wanted_set:
    34. images.append(frame.to_image())
    35. stamps.append(float(frame.time or 0.0))
    36. if idx >= last:
    37. break
    38. return images, stamps
    39. finally:
    40. container.close()
    41. def build_video_inputs(path, image_processor, max_frames=DEFAULT_MAX_FRAMES):
    42. """Decode the video and generate pixel tensors with the model's own image processor."""
    43. try:
    44. images, stamps = decode_and_sample(path, max_frames)
    45. except av.error.FFmpegError as exc:
    46. raise ValueError(
    47. f"Video decoding failed. The codec may be unsupported or the file may be corrupted: {exc}"
    48. ) from exc
    49. if not images:
    50. raise ValueError("No video frames were read")
    51. # Use the model's own image processor so that resizing, padding, and normalization
    52. # match the weights
    53. pixel_values = image_processor(images=images, return_tensors="pt")["pixel_values"]
    54. return pixel_values, stamps
    55. def check_token_budget(num_frames, tokens_per_frame, max_tokens=8192):
    56. """Check the total number of visual tokens before the model runs, to avoid running out of GPU memory."""
    57. total = num_frames * tokens_per_frame
    58. if total > max_tokens:
    59. raise ValueError(
    60. f"Visual tokens total {total}, exceeding the budget of {max_tokens}. "
    61. "Reduce the number of frames or the resolution."
    62. )
    63. return total

    The code runs in the following order. It first checks the file size to keep oversized files from filling memory. Then it reads the duration and frame count and rejects files that do not meet the limits. Next, it selects frame indices at even intervals and decodes only up to the last required frame, which avoids unnecessary computation. Finally, it passes the images through the model’s own image processor. The timestamps are passed to the model’s temporal template.

    The output structure of image_processor varies by model. Before integration, print the tensor shape once to confirm the token count per frame, then pass the result to check_token_budget.

    3.3 Error Handling

    The plugin should return clear errors for the following cases instead of raising raw low-level exceptions:

    • Decoding failure: Return an error stating that the format is unsupported or the file is corrupted, and log the file’s codec information.
    • Out of memory: Catch torch.cuda.OutOfMemoryError, clear the cache, and return an error stating that the video is too large and the frame count should be reduced.
    • Zero frame count: Explain that the container does not record the frame count, and recommend transcoding the file to standard MP4 with ffmpeg first.

    3.4 Security Controls for URL and Base64 Inputs

    If requests can supply a video URL, the plugin should apply the following checks to prevent server-side request forgery (SSRF) and malicious files:

    • Allow requests only to domains on an allowlist.
    • Resolve the domain and check the IP address. Reject private, loopback, and link-local addresses.
    • Set an upper limit on download size and a timeout, and limit the number of redirects.
    • Download to an isolated directory, and delete the file immediately after processing.

    Base64 input needs checks too. Estimate the decoded size before decoding, and reject input that exceeds the limit. This prevents the input from exhausting memory.

    4. Deployment Checklist

    After the plugin is integrated, the runtime environment must be pinned down. Use the following checklist to confirm that the deployment is complete:

    1. Image: Build on a CUDA version compatible with the GPU driver, and pin the base image tag.
    2. GPU driver and container tools: Install the NVIDIA driver and the NVIDIA Container Toolkit on the host machine in advance.
    3. Decoding library: Pin the PyAV version in requirements.txt.
    4. Model weights: Mount them as a read-only volume, and reference the path in a configuration file. Do not bake the weights into the image.
    5. Object storage: Store videos under a designated bucket and prefix. Grant the service account read access to that prefix only, and use temporary credentials.
    6. Resource limits: Set limits for GPU memory, concurrent requests, maximum video size and duration, and maximum frame count.
    7. Health checks: Provide an endpoint that reports model loading status, and a self-test endpoint that runs a short video through the full pipeline.
    8. Logging: Record video size, frame count, decoding time, and failure reasons. Do not log video content or access keys.

    The container platform schedules GPUs, and object storage can be read over the internal network. Together, these reduce video transfer latency. This approach still requires installing the environment and configuring dependencies. It is not a turnkey product. Hardware, driver versions, and model versions all affect results, so verify each item in the target environment.

    5. Common Mistakes and Precautions

    • Wrong normalization parameters: Using the mean and standard deviation from another model produces meaningless outputs without raising any error.
    • Temporal format mismatch: If the timestamp text or position encoding differs from the format used in training, video question answering accuracy drops.
    • No frame limit: Feeding a long video into the model in one pass can easily cause GPU out-of-memory errors.
    • Ignoring zero frame counts: Some containers do not record the frame count. Using them directly breaks the sampling logic.
    • No size limit on Base64 input: The decoded data can fill memory. Check the input length before decoding.

    6. Summary

    To add video input to an open-source inference framework, the key step is connecting video decoding, frame sampling, temporal tagging, and token concatenation to the existing vision pipeline. A plugin-based design keeps the core of the inference framework stable and makes the plugin easier to reuse across models.

    This approach lets a self-hosted service accept video input while keeping the original vision and language models. The effort required for teams to add video support themselves is lower as a result. Temporal encoding, memory budgeting, and input security still need careful handling, and the system should be validated in the target environment before production use.