AI video API output validation: Catch Broken Files
Your generation job reports success, but the downloaded MP4 has no usable video stream, the wrong dimensions, or a duration your editor cannot accept. AI video API output validation catches these delivery defects before customers receive a download link. Treat generation completion and application acceptance as separate events: a completed job is not proof that its bytes meet your product's requirements.
For applications using the GenRelay video API, the checks below belong to your own download and delivery pipeline. They describe application controls, not a promise of native GenRelay validation or undocumented response fields.
What should AI video API output validation check?
Validate the downloaded bytes, the video stream, the expected dimensions, and a declared duration tolerance before making the asset available. A container is the file structure that holds encoded video, audio, timestamps, and metadata; an MP4 extension alone proves none of those contents are correct.
Use three gates:
- Acquisition: confirm the download finished under your size and time limits, then close the writer and place the file in private application-owned storage.
- Structural acceptance: inspect the container and streams using ffprobe, the media inspection utility distributed with FFmpeg.
- Delivery acceptance: enforce your playback, content, and access-control requirements before publishing an application download URL.
Store the requested output contract before submitting generation: expected encoded width and height, expected duration, accepted deviation, and any required audio or codec rules. These are your application's values, not assumed API parameter names. Do not infer the contract from the returned file itself; that would let an incorrect output define its own acceptance criteria.
Why can a successful response still produce an unusable video?
Job success describes generation status, while usability depends on the complete download and your downstream requirements. An interrupted transfer can leave an incomplete file; an error document can be saved with an MP4 filename; a valid container can contain audio without video.
A file can also be technically readable but unsuitable for your editor. Examples include portrait dimensions for a landscape placement, an unsupported codec, missing required audio, or timestamps that produce an unexpected playback length.
Separate these diagnoses. A transfer problem may justify downloading the same existing result again. A specification mismatch needs investigation of the recorded request and actual output. Neither condition automatically justifies another paid generation. Use result reconciliation to associate attempts, downloaded artifacts, and acceptance decisions without confusing them with new generation requests.
Which duration should you compare with the request?
Compare media durations with your playback contract, but keep them separate from billable duration. Container duration is the file-level playback length reported by the demuxer, the component that reads a container; video-stream duration describes the video track and may be absent in some formats.
Audio can extend beyond the video track. Timestamp offsets and rounding can also make the two durations differ. Checking container duration alone could accept a file whose audio reaches eight seconds while its video stops much earlier.
Define an explicit rule, such as an eight-second target with an absolute tolerance of 0.25 seconds. That number is an illustrative application policy, not a measured platform guarantee. The example below requires both reported durations to be finite, positive, and within that tolerance. Missing duration is rejected for review rather than silently accepted. Some otherwise valid files will therefore need a separate inspection path.
Billable duration is the quantity defined by the applicable pricing and usage record. Do not derive it by rounding ffprobe output or substituting container duration into an invoice calculation. Preserve generation-level usage evidence separately; an output-validation failure does not establish that a charge is incorrect or refundable.
How can you inspect an application-owned file locally?
Run ffprobe against a private local file using a subprocess argument list, then reject metadata that violates a recorded contract. This example deliberately does not accept URLs or download anything.
Save this as validate_video.py. It requires Python 3 and an installed ffprobe executable on PATH. The JSON fields below are ffprobe output fields, not GenRelay API fields. The policy accepts exactly one non-cover-art video stream and checks encoded dimensions, not rotation-adjusted display dimensions.
import argparse
import json
import math
from pathlib import Path
import shutil
import subprocess
class Rejected(ValueError):
pass
def check_metadata(meta, width, height, seconds, tolerance):
if (type(width) is not int or type(height) is not int
or width < 1 or height < 1):
raise Rejected("invalid dimension policy")
if (not math.isfinite(seconds) or seconds <= 0
or not math.isfinite(tolerance) or tolerance < 0):
raise Rejected("invalid duration policy")
videos = [s for s in meta.get("streams", [])
if s.get("codec_type") == "video"
and not s.get("disposition", {}).get("attached_pic", 0)]
if len(videos) != 1:
raise Rejected("expected one video stream")
video = videos[0]
if (video.get("width"), video.get("height")) != (width, height):
raise Rejected("dimension mismatch")
durations = {}
for label, raw in (("container", meta.get("format", {}).get("duration")),
("video", video.get("duration"))):
try:
value = float(raw)
except (TypeError, ValueError):
raise Rejected(label + " duration unavailable") from None
if not math.isfinite(value) or value <= 0:
raise Rejected(label + " duration invalid")
if abs(value - seconds) > tolerance + 1e-9:
raise Rejected(label + " duration outside tolerance")
durations[label] = value
return {"width": width, "height": height, **durations}
def validate(root, name, width, height, seconds, tolerance):
root = Path(root).resolve(strict=True)
# Direct children with server-generated filenames; no paths or URLs.
if not name or Path(name).name != name or name in (".", ".."):
raise Rejected("expected a local filename")
path = root / name
if path.is_symlink() or not path.is_file():
raise Rejected("expected a regular, non-symlink file")
if not 0 < path.stat().st_size <= 100 * 1024 * 1024:
raise Rejected("file outside application byte limit")
executable = shutil.which("ffprobe")
if executable is None:
raise Rejected("ffprobe unavailable")
command = [
executable, "-v", "error", "-protocol_whitelist", "file,pipe",
"-show_entries",
"format=duration:stream=codec_type,width,height,duration:"
"stream_disposition=attached_pic",
"-of", "json", str(path),
]
try:
result = subprocess.run(command, capture_output=True, text=True,
timeout=10, check=True)
metadata = json.loads(result.stdout)
if not isinstance(metadata, dict):
raise Rejected("unexpected probe document")
return check_metadata(metadata, width, height, seconds, tolerance)
except (OSError, subprocess.SubprocessError, ValueError, TypeError,
AttributeError) as exc:
raise Rejected("probe rejected: " + type(exc).__name__) from exc
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("root")
parser.add_argument("name")
parser.add_argument("--width", type=int, required=True)
parser.add_argument("--height", type=int, required=True)
parser.add_argument("--seconds", type=float, required=True)
parser.add_argument("--tolerance", type=float, default=0.25)
args = parser.parse_args()
try:
print(json.dumps(validate(args.root, args.name, args.width,
args.height, args.seconds, args.tolerance)))
except (Rejected, OSError) as exc:
parser.exit(1, "QUARANTINE: " + str(exc) + "\n")
For example, run python3 validate_video.py /srv/app/quarantine clip.mp4 --width 1280 --height 720 --seconds 8. Successful output means these specific metadata checks passed, not that every frame decoded or the content is safe. A nonzero exit keeps the file quarantined; it must not trigger public delivery.
What security boundaries does this check still need?
Run inspection in an isolated worker because a local filename does not make untrusted media safe. The subprocess uses no shell, and the protocol allowlist excludes network protocols, but neither control is a complete sandbox.
The private directory must not be writable by customers or concurrent processes replacing files. The pathname checks are not race-proof against an attacker with filesystem write access. Use immutable artifacts and restrict the worker's filesystem view so malicious media cannot reference unrelated local files.
The 100 MiB input cap and ten-second timeout are illustrative limits. A timeout bounds elapsed subprocess time, not total memory, CPU consumption, or captured output. capture_output=True buffers output in memory. Production isolation should enforce operating-system memory and CPU limits, bounded logs/output, process-count limits, no network access, and a narrowly mounted input directory. Keep FFmpeg patched.
Metadata inspection does not fully decode the video. If delivery requires decode verification, run a separate constrained decoding stage. Codec compatibility, required audio, content moderation, and rotation handling also need explicit checks beyond this example.
How should failures affect quarantined delivery?
Keep failed or uncertain files private until a recorded acceptance decision permits delivery. Quarantine means application-controlled storage that customer-facing download routes cannot expose automatically.
Record an internal artifact identifier, content hash, policy version, probe outcome, and failure category. Bind acceptance to the exact immutable bytes inspected. Promote through an atomic application-state transition; issuing a public link before inspection finishes defeats the gate.
Retry a download for a confirmed transfer failure under a bounded policy. Route repeated probe errors, missing metadata, or specification mismatches to review rather than creating an endless generation loop. Schedule deletion for both rejected files and diagnostic records using your retention policy, preserving necessary billing evidence independently.
What questions arise when validating generated videos?
The recurring questions concern trust, decoding, tolerances, and repeat attempts.
Can I trust Content-Type instead of ffprobe?
No. A Content-Type header is useful download metadata, but it does not prove that the saved bytes contain a usable video track.
Does a successful ffprobe result prove every frame is playable?
No. Metadata can be readable while later packets are damaged. Add constrained full decoding when your acceptance requirements demand it.
Should I require an exact duration match?
Not usually. Define a tolerance appropriate to your editor and supported formats, then apply it consistently. Do not silently widen it after a failure.
Should validation failure automatically regenerate the video?
No. Diagnose transfer, inspection, and specification failures first. Another generation may incur a separate charge without fixing the underlying delivery problem.