AI video API HTTP Range: Python Delivery Tutorial
Your generated MP4 downloads successfully, but dragging the browser timeline triggers another full download. AI video API HTTP Range support addresses this delivery problem by returning selected file bytes instead of regenerating a clip. This tutorial builds an application-owned delivery handler for an already stored GenRelay output; it does not describe an undocumented GenRelay endpoint or promise behavior from an upstream output URL.
Start with the GenRelay video API for generation, then make playback delivery a separate application responsibility. The runnable Python standard-library examples below implement one byte range per GET request, explicit response planning, authentication, and bounded reads.
What does HTTP Range change in a video integration?
HTTP Range changes which bytes a client receives, not the generated video's duration or the model's generation parameters. A byte range is an inclusive interval in a selected HTTP representation: the exact sequence of bytes being delivered. For example, bytes=100-199 requests 100 bytes, not frames 100 through 199 or seconds 100 through 199.
The browser maps playback positions to media offsets using the file's container metadata. Your server merely returns byte intervals; it does not need to interpret timestamps. A response to a range covering the complete representation can still be 206 because the server honored a valid range request.
Generation and delivery also have different cost boundaries. Omni Flash costs $0.10/generation at 720P and $0.15/generation at 1080P. Repeated downloads of an existing output are not new generations, but storage reads, network transfer, and delivery infrastructure can incur delivery costs. Never submit another generation job just because a player requests another interval.
How should you prepare an output before serving ranges?
Authenticate the requester, authorize access to the asset, and select an immutable, validated MP4 before calculating or revealing file metadata. Authentication establishes identity; authorization decides whether that identity can read this particular output. A hidden URL alone is not that decision.
In a production application, map an opaque asset identifier to a trusted storage object only after permission checks. Do not accept arbitrary filesystem paths or fetch an arbitrary client-supplied URL. Complete the generation job and ingestion process before marking an asset ready. If you poll generation status, do so in that generation workflow, not inside every playback request.
Validation and delivery solve different problems. Check that the downloaded object is complete and actually contains supported media rather than an HTML error page; see AI video API output validation. The handler below deliberately assumes validation has already happened and does not claim that a .mp4 extension proves validity.
Faststart is an MP4 layout arrangement that places the movie metadata near the beginning of the file. It can improve progressive playback startup, but it neither implements HTTP Range nor repairs invalid media. Perform any faststart remux before hashing and publishing the immutable object because changing container layout changes byte offsets and the entity tag.
How do you plan single-range 200, 206, and 416 responses?
Use 200 for a complete response, 206 for an honored single range, and 416 for a valid but unsatisfiable byte-range request. Content-Range describes the returned interval and total length for 206, or the current total length for 416. Content-Length describes this response's body length, not always the complete asset size.
Save this first snippet as range_plan.py. It is a pure response planner: it examines metadata and request fields without opening files or sending network traffic.
import re
from dataclasses import dataclass
@dataclass(frozen=True)
class Plan:
status: int
start: int
length: int
headers: dict
def plan_response(size, etag, range_header=None, if_range=None):
"""Plan a GET of an immutable, identity-encoded representation."""
if size < 0:
raise ValueError("negative size")
if not re.fullmatch(r'"[0-9a-f]{64}"', etag):
raise ValueError("expected strong SHA-256 ETag")
base = {
"Accept-Ranges": "bytes",
"Content-Type": "video/mp4",
"ETag": etag,
"Cache-Control": "private, no-store, no-transform",
}
def full():
return Plan(200, 0, size, {**base, "Content-Length": str(size)})
def unsatisfied():
return Plan(416, 0, 0, {
**base, "Content-Length": "0",
"Content-Range": f"bytes */{size}",
})
if range_header is None:
return full()
# This application supports strong ETags, not date validators.
if if_range is not None and if_range.strip() != etag:
return full()
value = range_header.strip()
# Ignore unsupported, oversized, malformed, or multi-range fields.
if len(value) > 256 or "," in value:
return full()
match = re.fullmatch(r"bytes=([0-9]*)-([0-9]*)", value, re.I)
if not match or not any(match.groups()):
return full()
first, last = match.groups()
if first:
start = int(first)
end = int(last) if last else size - 1
if last and end < start:
return full() # Invalid syntax/ordering, not a valid range.
if start >= size:
return unsatisfied()
end = min(end, size - 1)
else:
suffix = int(last)
if suffix == 0 or size == 0:
return unsatisfied()
start, end = max(0, size - suffix), size - 1
length = end - start + 1
return Plan(206, start, length, {
**base, "Content-Length": str(length),
"Content-Range": f"bytes {start}-{end}/{size}",
})
For a ten-byte asset, bytes=2-4 produces Content-Range: bytes 2-4/10 and a three-byte body. An open-ended range such as bytes=7- ends at the last byte. A suffix range such as bytes=-3 selects the final three bytes; a suffix larger than the object selects the whole object. Overshooting an explicit end is clamped to the existing final byte.
An empty file has a valid zero-length 200 response when no range is applied. A syntactically valid range selecting bytes from that empty representation receives 416 with Content-Range: bytes */0. A zero-length suffix is also unsatisfiable. Reversed endpoints are invalid rather than a useful interval, so this application's documented policy ignores them.
Multipart ranges request multiple intervals, such as bytes=0-1,8-9. This implementation does not construct a multipart response: it ignores the entire Range field and returns the full representation with 200, without Content-Range. Unsupported units, malformed fields, and oversized fields follow the same policy. Ignoring Range is permitted, but this fallback can transfer a large asset; apply request limits rather than assuming every request saves bandwidth.
How should If-Range and ETag control resumed downloads?
Honor a range only when its supplied If-Range validator matches the current representation under the supported comparison rules. An ETag, or entity tag, identifies a specific representation; this example uses a quoted SHA-256 content digest as a strong ETag. Strong comparison requires the complete tag to match and excludes weak tags beginning with W/.
If-Range asks the server to send the requested interval when the validator matches, otherwise send the complete current representation. A mismatch therefore produces 200, not 416 or 304, even if the requested offset would be out of bounds. This protects clients from appending bytes from a changed object to an older partial download.
HTTP also defines date-based If-Range evaluation, but this example intentionally supports strong ETags only. Date validators, weak tags, and malformed values all fall back to a complete 200 response. It does not emit Last-Modified or pretend to compare dates. Applications supporting dates must evaluate them against reliable representation modification metadata and the applicable strong-validator requirements.
How do you stream only the planned bytes in Python?
Seek to the planned offset and send at most the planned length using fixed-size reads. Save this second snippet as serve_video.py beside the planner. Its /video path belongs solely to this local demonstration, not to GenRelay. The single configured bearer token grants access to the single configured file; replace that mapping with your application's identity and asset authorization.
import hashlib
import hmac
import os
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from range_plan import plan_response
def make_handler(path, token):
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
supplied = self.headers.get("Authorization", "").encode("utf-8")
expected = ("Bearer " + token).encode("utf-8")
if not hmac.compare_digest(supplied, expected):
self.send_error(401)
return
if self.path != "/video":
self.send_error(404)
return
# No stat, open, hash, or existence check before authorization.
with path.open("rb") as source:
size = os.fstat(source.fileno()).st_size
digest = hashlib.sha256()
for block in iter(lambda: source.read(64 * 1024), b""):
digest.update(block)
etag = '"' + digest.hexdigest() + '"'
ranges = self.headers.get_all("Range", [])
validators = self.headers.get_all("If-Range", [])
# Duplicate Range fields become an ignored multi-range value.
range_value = ",".join(ranges) if ranges else None
validator = validators[0] if len(validators) == 1 else (
"invalid" if validators else None
)
plan = plan_response(size, etag, range_value, validator)
self.send_response(plan.status)
for name, value in plan.headers.items():
self.send_header(name, value)
self.end_headers()
source.seek(plan.start)
remaining = plan.length
try:
while remaining:
block = source.read(min(64 * 1024, remaining))
if not block:
raise OSError("representation changed during read")
self.wfile.write(block)
remaining -= len(block)
except (BrokenPipeError, ConnectionResetError):
return
def log_message(self, *args):
pass
return Handler
if __name__ == "__main__":
handler = make_handler(Path(sys.argv[1]), os.environ["VIDEO_TOKEN"])
ThreadingHTTPServer(("127.0.0.1", 8000), handler).serve_forever()
Run the local demonstration with an already validated, immutable asset:
export VIDEO_TOKEN='local-test-token'
python3 serve_video.py /absolute/path/to/validated.mp4
From another terminal, inspect headers and save the selected bytes:
curl -i -H 'Authorization: Bearer local-test-token' \
-H 'Range: bytes=0-1023' http://127.0.0.1:8000/video
The server omits Content-Encoding and sends the stored bytes unchanged: this is the identity representation. Disable automatic compression and media transformation on the corresponding reverse-proxy route. Byte offsets, body lengths, and validators must all refer to the same representation; compressing a body after planning ranges breaks that agreement.
The example hashes the opened file on each authorized request to keep the demonstration self-contained. For production, compute the digest once during validated ingestion and store it with immutable object metadata. Never modify the file in place while serving it. Hashing and streaming one descriptor reduces pathname replacement races, but it does not prevent another process from mutating that descriptor's underlying file.
Python's demonstration HTTP server is not a production edge. Deploy behind TLS, add connection and read/write timeouts, cap concurrent streams, and rate-limit per identity. A 64 KiB read bound limits each buffer, not total concurrency or response size. On a truncated object or failed connection, terminate the response; never pad missing bytes or start generating replacement content.
What should you test before putting delivery behind a CDN?
Test status codes, headers, exact body bytes, authorization failures, and representation stability before introducing a content delivery network. A CDN is a distributed caching layer that can change how requests reach your origin. It may cache partial responses, combine ranges, transform content, or remove request headers depending on configuration.
Keep private video delivery uncached until you have verified its authorization and cache-key design. The example sends private, no-store, no-transform; do not configure a shared cache to ignore that policy. If you later introduce signed access and caching, ensure authorization occurs before cached content is released and that users cannot receive another account's objects. Confirm Range and If-Range reach the component responsible for evaluation.
Use this acceptance checklist with a known fixture:
- Compare a complete 200 body against the original file.
- Check closed, open-ended, suffix, oversized-suffix, and clamped ranges byte-for-byte.
- Check 416 has an empty body and the correct unsatisfied Content-Range.
- Verify matching strong ETags yield 206 while stale, weak, and date validators yield 200 under this policy.
- Verify empty files, malformed fields, and multipart fallback behavior.
- Confirm unauthorized requests reveal neither object size nor ETag, even when the object is absent.
Use synthetic bytes for protocol tests, then a separately validated MP4 for browser testing. A passing byte fixture cannot establish codec compatibility. For the player-facing checks, continue with AI video API browser playback.
What are common AI video API HTTP Range questions?
The common questions concern generation boundaries, response semantics, media layout, and browser authentication.
Does every seek create a new generation?
No. Seeking requests bytes from an existing asset. Keep generation submission separate from the delivery route so playback retries cannot create jobs.
Should a partial response include the full file's Content-Length?
No. A 206 response uses the interval's length as Content-Length and puts the complete representation length after the slash in Content-Range. A full 200 response omits Content-Range.
Does faststart eliminate the need for Range?
No. Faststart moves MP4 metadata for earlier discovery; Range supports selective byte delivery. A validated file can benefit from both, and neither establishes browser codec support.
Can a browser video element use this bearer-token demo directly?
Not by setting an Authorization attribute on the video element. Use an application delivery design compatible with browser authentication, such as an authorized same-origin cookie route or carefully scoped signed access. Cross-origin delivery also requires appropriate cross-origin resource sharing configuration; keep long-lived secrets out of media URLs.