AI Video API Sample Aspect Ratio: Normalize Non-Square Pixels
A downloaded clip looks correctly proportioned in a desktop player, but your application displays a stretched product or an unexpectedly narrow poster. AI video API sample aspect ratio is one property worth checking before changing your page layout. A video frame can contain non-square pixels, so its stored width divided by height does not necessarily describe its intended display shape.
This problem-solving guide covers an application-owned processing stage after downloading a completed asset from the GenRelay video API. It does not claim that generated clips normally have non-square pixels or introduce a generation parameter. The examples inspect local files using Python 3, ffprobe, and FFmpeg with the libx264 encoder. They make no paid requests. The normalization example intentionally produces a muted derivative; preserve the original separately if its audio matters.
What is the difference between sample and display aspect ratio?
Sample aspect ratio describes the shape of a pixel, while display aspect ratio describes the intended shape of the presented frame. Sample aspect ratio is commonly abbreviated SAR. Display aspect ratio is commonly abbreviated DAR.
For an ordinary unrotated frame, the relationship is:
DAR = (stored width / stored height) × SAR
A 720 × 576 frame has a stored width-to-height ratio of 5:4. With SAR 16:15, its display ratio becomes 4:3. With square pixels, SAR is 1:1 and display shape follows stored dimensions directly. Anamorphic video stores a picture using non-square pixels to represent a different display shape from the encoded raster.
Container metadata, codec signaling, and player behavior can complicate presentation. A stored ratio is not evidence that a browser, thumbnail extractor, or downstream editor interpreted it consistently. Inspect the completed file and verify the derivative in the software your application actually uses.
| Stored dimensions | SAR | Intended unrotated DAR |
|---|---|---|
| 720 × 576 | 16:15 | 4:3 |
| 720 × 576 | 64:45 | 16:9 |
| 768 × 576 | 1:1 | 4:3 |
These are mathematical examples, not supported GenRelay generation settings or claims about model output sizes.
Why can setting SAR to one distort the picture?
Setting SAR to one without resampling changes display interpretation rather than preserving the original display geometry. FFmpeg's setsar=1 filter declares square pixels; it does not automatically add or remove columns to compensate for the previous pixel shape.
For the 720 × 576 example with SAR 16:15, applying setsar=1 alone changes DAR from 4:3 to 5:4. Objects become narrower relative to their height. The correct square-pixel derivative can instead use 768 × 576 pixels, because 768/576 equals 4/3.
Resample the frame to dimensions approximating the intended DAR, then declare SAR 1:1. Resampling means calculating a new raster from the old one. It can change fine detail and require video re-encoding, so keep an original asset and record the transformation policy version. Do not present a delivery conversion as a new model generation or a resolution upgrade.
How do you inspect SAR with Python and ffprobe?
Read the selected video stream's width, height, sample aspect ratio, and rotation information before choosing an output geometry. Save this snippet as inspect_sar.py and run python3 inspect_sar.py input.mp4.
import json
import subprocess
from fractions import Fraction
MAX_DIM = 4096
MAX_PIXELS = 9_000_000
def inspect(path):
result = subprocess.run(
["ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_streams", "-of", "json", str(path)],
check=True, capture_output=True, text=True, timeout=20,
)
streams = json.loads(result.stdout).get("streams", [])
if len(streams) != 1:
raise ValueError("Expected a video stream")
stream = streams[0]
width, height = int(stream["width"]), int(stream["height"])
if not (0 < width <= MAX_DIM and 0 < height <= MAX_DIM):
raise ValueError("Dimensions outside policy")
if width * height > MAX_PIXELS:
raise ValueError("Raster outside pixel policy")
raw = stream.get("sample_aspect_ratio", "")
try:
sar = Fraction(raw.replace(":", "/"))
except (ValueError, ZeroDivisionError):
raise ValueError("Missing or invalid SAR") from None
if not Fraction(1, 4) <= sar <= 4:
raise ValueError("SAR outside supported policy")
if float(stream.get("tags", {}).get("rotate", 0)) != 0:
raise ValueError("Normalize rotation in a separate stage")
for item in stream.get("side_data_list", []):
if item.get("side_data_type") == "Display Matrix":
raise ValueError("Display matrix requires separate review")
return width, height, sar
if __name__ == "__main__":
import sys
width, height, sar = inspect(sys.argv[1])
print({"width": width, "height": height, "sar": str(sar),
"dar": str(Fraction(width, height) * sar)})
This policy deliberately rejects unspecified SAR rather than silently assuming square pixels. It also rejects display matrices, which can encode transformations beyond a simple rotation angle. Route those files to a separate orientation-aware stage. Rejection is a processing decision, not proof that the source file is invalid or that generation failed.
The process timeout bounds the subprocess duration, but it is not a complete resource sandbox. Use local private paths, bounded input bytes and duration, restricted workers, and tested decoder versions. Do not hand arbitrary user URLs to a media subprocess.
How do you normalize non-square pixels without stretching content?
Calculate an even square-pixel width from the intended display ratio, then scale and set SAR explicitly. The example keeps height approximately unchanged, rounds both dimensions to even values for a conventional H.264 delivery profile, and rejects outputs outside its application limits.
Save this second snippet as normalize_sar.py beside the inspector. Use a fresh staging destination rather than overwriting your source.
import subprocess
from fractions import Fraction
from pathlib import Path
from inspect_sar import inspect, MAX_DIM, MAX_PIXELS
def normalize(source, destination):
source, destination = Path(source), Path(destination)
if source.resolve() == destination.resolve():
raise ValueError("Source and destination must differ")
width, height, sar = inspect(source)
target_dar = Fraction(width, height) * sar
out_h = 2 * round(Fraction(height, 2))
out_w = 2 * round(target_dar * out_h / 2)
if not (2 <= out_w <= MAX_DIM and 2 <= out_h <= MAX_DIM):
raise ValueError("Target dimensions outside policy")
if out_w * out_h > MAX_PIXELS:
raise ValueError("Target exceeds pixel policy")
subprocess.run(
["ffmpeg", "-v", "error", "-nostdin", "-n",
"-noautorotate", "-i", str(source), "-map", "0:v:0",
"-vf", f"scale={out_w}:{out_h},setsar=1",
"-an", "-c:v", "libx264", "-pix_fmt", "yuv420p",
"-map_metadata", "-1", "-movflags", "+faststart",
str(destination)],
check=True, timeout=120,
)
actual_w, actual_h, actual_sar = inspect(destination)
if (actual_w, actual_h, actual_sar) != (out_w, out_h, Fraction(1)):
raise ValueError("Unexpected output geometry")
if abs(Fraction(actual_w, actual_h) - target_dar) > Fraction(1, out_h):
raise ValueError("Display ratio rounding exceeded policy")
subprocess.run(
["ffmpeg", "-v", "error", "-xerror", "-nostdin",
"-i", str(destination), "-map", "0:v:0", "-f", "null", "-"],
check=True, capture_output=True, timeout=120,
)
return out_w, out_h
if __name__ == "__main__":
import sys
print(normalize(sys.argv[1], sys.argv[2]))
The rounding tolerance acknowledges that integer raster dimensions cannot represent every rational display ratio exactly. Very narrow targets or large expansion factors should fail rather than producing surprising files. This example is intentionally conservative; a production pipeline may choose a different bounded resizing policy.
-an removes audio from the derivative. +faststart relocates MP4 metadata for progressive playback; it does not prove browser codec compatibility. The browser playback guide discusses that separate validation step. If you need a portrait canvas after normalization, apply a deliberate fit-and-pad stage as described in aspect ratio padding.
What should you test before publishing a derivative?
Test metadata, decoded geometry, and visible proportions rather than relying on an encoder's successful exit. Build a synthetic 720 × 576 fixture with SAR 16:15 and assert that normalization produces 768 × 576 with SAR 1:1. Repeat with SAR 64:45 and expect 1024 × 576.
Include a square-pixel control, a clip with a display rotation matrix, and an input outside dimension policy. The square-pixel control should preserve geometry; unsupported transforms and oversized rasters should be rejected. Check duration within a frame-sized tolerance, confirm the derivative contains no audio under this muted policy, and decode the complete output.
Use a frame containing circles or a calibration grid for visual inspection. Metadata arithmetic can be correct while an earlier editing stage already stretched the underlying image. Do not automatically compensate twice simply because the subject looks unusual.
Does pixel normalization create another generation charge?
Local transcoding is application compute, not another model generation request. Using the supplied GenRelay prices as of November 25, 2026, Omni Flash costs $0.10 per generation at 720P and $0.15 per generation at 1080P. A batch of 100 generations therefore costs $10 or $15 respectively, before application processing and storage.
Normalizing those downloaded files does not itself submit 100 more generations. Track transcoding CPU time, storage, and delivery traffic separately. If inspection rejects an asset, investigate the saved original and processing policy before considering a paid replacement. A non-square-pixel signal is not evidence that the model needs to be called again.
What do developers frequently ask?
Is SAR the same as video resolution?
No. Resolution describes raster dimensions; SAR describes pixel shape. Both contribute to display geometry.
Can I fix every file with setsar=1?
No. Changing the declaration without compensating resampling can distort anamorphic content. Inspect the intended display ratio first.
Should an unknown SAR be treated as 1:1?
Not automatically. Adopt an explicit ingestion policy and verify the source. The example rejects unknown values for separate review.
Does this example preserve audio and orientation metadata?
No. It creates a muted derivative and rejects display transformations before encoding. Handle audio retention and orientation in separately tested stages.