AI Video API Browser Playback: Diagnose and Fix Failed Videos
Your product-preview dashboard reports a completed generation, but Safari shows a blank player while a desktop media application opens the downloaded file. AI video API browser playback requires more than a successful generation: inspect the saved media, produce an appropriate delivery derivative when necessary, and test the actual HTTP response on your supported devices.
For an application integrating the GenRelay video API, these are application-owned postprocessing and delivery steps, not assumed generation parameters. Preserve the authorized original, keep playback failures separate from generation failures, and avoid paying for another generation before diagnosing the existing asset.
Why does a completed video fail in a browser?
A completed video can fail because its encoded streams, container metadata, HTTP delivery, or playback policy do not match the browser's requirements. Start by distinguishing those layers instead of renaming the extension.
A container packages encoded streams and timing information; MP4 is a container. A codec defines how media is compressed and decoded; H.264 encodes video, while AAC encodes audio. A pixel format describes how decoded image components are represented; yuv420p uses eight-bit components with reduced color resolution. These properties are separate: an MP4 file can contain a codec your target device cannot decode.
A MIME type is the media label sent in an HTTP Content-Type header. An actual MP4 delivery asset normally uses video/mp4; changing that header cannot convert incompatible media. Likewise, a browser rejecting audible autoplay is not evidence that decoding failed. Test user-initiated playback before diagnosing autoplay.
| Symptom | First check | Next action |
|---|---|---|
| Local player works, browser fails | Video codec and pixel format | Produce a tested delivery derivative |
| Playback waits for the entire download | MP4 metadata placement | Apply faststart and inspect delivery |
| Video plays without expected sound | Audio stream and player mute state | Inspect audio separately |
| Seeking fails after playback starts | Byte-range response behavior | Test the storage and delivery path |
| Cross-origin requests fail | Browser console and access headers | Match the actual request mode |
How do you inspect an application-owned local file?
Inspect a staged local file with ffprobe, FFmpeg's metadata inspection utility, before attempting conversion. A staged file is a completed download placed in a private processing directory where other jobs cannot modify it.
Save the following as browser_mp4.py. This first section prints metadata when executed directly and supplies inspection functions used by the conversion section below. It deliberately accepts one MP4-family video stream, with at most one audio stream. Other containers need a separately reviewed ingestion policy.
import json
import math
import os
import subprocess
import tempfile
from pathlib import Path
def run(args, timeout=15):
return subprocess.run(
args, check=True, capture_output=True,
text=True, timeout=timeout,
).stdout
def inspect(path):
path = Path(path).resolve(strict=True)
if not path.is_file() or not 0 < path.stat().st_size <= 100 * 1024**2:
raise ValueError("input file/byte policy")
info = json.loads(run([
"ffprobe", "-v", "error", "-protocol_whitelist", "file",
"-show_streams", "-show_format", "-of", "json", str(path),
]))
if "mp4" not in info["format"]["format_name"].split(","):
raise ValueError("MP4-family input required")
video = [s for s in info["streams"] if s["codec_type"] == "video"]
audio = [s for s in info["streams"] if s["codec_type"] == "audio"]
if len(video) != 1 or len(audio) > 1:
raise ValueError("stream policy")
v = video[0]
if v.get("disposition", {}).get("attached_pic"):
raise ValueError("cover art is not a video")
if not all(0 < v.get(k, 0) <= 4096 for k in ("width", "height")):
raise ValueError("dimension policy")
duration = float(info["format"]["duration"])
if not math.isfinite(duration) or not 0 < duration <= 60:
raise ValueError("duration policy")
return info
The 100 MiB, 4096-pixel, and 60-second limits are example application policies, not GenRelay limits. Metadata inspection is not complete validation: a file may declare plausible dimensions while containing damaged packets. The video output validation guide explains why acceptance should include decoding rather than trusting filenames or job status.
How can you create and validate a browser MP4 derivative?
Create a separate H.264, yuv420p MP4 derivative, retain AAC audio when present, then decode the result before making it visible. A derivative is a transformed copy of an original asset. This profile is a practical compatibility starting point, not a promise for every browser, operating system, or device.
Append this section to the same file. Install a current FFmpeg build that includes libx264, an H.264 encoder, and the AAC encoder. The worker's output directory must already exist and be private to the job; choose a new, versioned destination name.
def convert(source, destination):
source = Path(source).resolve(strict=True)
destination = Path(destination).absolute()
original = inspect(source)
if destination.exists() or destination == source:
raise ValueError("choose an unused derivative path")
fd, temporary = tempfile.mkstemp(
prefix=".browser-", suffix=".mp4", dir=destination.parent,
)
os.close(fd)
temporary = Path(temporary)
try:
run([
"ffmpeg", "-v", "error", "-nostdin", "-y",
"-protocol_whitelist", "file", "-threads", "1",
"-i", str(source), "-map", "0:v:0", "-map", "0:a:0?",
"-map_metadata", "-1", "-map_chapters", "-1",
"-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2,setsar=1",
"-c:v", "libx264", "-preset", "medium", "-crf", "23",
"-pix_fmt", "yuv420p", "-threads", "1",
"-c:a", "aac", "-b:a", "128k", "-ac", "2", "-ar", "48000",
"-movflags", "+faststart", "-f", "mp4", str(temporary),
], timeout=120)
result = inspect(temporary)
videos = [s for s in result["streams"] if s["codec_type"] == "video"]
audios = [s for s in result["streams"] if s["codec_type"] == "audio"]
had_audio = any(s["codec_type"] == "audio" for s in original["streams"])
if videos[0]["codec_name"] != "h264" or videos[0]["pix_fmt"] != "yuv420p":
raise ValueError("unexpected video encoding")
if bool(audios) != had_audio or any(s["codec_name"] != "aac" for s in audios):
raise ValueError("unexpected audio encoding")
before = float(original["format"]["duration"])
after = float(result["format"]["duration"])
if abs(before - after) > 0.5:
raise ValueError("unexpected duration change")
run([
"ffmpeg", "-v", "error", "-xerror", "-nostdin",
"-protocol_whitelist", "file", "-threads", "1",
"-i", str(temporary), "-map", "0:v:0", "-map", "0:a:0?",
"-f", "null", "-",
], timeout=120)
os.replace(temporary, destination)
return result
finally:
temporary.unlink(missing_ok=True)
if __name__ == "__main__":
import sys
if len(sys.argv) == 2:
print(json.dumps(inspect(sys.argv[1]), indent=2))
elif len(sys.argv) == 3:
print(json.dumps(convert(sys.argv[1], sys.argv[2]), indent=2))
else:
raise SystemExit("usage: browser_mp4.py INPUT [OUTPUT.mp4]")
Run python3 browser_mp4.py original.mp4 playback.mp4; omit the output argument to inspect. The optional audio mapping preserves a silent input as silent rather than inventing a soundtrack. Review narration, music rights, and track selection separately using the audio-track guide.
The temporary output stays beside its destination, allowing an atomic rename: readers see either no final asset or the completed file, not a partial encode. The unused-name check assumes a single writer in a private directory; it is not concurrency control. Production workers also need disk quotas, memory and CPU limits, bounded logs, restricted filesystem access, and current decoder patches. Timeouts and one encoding thread do not provide complete isolation.
This example normalizes pixels, not visual meaning. Its square-pixel assumption suits typical generated clips; reject or separately handle anamorphic video, HDR color, unusual rotation, and extreme frame rates. Record the source hash, conversion policy, and validation outcome, and review display geometry before release.
How do you test the conversion without generating another video?
Use synthetic local fixtures to verify encoding and rejection behavior without calling a generation API. A fixture is controlled test input with known properties. Run these commands in a fresh directory containing your script:
ffmpeg -v error -nostdin -n \
-f lavfi -i 'testsrc2=size=320x180:rate=12' \
-t 2 -c:v mpeg4 -an silent.mp4
ffmpeg -v error -nostdin -n \
-f lavfi -i 'testsrc2=size=320x180:rate=12' \
-f lavfi -i 'sine=frequency=440:sample_rate=48000' \
-t 2 -c:v mpeg4 -c:a aac with-audio.mp4
python3 browser_mp4.py silent.mp4 silent-browser.mp4
python3 browser_mp4.py with-audio.mp4 audio-browser.mp4
Check both derivatives with the inspection command. Add rejection tests for a text file, an existing destination, missing video, excessive dimensions, and duration outside policy. Confirm original hashes remain unchanged and temporary files disappear after failures. Local decode success cannot establish real-device playback or prove perceptual quality.
Which delivery settings still need browser testing?
The deployed response still needs correct media labeling, working seek requests, secure URLs, and access controls matching your player. Faststart moves MP4 indexing metadata before media data so playback can begin before the entire download finishes. It is progressive download optimization, not adaptive streaming with multiple bitrate segments.
A byte-range request asks for part of a resource. Test actual GET requests with a Range header: a supported partial response uses 206 Partial Content with a correct Content-Range. An Accept-Ranges label alone proves little. Check redirects, expiring signed URLs, caches, and subsequent seeks through the actual delivery service.
HTTPS encrypts delivery and avoids mixed-content failures on secure pages. CORS, Cross-Origin Resource Sharing, governs script access to resources across origins. Plain cross-origin video embedding does not always require CORS permission, but credentialed loading, JavaScript fetching, and canvas access introduce different requirements. Test your chosen mode; do not add wildcard access indiscriminately.
On real Safari, Chromium, and Firefox devices you support, test start, seek, pause/resume, audible user-initiated playback, and a muted inline autoplay case. Device decoder limits, network conditions, authentication, and browser policy remain outside local FFmpeg validation. Before distributing assets or shipping encoders, review source-content rights and applicable software and codec licensing obligations.
What else should developers know about browser playback?
Treat these questions as separate checks rather than assuming every playback issue needs transcoding.
Does changing WebM to an MP4 filename convert the video?
No. Renaming changes neither the container structure nor the encoded streams. Inspect the bytes and create a genuine derivative when required.
Should every generated video be transcoded?
No. Retain a validated original when it already meets your tested delivery profile. Unnecessary re-encoding consumes compute and can introduce visual loss.
Does faststart provide adaptive streaming?
No. It reorganizes one MP4 file. Adaptive streaming requires a separately designed packaging and player workflow.
Does AAC encoding add sound to a silent generation?
No. The optional mapping encodes an existing track; it creates no audio when none exists. Adding licensed sound is a separate editorial operation.