Relaying an HLS audio stream as one seekable file
How Melodius turns an HLS playlist into a single byte range every player can seek: parse the playlist, measure each segment, map range requests onto segments, and refuse what cannot be joined.
Some audio sources in Melodius arrive as HLS: a playlist pointing at many small segments. Browsers, the desktop app and Android all play a plain file and seek in it with range requests, but their HLS support differs. So the relay presents an HLS stream as one file.
Why not just play HLS?
Every player in the family already knows how to play a URL with a length and seek by byte range. Making HLS look like that means one playback path everywhere: the same relay, the same tokens, the same seek behaviour, the same rate limits.
Which streams can be joined
Concatenating segments only works for formats whose segments are valid when placed back to back: MP3, AAC and fragmented MP4 (an init section followed by its fragments). MPEG-TS segments and encrypted segments do not join into a file a player accepts, so those streams are refused up front with a clear error rather than producing audio that fails halfway through.
Building a plan
- Fetch the playlist, at most 1 MB, and require it to start with
#EXTM3U. Master playlists are followed to a media playlist. - Collect the init section and segments, including
EXT-X-BYTERANGEsub-ranges of a larger file. A byte range without an offset continues where the previous one in that URL ended. - Measure every part. A byte-ranged part already knows its length; a whole-file part is measured with a
Range: bytes=0-0request and the total fromContent-Range. Six run at a time. - Store the plan: the parts in order with their URLs, offsets and lengths, the total size and the content type.
interface HlsPlan {
parts: { url: string; offset: number | null; length: number }[];
size: number;
contentType: string; // e.g. audio/mpeg, audio/mp4
}Serving a range
With the plan, the relay can answer Range: bytes=from-to for the virtual file. It walks the parts, finds the ones that overlap the requested range, and turns each into an upstream request: the whole URL when the part is used entirely, or a precise byte range inside it otherwise. Responses are streamed back to back, and a part that does not answer with the expected status aborts the response instead of sending a corrupt file.
Guard rails
- Only hosts on an allowlist are ever fetched, so a crafted playlist cannot make the relay request arbitrary URLs.
- Playlists have a size cap and must contain at least one segment.
- Every upstream fetch shares the request's abort signal, so a listener skipping the song cancels the work immediately.
It is a small piece of the playback path described in making a track start fast.
