Problem: I'm serving medium size videos (approximately 20Mb each) using litestar's static file router from litestar.static_files import create_static_files_router, and I need to play these videos on the frontend. However, browsers require specific headers like content-length, content-range, accept-ranges, and content-encoding etc for seeking functionality.
Current stupid workaround:
I just add header, but it doesn't truly solve the seeking problem, and eats bandwidth like crazy.
class VideoHeaderMiddleware(AbstractMiddleware):
"""
Check if any header is Content-Type and starts with 'video/'
If true, add 'Accept-Ranges: bytes' header
"""
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
async def modified_send(message):
if message["type"] == "http.response.start":
headers = message.get("headers", [])
# Quick check for video content type
if any(k.lower() == b'content-type' and v.lower().startswith(b'video/') for k, v in headers):
# Append Accept-Ranges header
message["headers"] = [*headers, (b'Accept-Ranges', b'bytes')]
await send(message)
await self.app(scope, receive, modified_send)
create_static_files_router(
middleware=[jwt_cookie_auth.middleware],
path="/static",
directories=[
# ...
],
send_as_attachment=False,
middleware=[VideoHeaderMiddleware]
),
The problem is that this results in multiple redundant requests (duplicate requests each 20Mb ). So, it is not truly streaming response with proper chunk sizes but at least seeking is working
Anyone else had a similar problem? Any ideas?