AI Video API Frame Rate Normalization: Python and FFmpeg

Nov 23, 2026·10 min read

Your generation job succeeds, but an editing pipeline rejects the downloaded clip because its frame timestamps are irregular. AI video API frame rate normalization belongs in your application's delivery pipeline: inspect the completed asset, convert its video cadence when necessary, and verify that the derivative retains the original playback duration and audio.

This API integration tutorial starts after generation and download. For applications using the GenRelay video API, every operation below is post-generation, application-owned processing, not a documented GenRelay generation parameter or server-side conversion feature. No credentials, API requests, or paid generation are needed. You will build a local inspection and normalization stage using Python's standard library, FFmpeg, and ffprobe.

What does frame rate normalization change?

Frame rate normalization changes when frames are presented, without intentionally changing the clip's playback speed. Constant frame rate, or CFR, means adjacent presentation timestamps follow a fixed interval. Variable frame rate, or VFR, means those intervals can differ. A presentation timestamp identifies when a decoded frame should appear on the playback timeline.

Converting an irregular timeline to 30 CFR means selecting frames for a grid spaced one thirtieth of a second apart. FFmpeg can drop source frames or repeat them to populate that grid. It does not create additional motion detail. This tutorial does not implement slow motion or motion interpolation, which synthesizes intermediate images.

Choose a target based on the receiving system's contract. Use 30 for exactly thirty frames per second, or 30000/1001 for approximately 29.97. Those rates are different. Do not normalize every asset automatically: a player that accepts the original cadence may need no derivative, while an editor or downstream encoder may require a fixed delivery rate.

How do you inspect a downloaded clip before conversion?

Inspect stream metadata and decoded frame timestamps together, because a reported average frame rate does not prove constant cadence. Save the following as inspect_video.py, then run python3 inspect_video.py source.mp4. Install FFmpeg and ffprobe first and make both executables available on your command search path.

import json
import subprocess
import sys


def probe(path):
    result = subprocess.run(
        ["ffprobe", "-v", "error", "-show_streams", "-show_format",
         "-of", "json", str(path)],
        check=True, capture_output=True, text=True, timeout=60,
    )
    return json.loads(result.stdout)


def frame_times(path):
    result = subprocess.run(
        ["ffprobe", "-v", "error", "-select_streams", "v:0",
         "-show_frames", "-show_entries",
         "frame=best_effort_timestamp_time", "-of", "json", str(path)],
        check=True, capture_output=True, text=True, timeout=60,
    )
    return [float(f["best_effort_timestamp_time"])
            for f in json.loads(result.stdout)["frames"]
            if "best_effort_timestamp_time" in f]


if __name__ == "__main__":
    path = sys.argv[1]
    info = probe(path)
    times = frame_times(path)
    gaps = [b - a for a, b in zip(times, times[1:])]
    summary = {
        "streams": [{k: s.get(k) for k in (
            "codec_type", "codec_name", "r_frame_rate", "avg_frame_rate",
            "time_base", "start_time", "duration")}
            for s in info["streams"]],
        "container_duration": info["format"].get("duration"),
        "decoded_frames": len(times),
        "minimum_frame_gap": min(gaps) if gaps else None,
        "maximum_frame_gap": max(gaps) if gaps else None,
    }
    print(json.dumps(summary, indent=2))

The avg_frame_rate field describes an average; r_frame_rate is a stream rate estimate and is not a reliable VFR detector by itself. The time_base field expresses the timestamp tick size. Decoded timestamp gaps reveal the actual cadence, subject to that clock's precision. Allow small rounding differences rather than treating every unequal decimal as VFR.

Also check each stream's start time and duration. A container duration summarizes the file and can conceal shorter video or longer audio. The examples below target short, trusted local clips with one primary video stream and optional primary audio, both starting near zero and ending together. Route files with meaningful track offsets, multiple required audio tracks, or missing timestamps into a separate timing policy rather than silently rewriting them.

How can Python convert VFR to CFR without slowing the clip?

Use FFmpeg's fps video filter to resample the existing presentation timeline, and copy compatible audio without changing its timestamps. Save this second snippet as normalize_video.py beside the inspection script. Run python3 normalize_video.py source.mp4 delivery.mp4 30; the third argument also accepts rational rates such as 30000/1001.

from fractions import Fraction
from pathlib import Path
import subprocess
import sys

from inspect_video import frame_times, probe


def normalize(source, destination, rate="30"):
    target = Fraction(rate)
    if not 1 <= target <= 120:
        raise ValueError("delivery rate must be between 1 and 120 fps")
    source, destination = Path(source).resolve(), Path(destination).resolve()
    if source == destination or destination.exists():
        raise ValueError("choose a new output path; preserve the original")
    before = probe(source)
    videos = [s for s in before["streams"] if s["codec_type"] == "video"]
    audios = [s for s in before["streams"] if s["codec_type"] == "audio"]
    if len(videos) != 1 or len(audios) > 1:
        raise ValueError("expected one video and at most one audio stream")
    selected = videos + audios
    for stream in selected:
        if abs(float(stream.get("start_time", 0))) > 0.01:
            raise ValueError("nonzero track start requires an explicit timing policy")
        if "duration" not in stream:
            raise ValueError("missing stream duration requires separate inspection")
    source_duration = float(videos[0]["duration"])
    tolerance = max(1 / float(target), 0.05)
    if audios and abs(float(audios[0]["duration"]) - source_duration) > tolerance:
        raise ValueError("unequal track lengths require an explicit timing policy")
    if audios and audios[0]["codec_name"] != "aac":
        raise ValueError("this MP4 example expects AAC audio or no audio")
    rational = f"{target.numerator}/{target.denominator}"
    subprocess.run([
        "ffmpeg", "-hide_banner", "-loglevel", "error", "-nostdin", "-n",
        "-i", str(source), "-map", "0:v:0", "-map", "0:a:0?",
        "-vf", f"fps=fps={rational}:round=near",
        "-fps_mode:v", "cfr", "-c:v", "libx264", "-preset", "medium",
        "-crf", "18", "-pix_fmt", "yuv420p", "-c:a", "copy",
        "-movflags", "+faststart", str(destination),
    ], check=True, timeout=180)
    after = probe(destination)
    video = next(s for s in after["streams"] if s["codec_type"] == "video")
    assert Fraction(video["avg_frame_rate"]) == target, "wrong output rate"
    times = frame_times(destination)
    assert len(times) >= 2, "not enough frames to validate cadence"
    assert all(abs((b - a) - 1 / float(target)) < 0.0001
               for a, b in zip(times, times[1:])), "irregular output cadence"
    assert abs(float(video["duration"]) - source_duration) <= tolerance, "duration changed"
    output_audio = [s for s in after["streams"] if s["codec_type"] == "audio"]
    assert len(output_audio) == len(audios), "audio presence changed"
    if audios:
        assert abs(float(output_audio[0]["duration"]) -
                   float(audios[0]["duration"])) <= tolerance, "audio length changed"
    subprocess.run([
        "ffmpeg", "-v", "error", "-xerror", "-nostdin", "-i", str(destination),
        "-map", "0:v:0", "-map", "0:a:0?", "-f", "null", "-",
    ], check=True, timeout=180)
    return {"rate": rational, "duration": video["duration"],
            "audio_present": bool(output_audio), "decoded_frames": len(times)}


if __name__ == "__main__":
    print(normalize(sys.argv[1], sys.argv[2],
                    sys.argv[3] if len(sys.argv) > 3 else "30"))

This command re-encodes video as H.264 but stream-copies AAC audio, meaning the encoded audio packets are retained rather than decoded and re-encoded. The optional audio mapping accepts silent sources without manufacturing a soundtrack. For other audio codecs, choose a container-compatible encoding policy explicitly; consult the audio track handling guide before adding transcoding or muting.

The fps filter performs timestamp-based frame selection. The output fps_mode makes the requested CFR policy explicit. Neither option applies a playback-speed multiplier. Avoid changing the input rate with -r before -i, or applying a setpts expression that compresses or stretches timestamps, when the requirement is ordinary duration-preserving normalization.

How do you verify duration and audio synchronization?

Verify output cadence, per-stream duration, audio presence, and full decoding before accepting a derivative. The second snippet performs those checks and allows a duration tolerance of one target frame or fifty milliseconds, whichever is larger. Discrete frame grids can move the video endpoint slightly; normalization should not promise mathematically identical duration for every input.

Do not add -shortest reflexively. It ends output when the shortest output stream ends, which can discard a tail that your application intended to preserve. Likewise, independently resetting video and audio timestamps can erase a meaningful offset. This tutorial rejects notable offsets instead of pretending that timestamp cleanup is always safe.

A successful decode detects corrupt packets and decoder failures; it does not prove perceptual lip synchronization. Retain a test clip with a visible event and matching sound, then review the beginning and end on supported players. Add timestamp-offset assertions for your actual media contract. For playback-specific codec and container checks, continue with the browser playback guide.

How should this stage fit into an API application's worker?

Run normalization as a separate derivative job after the original download has passed validation, and expose the result only after local checks succeed. Keep generation completion distinct from delivery readiness. A conversion failure is not evidence that the generation request needs repeating.

Record the source asset identifier, target rational rate, encoder settings, FFmpeg version, and validation result. These values make a derivative reproducible and prevent confusing a new delivery profile with a new generation. Preserve the original asset and impose file-size, runtime, memory, and concurrent-process limits. The frame inspection example captures all frame records in memory, so production workers handling long videos should stream probe output or enforce short-clip limits.

The snippet writes a new local filename and raises on failure; it is not a complete publication transaction. A production worker should write into private staging, remove failed partial outputs, and promote the file only after validation. Run Python normally: its assert checks are disabled by optimization flags, so production validation should replace them with explicit exceptions.

What questions arise when normalizing generated video?

The most common questions concern what CFR actually guarantees and which timing changes require separate processing.

Does changing 24 fps to 30 fps make motion smoother?

Not necessarily. Frame repetition fills additional presentation slots but adds no newly generated movement. Motion interpolation is a different transformation with its own artifacts and compute cost; it is intentionally absent here.

Can I normalize frame rate without re-encoding video?

Not with the fps filter. Filtering requires decoding video and encoding the resulting frames. Merely editing a rate label or copying compressed video does not demonstrate that decoded presentation timestamps form a constant-rate grid.

Will normalizing a silent video add an audio track?

No. Optional audio mapping preserves absence as well as presence. If a destination requires silence encoded as an audio track, implement that as a separate delivery rule rather than confusing it with frame rate conversion.

Should every generated clip become 30 fps?

No. Normalize to an explicit downstream requirement, not a universal default. Preserve acceptable originals, distinguish exact 30 from fractional rates, and validate each derivative against its own delivery profile.

Related posts

Join our DiscordAI Video API Frame Rate Normalization: Python and FFmpeg — GenRelay