Integrating Video Input into Local Inference Services: Pipeline and Best Practices

    This article details the complete pipeline and implementation guidelines for adding video input capabilities to local inference services. It covers request security validation, decoding, frame extraction strategies, temporal chunking, and visual feature fusion, providing a technical roadmap for teams deploying video-processing models locally.

    I. Video Input Gaps and Modification Boundaries

    Cloud model service providers have already opened video input APIs. Teams that deploy models independently must implement the same capabilities in their local inference services. A video request must sequentially pass through container parsing, decoding, frame extraction, temporal chunking, visual encoding, and concatenation. An error in any step will result in missing or misaligned frames for the model, ultimately leading to request failures or answers that do not match the visual content.

    The modification cost primarily depends on two factors. First, whether the visual encoder can receive multiple images in a single pass. Second, whether the inference framework allows adding custom logic at the request entry point and the visual feature concatenation point. If both conditions are met, a preprocessing module can be added to the existing service without replacing the model.

    If the business only requires answering questions related to key frames, single-frame input is sufficient. In this case, only decoding and single-image processing need to be implemented, and temporal chunking can be deferred.

    II. Request Reception and Security Validation

    Video requests come from three sources: remote URLs, inline encoded data, and file uploads. The validation fields for these three sources differ and must be handled separately.

    Source Required Validation Fields Key Limits
    Remote URL Protocol, hostname, port, Content-Type Only HTTPS allowed by default; total download timeout 10s; max 3 redirects
    Inline data base64 length, MIME type, file header Encoded size up to 150 MB
    File upload File size, extension, file header Single file up to 200 MB

    All sources must enforce a video duration limit; videos longer than 120 seconds after decoding are rejected outright. The format whitelist includes mp4, webm, and mov.

    Remote URLs require specific hardening. The specific practices are as follows:

    1. Allow only the HTTPS protocol and port 443. If absolutely necessary, add port 80 and specific domains to the whitelist.
    2. Resolve DNS first and reject requests where the resolved IP falls within private, loopback, link-local, or multicast address ranges. Private address ranges include 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 127.0.0.0/8, 169.254.0.0/16, and IPv6 ::1 and fc00::/7.
    3. Use the validated IP from step 2 when establishing the connection to prevent DNS rebinding attacks where re-resolution points to an internal network address.
    4. Re-run validation for every redirect. If the business does not require redirects, disable them entirely.
    5. Set an upper limit of 200 MB for the response body; terminate the connection immediately if exceeded.

    The service should return unified error codes to help callers and operations teams locate issues:

    HTTP Status Business Code Trigger Scenario
    400 VIDEO_PARAM_INVALID Missing source, or conflicting parameters
    403 VIDEO_SOURCE_DENIED Address falls within internal network range, or is not in the whitelist
    413 VIDEO_TOO_LARGE File size or duration exceeds the limit
    415 VIDEO_MIME_UNSUPPORTED Format is not in the whitelist
    422 VIDEO_DECODE_FAILED Container corrupted, or no available video stream
    429 VIDEO_BUSY Concurrent requests exceed single instance limit
    504 VIDEO_FETCH_TIMEOUT Remote download exceeds time limit

    Error messages should not include internal network addresses, full file paths, or stack traces.

    III. Decoding, Frame Extraction, and Temporal Chunking

    3.1 Decoding

    It is recommended to use FFmpeg 5.x or higher, or PyAV based on it. When decoding, only read the first video stream and ignore audio streams.

    Video rotation metadata must be read and applied. If this information is ignored for vertically shot mobile videos, the frames will appear sideways, causing errors in the model’s direction and content descriptions. After decoding, uniformly convert frames to RGB format. Each frame must record a timestamp in seconds, calculated as the frame’s pts multiplied by the time base.

    3.2 Frame Extraction Strategies

    Strategy Approach Applicable Scenarios
    Uniform extraction Take points at fixed frame intervals across the entire video length, default 16 frames, max 32 frames General Q&A, variable duration
    Fixed frame rate Extract 1 frame per second; if the limit is exceeded, switch to uniform extraction Action process description, short videos
    Key frame extraction Extract only I-frames, then deduplicate by time interval Low-cost summarization, minimal scene changes

    Uniform extraction is used by default. Note the following when choosing an extraction strategy:

    • For videos shorter than 4 seconds, extract at least 4 frames to ensure sufficient temporal information.
    • When a video exceeds the frame limit, increase the sampling interval to cover the entire length. Do not only take the first N frames, as the content in the second half will be lost.
    • Ensure that frame indices are monotonically increasing after extraction. Duplicate frames with identical timestamps can be deduplicated, but the original order must be preserved.

    3.3 Temporal Chunking

    The extracted frames are split into several chunks in chronological order, with a default of 8 frames per chunk and no overlap between chunks by default. A 16-frame video will be split into two chunks. Each chunk records its start and end times for use during subsequent concatenation.

    Each chunk is sent to the visual encoder as a batch. The batch size must match the GPU memory budget (see Section V).

    IV. Visual Feature Fusion and Model Reusability

    The processing flow is as follows:

    1. Image preprocessing: Uniformly scale to the target resolution (e.g., 448×448) or maintain the aspect ratio and add padding. Then perform normalization.
    2. Visual encoder: Process the frames of each chunk in batches.
    3. Projection layer: Map the visual features to the hidden dimension of the language model.
    4. Time markers: Add temporal information to each frame.
    5. Concatenation: Place all visual tokens into the input sequence of the language model in chronological order.

    The video tokens entering the language model have the same shape as image tokens—both are embedding vectors processed through the visual encoder and projection layer, rather than raw pixels. Images and videos share the same encoder and projection layer, meaning the scaling, normalization, and splitting logic only needs to be maintained in one place.

    There are two methods for preserving temporal information:

    • Positional encoding: If the model’s positional encoding supports temporality, write the frame index into the position ID.
    • Text markers: Insert timestamp text before the visual tokens of each frame (e.g., “at 2.0 seconds”). This method works with all models at the cost of consuming a few additional text tokens.

    Before modifying the service, confirm that the model meets the following conditions:

    • The visual encoder can receive multiple images as a single input.
    • The projection layer’s output dimension matches the language model’s hidden dimension.
    • The language model’s context length is greater than the sum of the visual tokens and text tokens.

    Taking a patch size of 14 and an input of 448×448 as an example, there are about 1024 patches after encoding. After a 2×2 merge, each frame has about 256 visual tokens, and 16 frames have about 4096 visual tokens. The actual numbers depend on the specific model; recalculate based on your own model before going live.

    V. Resource Control