AI Video API Aspect Ratio Padding: Keep the Full Scene
Your generated landscape product clip looks correct until a vertical preview cuts off the packaging logo. AI video API aspect ratio padding solves the delivery mismatch by fitting the complete frame inside a fixed canvas, then filling the unused area instead of cropping the scene. For a 1080x1920 export, make that transformation in your application after downloading and validating the generated asset.
When integrating the GenRelay video API, treat this as application-owned postprocessing, not an assumed provider option or an undocumented request parameter. Keep the original and create a separate delivery file. Padding preserves the frame's composition; it cannot recover a logo already missing from the generated original.
Why does a vertical export cut off the original scene?
A vertical export cuts off the scene when a fill operation enlarges the image until the canvas is covered and discards the overflow. An aspect ratio is the relationship between displayed width and height. A landscape frame and a 9:16 destination have different proportions, so covering the destination necessarily removes part of that landscape image unless you distort it.
Letterboxing adds horizontal bands above and below an image; pillarboxing adds vertical bands beside it. The appropriate bands depend on the source relative to the destination, not whether somebody calls the clip “portrait.” A very tall portrait source can require side bands even inside a vertical canvas.
A fit-and-pad operation scales the source to fit within both canvas dimensions and fills the remainder. It preserves the whole scene geometrically, but downscaling can still make fine print unreadable. Black bands are an intentional layout choice, not evidence of a failed generation.
Check the player before re-encoding. CSS object-fit: cover can crop a correctly padded file again if its display box has another ratio. Use a matching preview box or a containment layout when the product requirement is to show every edge.
What geometry preserves a full scene inside 1080x1920?
Scale proportionally until neither dimension exceeds 1080x1920, center the result, and pad the remaining pixels. For a square-pixel source of width W and height H, the ideal scale factor is the smaller of 1080/W and 1920/H. Encoder-friendly dimensions may require slight rounding.
A 1920x1080 source fits at approximately 1080x608 after even-dimension rounding, leaving approximately 656 pixels above and below. This is geometry, not a measured performance result. Avoid promising that every source occupies the same content rectangle: source proportions and rounding determine that rectangle.
Sample aspect ratio, or SAR, describes the shape of an individual stored pixel. Display aspect ratio, or DAR, combines the stored dimensions with SAR to describe the intended displayed shape. The examples below require square pixels, SAR 1:1, and explicitly write that SAR to the output. Merely adding setsar=1 to an anamorphic source can change its intended proportions; it is not a general normalization algorithm.
Rotation metadata tells a player to transform stored pixels for display. These examples require an already upright file without a display rotation and disable automatic rotation deliberately. Inspect rotation and SAR first. Reject unexpected geometry or normalize it in a separately tested ingestion stage that applies the intended rotation and converts display proportions to square pixels. Do not erase orientation metadata before applying its meaning.
How can FFmpeg add padding without cropping the source?
Use scale with force_original_aspect_ratio=decrease, followed by pad and setsar, on a staged square-pixel, upright input. The following executable shell snippet assumes input.mp4 is a local, validated clip and requires FFmpeg with the libx264 encoder. Run it in a private job directory with an unused output name.
ffprobe -v error -select_streams v:0 \
-show_entries stream=width,height,sample_aspect_ratio:stream_tags=rotate:stream_side_data=rotation \
-of json input.mp4
# Continue only after confirming square pixels and no display rotation.
ffmpeg -v error -nostdin -n -noautorotate -i input.mp4 \
-map 0:v:0 -map '0:a:0?' -map_metadata -1 -map_chapters -1 \
-vf 'scale=1080:1920:force_original_aspect_ratio=decrease:force_divisible_by=2,pad=1080:1920:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1' \
-c:v libx264 -preset medium -crf 20 -pix_fmt yuv420p \
-c:a aac -b:a 128k -movflags +faststart padded-1080x1920.mp4
force_divisible_by=2 makes scaled dimensions even for the selected pixel format. ow and oh are the padding filter's output dimensions; iw and ih are its incoming image dimensions. Centering distributes unused space between opposite edges, subject to pixel and chroma alignment. No crop filter is involved.
The optional audio mapping selects the first audio stream if present. AAC encoding applies to that existing stream; it does not synthesize audio for a silent clip. If the existing codec is already acceptable in your tested MP4 delivery profile, replace the AAC options with -c:a copy to avoid audio re-encoding. Use -an instead of audio mapping and encoding when your explicit policy is silent delivery. Multiple-language selection needs its own track policy.
H.264 encoding changes the compressed video and can lose detail. The CRF value controls an encoder quality tradeoff, not a service quality guarantee. The browser playback guide covers codec and delivery checks; padding alone does not establish browser compatibility.
How can Python reject unexpected geometry before encoding?
Probe the input and reject unsupported orientation or SAR before constructing the same fit-and-pad command. Save this independent executable snippet as pad_portrait.py, then run python3 pad_portrait.py input.mp4 python-padded.mp4. Add --copy-audio when retaining a compatible original audio codec is intentional.
import argparse
import json
import subprocess
from fractions import Fraction
from pathlib import Path
def run(args):
return subprocess.run(
args, check=True, capture_output=True, text=True, timeout=180
).stdout
def probe(path):
return json.loads(run([
"ffprobe", "-v", "error", "-show_streams", "-of", "json", str(path)
]))
parser = argparse.ArgumentParser()
parser.add_argument("source", type=Path)
parser.add_argument("destination", type=Path)
parser.add_argument("--copy-audio", action="store_true")
args = parser.parse_args()
src = args.source.resolve(strict=True)
dst = args.destination.absolute()
if dst.exists() or dst.suffix.lower() != ".mp4":
raise ValueError("Choose an unused .mp4 destination")
streams = probe(src)["streams"]
videos = [s for s in streams if s["codec_type"] == "video"]
if len(videos) != 1 or videos[0].get("disposition", {}).get("attached_pic"):
raise ValueError("Exactly one real video stream required")
v = videos[0]
sar = v.get("sample_aspect_ratio", "")
if sar in ("", "N/A", "0:1") or Fraction(sar.replace(":", "/")) != 1:
raise ValueError("Normalize to known square pixels first")
rotations = [v.get("tags", {}).get("rotate", 0)]
rotations += [d["rotation"] for d in v.get("side_data_list", [])
if "rotation" in d]
if any(float(r) % 360 != 0 for r in rotations):
raise ValueError("Normalize display rotation first")
vf = (
"scale=1080:1920:force_original_aspect_ratio=decrease:"
"force_divisible_by=2,"
"pad=1080:1920:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1"
)
audio = (["-c:a", "copy"] if args.copy_audio else
["-c:a", "aac", "-b:a", "128k"])
run([
"ffmpeg", "-v", "error", "-nostdin", "-n", "-noautorotate",
"-i", str(src), "-map", "0:v:0", "-map", "0:a:0?",
"-map_metadata", "-1", "-map_chapters", "-1", "-vf", vf,
"-c:v", "libx264", "-preset", "medium", "-crf", "20",
"-pix_fmt", "yuv420p", *audio, "-movflags", "+faststart", str(dst),
])
out = next(s for s in probe(dst)["streams"] if s["codec_type"] == "video")
assert (out["width"], out["height"], out["sample_aspect_ratio"]) == (
1080, 1920, "1:1"
)
run(["ffmpeg", "-v", "error", "-xerror", "-nostdin", "-i", str(dst),
"-map", "0:v:0", "-map", "0:a:0?", "-f", "null", "-"])
print(json.dumps({"output": str(dst), "geometry": "1080x1920 SAR 1:1"}))
This is a geometry gate for staged local files, not a complete hostile-media processing service. It does not detect visually sideways pixels lacking metadata. Review mirrored or unusual display matrices separately. Production workers need restricted filesystem access, input limits, resource quotas, updated decoders, and an isolated temporary output promoted after validation. If this demonstration fails after encoding, its output is not approved for delivery.
How do you protect logos and validate the padded result?
Keep existing logos inside the full source frame, then review their readability and the destination player's overlays before release. Padding avoids intentional edge removal, but a smaller product label can become illegible after scaling, and platform controls can cover content even when the file is correct.
Do not stretch a logo, remove required attribution, or paint over a watermark to make the canvas look filled. If adding an authorized brand overlay, place it after padding in destination coordinates and keep it inside a reviewed safe area. A safe area is the region reserved for meaningful content away from expected interface overlays; its dimensions depend on the destination interface, not a universal pixel margin.
Validate more than the declared resolution. Confirm 1080x1920, SAR 1:1, expected duration, intended audio presence, and a full decode. Inspect representative frames near the beginning, middle, and end for lost edges, unexpected orientation, band placement, and logo readability. Use the video output validation checklist as the acceptance layer before publishing the derivative.
Local synthetic tests should cover landscape, ordinary portrait, and narrower-than-target inputs, with silent and audio-bearing variants. Include rejection cases for rotation metadata, non-square SAR, and an existing destination. Those checks establish the transformation's behavior on controlled fixtures, not model fidelity or real-device playback quality.
What questions remain about aspect ratio padding?
Padding changes delivery geometry rather than the generated scene; these distinctions prevent common integration mistakes.
Does padding turn landscape video into a newly composed portrait scene?
No. It places the landscape composition inside a portrait canvas. Reframing or generating a new portrait composition is a separate editorial decision.
Will padding preserve every logo clearly?
It preserves the frame boundaries, not guaranteed legibility. Review the scaled logo at its actual display size, especially when the source contains small text.
Can I use a background color instead of black bands?
Yes. Change the padding filter's color to a supported FFmpeg color value and test contrast. A blurred background requires a different compositing pipeline and should not obscure the foreground.
Does a silent input need an empty AAC track?
No. Optional mapping leaves a silent input without audio. Add silence only when a documented downstream delivery requirement explicitly calls for an audio stream.