AI Video API Rotation Metadata: Inspect and Normalize

Nov 24, 2026·10 min read

A downloaded clip looks upright in one player but sideways in your thumbnail service. AI video API rotation metadata can explain this mismatch: the file may store landscape-shaped pixels plus instructions telling a player to rotate them. Normalize the orientation into the pixels when your delivery pipeline cannot consistently honor those instructions, then verify the resulting file rather than trusting an encoder's exit status.

This API integration tutorial builds an application-owned inspection and delivery stage after downloading a completed asset. It applies to files obtained through the GenRelay video API, but neither snippet calls an API or assumes a generation parameter. You need Python 3, FFmpeg with the libx264 encoder, and ffprobe on your command search path. All processing and testing here use local files, not paid generation.

What does rotation metadata actually describe?

Rotation metadata describes a display transformation, not necessarily the arrangement of encoded pixels. Coded width and height describe the stored frame raster; a display transformation tells compatible software how to present that raster. A 320 × 180 raster with a quarter-turn instruction can therefore appear as portrait video without storing 180 × 320 frames.

A display matrix is a numeric transformation associated with a video track. In ffprobe JSON, it commonly appears inside side_data_list, with side_data_type equal to Display Matrix and a derived rotation value. Side data means structured information associated with a stream beyond its ordinary key-value tags.

Older files and tools may expose tags.rotate instead. Do not inspect only that tag: contemporary MP4 files can have a valid matrix and no rotate tag. Conversely, a visible tag does not prove that the container contains a working display matrix. Probe the saved file, not just FFmpeg's description of metadata before writing it.

The numeric rotation extracted from a matrix also should not be copied blindly into a manual clockwise filter. Sign conventions and coordinate systems differ between representations. Establish the intended orientation using a recognizable frame, especially when resolving contradictory sources.

How do you inspect both rotation representations with Python?

Read the complete video stream record and retain both the display matrix and legacy rotation tag. Save this first executable snippet as inspect_rotation.py, then run python3 inspect_rotation.py source.mp4. It deliberately reports raw evidence rather than claiming that a single angle completely describes every matrix.

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 matrices(video):
    return [item for item in video.get("side_data_list", [])
            if item.get("side_data_type") == "Display Matrix"]


if __name__ == "__main__":
    info = probe(sys.argv[1])
    video = next(s for s in info["streams"]
                 if s["codec_type"] == "video")
    print(json.dumps({
        "width": video["width"], "height": video["height"],
        "sample_aspect_ratio": video.get("sample_aspect_ratio"),
        "legacy_rotate": video.get("tags", {}).get("rotate"),
        "display_matrices": matrices(video),
        "video_duration": video.get("duration"),
        "audio_streams": sum(s["codec_type"] == "audio"
                             for s in info["streams"]),
    }, indent=2))

Sample aspect ratio, or SAR, describes the width of an individual pixel relative to its height. Square pixels have SAR 1:1. Before rotation, display aspect ratio is approximately coded width divided by coded height, multiplied by SAR. A quarter-turn swaps the displayed axes, so merely checking whether coded height exceeds width is not an orientation test.

The normalization example below intentionally accepts only square-pixel inputs. Changing an anamorphic source to setsar=1 without corresponding resampling would change its displayed shape. Handle those assets through a separate geometry policy that calculates display dimensions before resizing.

How do you bake the intended orientation into pixels?

Let FFmpeg's default autorotation operate during video transcoding, and do not also add a manual transpose filter. Autorotation applies supported display transformations while decoding and filtering for a new encode. Adding another quarter-turn after that can rotate an already corrected frame a second time.

Save this second snippet as normalize_rotation.py beside the inspection script. Run python3 normalize_rotation.py source.mp4 delivery.mp4 180 320, supplying the expected upright output width and height from your delivery contract or visual inspection. Requiring that expectation prevents a no-op conversion from silently passing as a successful portrait normalization.

from pathlib import Path
import subprocess
import sys

from inspect_rotation import matrices, probe


def require(condition, message):
    if not condition:
        raise ValueError(message)


def normalize(source, destination, width, height):
    source, destination = Path(source).resolve(), Path(destination).resolve()
    require(source != destination and not destination.exists(),
            "choose a new output path")
    require(width > 0 and height > 0, "invalid expected geometry")
    before = probe(source)
    videos = [s for s in before["streams"] if s["codec_type"] == "video"]
    audio = [s for s in before["streams"] if s["codec_type"] == "audio"]
    require(len(videos) == 1 and len(audio) <= 1,
            "expected one video and at most one audio stream")
    video = videos[0]
    require(video.get("sample_aspect_ratio") == "1:1",
            "non-square or unknown SAR needs a separate geometry policy")
    require(not audio or audio[0]["codec_name"] == "aac",
            "this MP4 example preserves AAC audio only")
    for stream in videos + audio:
        require("duration" in stream, "missing stream duration")
        require(abs(float(stream.get("start_time", 0))) <= 0.01,
                "track offsets need a separate timing policy")
    subprocess.run([
        "ffmpeg", "-hide_banner", "-loglevel", "error", "-nostdin", "-n",
        "-i", str(source), "-map", "0:v:0", "-map", "0:a:0?",
        "-vf", "setsar=1", "-c:v", "libx264", "-preset", "medium",
        "-crf", "18", "-pix_fmt", "yuv420p", "-c:a", "copy",
        "-map_metadata", "-1", "-metadata:s:v:0", "rotate=0",
        "-movflags", "+faststart", str(destination),
    ], check=True, timeout=180)
    after = probe(destination)
    output = next(s for s in after["streams"] if s["codec_type"] == "video")
    require((output["width"], output["height"]) == (width, height),
            "unexpected output geometry")
    require(output.get("sample_aspect_ratio") == "1:1", "unexpected SAR")
    require(not matrices(output), "output still contains a display matrix")
    require(float(output.get("tags", {}).get("rotate", 0)) == 0,
            "output still requests rotation")
    require(abs(float(output["duration"]) - float(video["duration"])) <= 0.05,
            "video duration changed")
    out_audio = [s for s in after["streams"] if s["codec_type"] == "audio"]
    require(len(out_audio) == len(audio), "audio presence changed")
    if audio:
        require(out_audio[0]["codec_name"] == audio[0]["codec_name"],
                "audio codec changed")
        require(abs(float(out_audio[0]["duration"]) -
                    float(audio[0]["duration"])) <= 0.05,
                "audio duration 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 {"width": width, "height": height,
            "duration": output["duration"], "audio_preserved": bool(audio)}


if __name__ == "__main__":
    print(normalize(sys.argv[1], sys.argv[2],
                    int(sys.argv[3]), int(sys.argv[4])))

Video must be re-encoded because baking orientation changes decoded pixels; -c:v copy cannot apply a pixel rotation. Audio is different: -c:a copy retains compatible encoded audio without re-encoding it, and the optional audio mapping accepts silent clips. The command does not add -shortest, reset timestamps, or deliberately change playback speed.

The rotate=0 assignment requests neutral orientation metadata, while -map_metadata -1 suppresses automatic metadata copying. Neither flag alone proves that every form of side data disappeared. This example rejects any remaining display matrix, including an identity matrix, as a deliberately strict delivery rule. If a different FFmpeg build preserves one, investigate the actual output instead of weakening validation without understanding it.

How can you test a real rotation fixture locally?

Create a baseline MP4, attach orientation through a stream-copy pass, and confirm that ffprobe actually sees the transformation before testing normalization. A fixture is a controlled test asset with known properties. Use an asymmetric test pattern so visual rotation remains recognizable, plus an audio tone to detect accidental soundtrack removal.

The intended fixture recipe creates two seconds of 320 × 180 H.264 video with AAC audio, then runs a stream-copy command containing -metadata:s:v:0 rotate=90. There is an important version limitation: in the local FFmpeg 9.0.2 test, that command completed successfully but the resulting file had neither a display matrix nor a rotate tag. Treating it as a rotated fixture would have produced a false positive.

For the real matrix fixture on that build, an additional stream-copy pass used the input option -display_rotation:v:0 90 before -i. A subsequent ffprobe inspection confirmed a Display Matrix with rotation 90. This explicit input override is a fixture-construction choice, not an instruction to overwrite orientation on unknown production clips.

Running the two Python snippets against that matrix-bearing file produced 180 × 320 video with SAR 1:1, unchanged two-second video and audio durations, and no remaining display matrix or nonzero rotate tag. AAC audio remained present, its probed packet payload hashes matched the source, and the output decoded successfully. An unrotated control retained 320 × 180 geometry. These are synthetic local-media checks, not tests of generated content or provider behavior.

Where should this stage run in an API delivery pipeline?

Run orientation normalization after download validation and before generating thumbnails, publication derivatives, or player-specific assets. Preserve the original download and record probe JSON, expected geometry, FFmpeg version, conversion settings, and validation outcome with each derivative.

Do not combine every media repair into one unexplained operation. Orientation concerns spatial presentation; timing concerns frame scheduling. Apply a separate, explicit policy if your destination also needs frame rate normalization. For player compatibility beyond orientation, use the browser playback guide.

The snippets target short, trusted, ordinary SDR clips. Standard dynamic range, or SDR, is the conventional brightness and color delivery range rather than an HDR mastering workflow. The H.264 settings here are not a color-preservation recipe for every source. Production workers also need resource limits, private staging, partial-output cleanup, and promotion only after validation succeeds.

What questions do developers ask about rotation metadata?

The recurring questions concern metadata-only changes, conflicting instructions, and what geometric checks can prove.

Can I fix sideways playback just by deleting the rotate tag?

Only if the stored pixels already have the intended orientation and the tag is erroneous. Deleting a valid display instruction can make a previously upright clip sideways. Confirm pixel orientation independently before changing metadata alone.

Should I use transpose when autorotation is enabled?

Not for the same rotation. Choose either metadata-driven autorotation or an explicit manual transformation with input autorotation disabled. Manual processing requires a validated mapping from source orientation to the chosen filter, not an assumed angle-sign conversion.

Does a zero rotation value prove the matrix is harmless?

No. Matrices can contain reflection, scaling, or other transformations that a single derived angle cannot describe. Conflicting tags, unusual matrices, and container-specific behavior require matrix inspection and visual review; this tutorial does not implement a general matrix validator.

Do correct portrait dimensions prove the subject is upright?

No. Dimensions cannot distinguish upright from upside-down pixels, and content can already be rotated despite misleading metadata. Verify recognizable frames and representative playback as well as geometry, duration, audio, and the final output probe.

Related posts

Join our DiscordAI Video API Rotation Metadata: Inspect and Normalize — GenRelay