hlsv2 Documentation
hlsv2.31 is a patched build of hls.js with the WSP-HLS (Whole Segment Preload) extension built in. It adds hls.wsphls() a method that prefetches every HLS segment into memory in the background, then installs a cache-first loader so seeks are instant with no buffering spinner.
wsphls(), done.Hls.prototype and does not change any existing behaviour.
Purpose & Use Cases
WSP-HLS is designed for applications where seek latency matters and CDN egress cost is a concern. Standard hls.js buffers forward it cannot predict where a user will seek. WSP-HLS solves this by fetching the entire video into memory up front.
Cost Optimization
WSP-HLS is a CDN egress cost control mechanism. Standard hls.js re-fetches a segment from your CDN every time a seek lands outside the 30-second forward buffer. WSP-HLS prefetches every segment once into memory after that, every seek is served from window.__hlsSegmentCache at zero network cost.
The key insight: each segment is fetched exactly once, regardless of how many times the user seeks to it. This means your CDN sees N segment requests total per viewer one per segment instead of N × seeks.
How wsphls() eliminates seek-driven CDN cost
Here is the full pattern. After MANIFEST_PARSED fires, call wsphls(). It prefetches every segment in the background, installs a CacheFirstLoader, and resolves the Promise when complete. All subsequent seeks hit the in-memory cache zero network requests.
<script src="https://cdn.jsdelivr.net/gh/Tsukinatsune/CDN-Javascript-project@main/hlsv2.31.js"></script>
<script>
var video = document.getElementById('video');
var src = 'https://example.com/stream/playlist.m3u8';
if (Hls.isSupported()) {
var hls = new Hls();
hls.loadSource(src);
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED, function() {
video.play();
// wsphls() fetches every segment into window.__hlsSegmentCache.
// Once resolved, CacheFirstLoader is installed as hls.config.fLoader.
// Every subsequent seek is served from memory CDN is never hit again.
hls.wsphls({
concurrency: 6, // parallel fetch workers
onProgress: function(p) {
// p = { prefetched, total, failed }
// Drive a progress bar: p.prefetched / p.total
console.log(p.prefetched + '/' + p.total + ' segments cached');
}
}).then(function(result) {
// result.prefetched segments now in cache
// result.total total segments in level
// result.failed array of { url, error } for any failures
console.log('All segments cached. Seeks are now instant.', result);
// From this point, window.__hlsSegmentCache holds every segment.
// Inspect: window.__hlsSegmentCache.size
// Clear to free RAM: window.__hlsSegmentCache.clear()
});
});
}
</script>
Adaptive prefetch cap bandwidth cost on long content
For large or high-bitrate streams, prefetching the full video may exceed practical RAM or bandwidth limits. Use endTime to prefetch only the high-seek-risk region and let normal hls.js buffering handle the rest.
hls.on(Hls.Events.MANIFEST_PARSED, function() {
video.play();
// Estimate how large the full video is at the current level
var level = hls.levels[hls.currentLevel >= 0 ? hls.currentLevel : 0];
var durS = (level && level.details) ? level.details.totalduration : 0;
var estMB = level ? (level.bitrate / 8 / 1e6) * durS : 0;
var opts = { concurrency: 6 };
if (estMB > 800) {
// Very large (e.g. 1080p movie) prefetch intro skip zone only (first 5 min)
opts.concurrency = 3;
opts.endTime = 300;
} else if (estMB > 300) {
// Medium (e.g. 720p episode > 30 min) prefetch first 20 min
opts.concurrency = 4;
opts.endTime = 1200;
}
// else: under 300 MB (short clip or low bitrate) prefetch everything
hls.wsphls(opts).then(function(result) {
// CacheFirstLoader is now installed. All seeks within the prefetched
// window are served from window.__hlsSegmentCache no CDN requests.
console.log(
'Prefetch done: ' + result.prefetched + '/' + result.total +
' segments. Failed: ' + result.failed.length
);
});
});
Why it saves money
With standard hls.js, every seek outside the forward buffer fires a CDN request. With wsphls(), each segment is fetched from the CDN exactly once during prefetch. The cache is shared across all Hls instances on the page, so rewatches and quality switches also cost nothing.
CDN Cost Calculator real-world model
This calculator models what actually happens at CDN level: viewers don't all seek equally, standard hls.js has a 30-second forward buffer that absorbs nearby seeks for free, and wsphls() itself generates egress during prefetch. There are real conditions where wsphls() costs more those are shown honestly.
Real-World Scenarios
Standard HLS already handles buffering ahead of playback and reconnects after dropouts. WSP-HLS is useful in a narrower, more specific set of situations where the bottleneck is not the stream itself but the cost and latency of segment requests at unpredictable seek targets.
How to adapt for every situation
| Situation | How to adapt wsphls() |
|---|---|
| Live stream | Call wsphls() after the stream ends and the VOD replay becomes available at that point all segments are fixed and cacheable. During live, let standard HLS run normally. |
| Linear viewer who rarely seeks | Prefetch a short safety window endTime: 300 (5 min). Covers the rare seek without burning bandwidth on content they will play straight through. |
| Content > 2 h at 1080p on mobile | Prefetch in a rolling window: cache the next 20 minutes ahead of the playhead by re-calling wsphls({ startTime, endTime }) on a timer as the user advances. |
| Mid-video connection drop on linear playback | The standard 30–60 s forward buffer already covers brief dropouts. Pair with maxRetry: 5 in wsphls() so any segment that failed during the dropout is retried silently when the connection returns. |
| Very low bitrate content (sub 500 kbps) | Seek latency is already low, so wsphls() is optional. Still worth running with concurrency: 2 to cap the extra bandwidth the cache still eliminates duplicate fetches if the user rewinds. |
Live Demo HLS Playback
Try it live: paste a .m3u8 URL or paste raw M3U8 playlist text directly. Once wsphls() completes prefetch, seeking is instant with no buffering spinner.
.m3u8 URL or pick a preset. Raw M3U8 tab: paste a full playlist directly segment URLs must be absolute. Use the wsphls mode row to test default, level: N, or allLevels before loading. Loading always fully resets the Hls instance and cache.Installation
No build step needed. Load the script from the CDN or host it yourself.
CDN (recommended)
<script src="https://cdn.jsdelivr.net/gh/Tsukinatsune/CDN-Javascript-project@main/hlsv2.31.js"></script>
Self-hosted
Download hlsv2.31.js and serve it from your own origin:
<script src="/js/hlsv2.31.js"></script>
Module / ESM
The file ships a UMD bundle. In a module context use a dynamic import or a bundler alias:
// Bundler (webpack / vite) alias hls.js to hlsv2.31.js in config
import Hls from 'hls.js'; // now resolves to your patched file
// Or: dynamic import after the script tag loads
const Hls = window.Hls;
Quick Start
A minimal working example stream plays normally, then all segments are prefetched in background so seeks become instant.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/gh/Tsukinatsune/CDN-Javascript-project@main/hlsv2.31.js"></script>
</head>
<body>
<video id="video" controls width="800"></video>
<script>
const video = document.getElementById('video');
const src = 'https://example.com/stream/playlist.m3u8';
if (Hls.isSupported()) {
const hls = new Hls();
hls.loadSource(src);
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED, function() {
video.play();
// Start background prefetch returns a Promise
hls.wsphls({ concurrency: 6 }).then(function(result) {
console.log('Prefetch done:', result);
// result = { prefetched: N, total: N, failed: [] }
});
});
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
// Safari native HLS wsphls() not available
video.src = src;
}
</script>
</body>
</html>
wsphls() Call Signatures
Three ways to call hls.wsphls() giving precise control over which quality level is prefetched. The default (no arguments) still prefetches the current level as before.
1 · Default prefetch (current level)
Call with no arguments. Prefetches whichever level hls.js is currently playing. Behavior is identical to the original API.
// Prefetch the current (ABR-selected) quality level
hls.wsphls();
2 · Prefetch a specific quality level
Pass { level: N } to lock prefetch to an exact quality index. 0 is always the lowest bitrate; higher indices correspond to higher qualities. Useful for "warm up 360p only" patterns where bandwidth is limited, or for pre-loading a known quality before the user switches.
// Force a specific quality index (0 = lowest)
hls.wsphls(); // default uses current ABR level
// Prefetch level 2 only (e.g. 380p in your playlist)
hls.wsphls({ level: 2 });
// Prefetch 1080p (index 4, if your playlist has 5 levels)
hls.wsphls({ level: 4 });
hls.levels.length and inspect hls.levels[N].height to confirm which resolution maps to which index before hardcoding a level number.3 · Prefetch all quality levels at once
Pass { allLevels: true } to prefetch every rendition in the master playlist simultaneously. Segment workers are shared across all levels, so the concurrency option still applies globally. This is the highest memory usage mode best for short videos or when storage is not a concern.
// Prefetch every quality level in the master playlist
hls.wsphls({ allLevels: true }).then(function(result) {
console.log('All levels done:', result);
});
At a glance
| Call | Levels prefetched | Memory cost | When to use |
|---|---|---|---|
hls.wsphls() |
Current ABR level | Low | Default. Good for most use cases one quality, smallest RAM footprint. |
hls.wsphls({ level: N }) |
Exactly level N | Low | Pin to a known quality (e.g. warm up 360p before user requests HD). |
hls.wsphls({ allLevels: true }) |
All levels | High | Short clips, review tools, or offline-capable players where all bitrates are needed. |
Quality Settings
Quality level selection directly controls prefetch size and CDN egress. Inspect hls.levels before deciding which level to cache. The array is sorted lowest → highest bitrate (index 0 = lowest quality).
// After MANIFEST_PARSED fires, inspect what levels exist
hls.on(Hls.Events.MANIFEST_PARSED, function() {
hls.levels.forEach(function(lvl, i) {
console.log(i, lvl.height + 'p', Math.round(lvl.bitrate / 1000) + 'kbps');
// → 0 360p 400kbps
// → 1 720p 1000kbps
// → 2 1080p 2500kbps
});
// Pick lowest bitrate to minimise prefetch data cost
hls.wsphls({ level: 0 });
// Or pick the level closest to a target resolution
var targetHeight = 720;
var idx = hls.levels.reduce(function(best, lvl, i) {
return Math.abs(lvl.height - targetHeight) < Math.abs(hls.levels[best].height - targetHeight) ? i : best;
}, 0);
hls.wsphls({ level: idx });
});
Quality vs. memory trade-off
Higher quality means larger prefetch. The table below shows approximate in-memory size for a 24-minute episode at common quality levels. Use hls.levels[N].bitrate and your stream's duration to compute it exactly.
| Quality | Typical bitrate | 24 min episode (est.) | Prefetch recommendation |
|---|---|---|---|
| 360p | 400 kbps | ~72 MB | Always safe prefetch entire video on any device. |
| 480p | 700 kbps | ~126 MB | Safe on desktop/tablet. Add memory check on mobile. |
| 720p | 1 000 kbps | ~180 MB | Fine for episodes. Skip on mobile with < 1 GB RAM available. |
| 1080p | 2 500 kbps | ~450 MB | Use endTime to cap to first 20 min on constrained devices. |
| 4K / 2160p | 8 000 kbps | ~1.4 GB | Full prefetch only on desktop/TV. Always use endTime on mobile. |
hls.on(Hls.Events.MANIFEST_PARSED, function() {
var level = hls.levels[hls.currentLevel >= 0 ? hls.currentLevel : 0];
var durS = level.details ? level.details.totalduration : 0;
var estMB = (level.bitrate / 8 / 1e6) * durS;
var isMobile = /Mobi|Android/i.test(navigator.userAgent);
var opts = { concurrency: isMobile ? 3 : 6 };
if (estMB > 1000 || (isMobile && estMB > 400)) {
// 4K or large file on mobile prefetch intro-skip zone only
opts.endTime = 300;
} else if (estMB > 400) {
// 1080p prefetch first 20 min to cover likely seek range
opts.endTime = 1200;
}
// 720p and below: prefetch everything fits comfortably in RAM
hls.wsphls(opts);
video.play();
});
default, level: N, and allLevels on any stream. Use the quality preset buttons in the cost calculator above to see how each quality tier affects CDN egress before choosing your strategy.hls.wsphls( options )
Prefetches all HLS segments for the current level into window.__hlsSegmentCache. Once the Promise resolves, a CacheFirstLoader is installed and buffer limits are set to effectively infinite the browser never enters a "waiting" state on seek because all data is already in the SourceBuffer.
If the manifest has not yet been loaded when wsphls() is called, it automatically waits for the LEVEL_LOADED event before starting.
alias hls.prefetchAllSegments() is identical.
What happens after the Promise resolves
hls.config.fLoader. All future fragment requests are served from __hlsSegmentCache at zero network cost. Falls back to real network only on a cache miss.maxBufferLength, maxMaxBufferLength, and backBufferLength are all set to 86400 (24 h). hls.js will eagerly append the entire video content into the SourceBuffer.
hls.prefetchAllSegments( options )
Exact alias of hls.wsphls(). Accepts the same options and returns the same Promise. Use whichever name you prefer.
hls.prefetchAllSegments({ concurrency: 4 }).then(function(r) {
console.log(r.prefetched + ' / ' + r.total + ' segments cached');
});
hls.help()
Logs the tutorial URL to the console and returns it as a string.
hls.help();
// logs: "wsphls help: see tutorial at https://wsphls-tutorial-2.pages.dev/"
// returns: "https://wsphls-tutorial-2.pages.dev/"
wsphls() Options
All options are optional. Pass as a plain object.
| Option | Type | Default | Description |
|---|---|---|---|
| concurrency | number | 6 | Number of parallel fetch workers. Higher values speed up prefetch but increase bandwidth burst. Falls back to hls.config.prefetchConcurrency if set. |
| includeAudio | boolean | false | Also prefetch segments from alternate audio tracks. Falls back to hls.config.prefetchIncludeAudio. |
| includeSubtitles | boolean | false | Also prefetch subtitle track segments. Falls back to hls.config.prefetchIncludeSubtitles. |
| allLevels | boolean | false | Prefetch segments from every quality level. When false, only the current (or first) level is prefetched. |
| level | number | null | Force prefetch of a specific quality level by index (0 = lowest, higher indices = higher qualities). When set, overrides the current ABR level selection. Ignored if allLevels is true. |
| maxRetry | number | 2 | How many times to retry a failed segment fetch before recording it in result.failed. |
| startTime | number | null | Only prefetch segments whose end time is after this value (seconds). Useful for prefetching a clip range. |
| endTime | number | null | Only prefetch segments whose start time is before this value (seconds). |
| onProgress | function | undefined | Called after each segment is fetched with { prefetched, total, failed }. Use to drive a progress bar. |
| onError | function | undefined | Called with (segment, error) when a segment fails after all retries. Does not abort the prefetch. |
Config Options (new Hls({...}))
These can be set in the Hls constructor config object as defaults for wsphls(). Per-call options override these.
| Config Key | Type | Description |
|---|---|---|
| prefetchConcurrency | number | Default concurrency for wsphls(). Overridden by options.concurrency. |
| prefetchIncludeAudio | boolean | Default for includeAudio option. |
| prefetchIncludeSubtitles | boolean | Default for includeSubtitles option. |
const hls = new Hls({
prefetchConcurrency: 8,
prefetchIncludeAudio: true,
prefetchIncludeSubtitles: false,
});
// Now hls.wsphls() defaults to concurrency 8 and includes audio tracks
How It Works
WSP-HLS has two phases: prefetch (background segment download) and serve (cache-first interception via config.loader + config.fLoader). Click any step to explore details.
MANIFEST_PARSED. Accepts optional { concurrency, startTime, endTime, onProgress, maxRetry }.hls.levels[currentLevel].details.fragments. Filters by startTime / endTime if provided. Deduplicates segments by cache key.url + "|" + byteRangeStart + "-" + byteRangeEnd
Uniquely identifies each byte-range sub-resource. Byte-range segments inside the same file get separate keys.
prefetched. No network trip. Move to next segment immediately.Range: bytes=start-end for byte-range segments. Full segments use a plain GET. Retries up to maxRetry times on failure.{ payload: ArrayBuffer, iv?: Uint8Array } into window.__hlsSegmentCache. Calls onProgress({ prefetched, total }) for progress bar rendering.{ prefetched, total, failed[] }. CacheFirstLoader is set as both hls.config.loader and hls.config.fLoader both must be replaced so hls.js picks up the cache loader for every new request. Buffer limits are maximized. hls.startLoad() is called.url + "|" + byteRangeStart + "-" + byteRangeEnd. Looked up in window.__hlsSegmentCache.ArrayBuffer via setTimeout(0). Zero latency. Restores iv for AES-128 streams. Calls callbacks.onSuccess.DefaultLoader for a normal network fetch. Covers init segments and anything outside the prefetch window.HTMLVideoElement can seek with no buffering spinner.Phase 2 detail cache hit & miss
setTimeout(0) with zero network latency. Restores IV for encrypted streams.DefaultLoader for a normal network fetch. This covers init segments or anything not prefetched.Segment Cache window.__hlsSegmentCache
All cached segments live in a single shared Map at window.__hlsSegmentCache (or self.__hlsSegmentCache in workers). This means:
- Multiple
Hlsinstances on the same page share the cache. - You can inspect the cache directly:
window.__hlsSegmentCache.size - To clear it:
window.__hlsSegmentCache.clear() - Each entry:
Map<cacheKey: string, { payload: ArrayBuffer, iv?: Uint8Array }>
// Inspect cache after prefetch
const cache = window.__hlsSegmentCache;
console.log('Cached segments:', cache.size);
// Estimated memory usage (bytes)
let totalBytes = 0;
cache.forEach(function(v) {
totalBytes += v.payload ? v.payload.byteLength : 0;
});
console.log('~' + (totalBytes / 1024 / 1024).toFixed(1) + ' MB in memory');
// Clear the cache to free memory
window.__hlsSegmentCache.clear();
CacheFirstLoader
Installed automatically after wsphls() resolves as both hls.config.loader and hls.config.fLoader. Implements the full hls.js loader interface.
| Method / Property | Description |
|---|---|
| stats | Read-only property returning the loader stats object. Synced to the inner DefaultLoader on cache miss. |
| load(context, config, callbacks) | Checks the cache. On hit: calls callbacks.onSuccess via setTimeout(0). On miss: delegates to DefaultLoader. |
| abort() | Aborts the inner DefaultLoader if a network request is in flight. |
| destroy() | Destroys and nulls the inner DefaultLoader. |
wsphls() automatically. Installation is guarded by hls.__wsphlsCacheInstalled so it only runs once per instance, regardless of what config.fLoader is set to. Both hls.config.loader and hls.config.fLoader are replaced this is required because hls.js reads config.loader when constructing new loader instances at request time; setting only fLoader has no effect after the instance is already running.
Example: Basic Embed
Minimal full-page video player with prefetch.
<video id="v" controls style="width:100%"></video>
<script src="https://cdn.jsdelivr.net/gh/Tsukinatsune/CDN-Javascript-project@main/hlsv2.31.js"></script>
<script>
var video = document.getElementById('v');
if (Hls.isSupported()) {
var hls = new Hls();
hls.loadSource('https://example.com/video.m3u8');
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED, function() {
hls.wsphls(); // fire and forget
video.play();
});
}
</script>
Example: Progress Bar
Show prefetch progress to the user with the onProgress callback.
<video id="video" controls></video>
<div id="bar-wrap" style="background:#eee;height:4px;border-radius:2px">
<div id="bar" style="background:#2563eb;height:100%;width:0;transition:width 0.2s"></div>
</div>
<p id="label">Buffering segments…</p>
<script>
var hls = new Hls();
hls.loadSource('https://example.com/video.m3u8');
hls.attachMedia(document.getElementById('video'));
hls.on(Hls.Events.MANIFEST_PARSED, function() {
hls.wsphls({
concurrency: 8,
onProgress: function(p) {
var pct = (p.prefetched / p.total * 100).toFixed(0);
document.getElementById('bar').style.width = pct + '%';
document.getElementById('label').textContent =
pct + '% cached (' + p.failed + ' failed)';
}
}).then(function() {
document.getElementById('label').textContent = ' Fully cached instant seeks enabled';
});
});
</script>
Example: Time Range Prefetch
Only prefetch the first 5 minutes of a long stream (segments 0 – 300 s).
hls.wsphls({
startTime: 0,
endTime: 300, // prefetch first 5 minutes only
concurrency: 6,
onProgress: function(p) {
console.log(p.prefetched + '/' + p.total);
}
}).then(function(r) {
console.log('Clip prefetch done', r);
});
startTime AND its start time is before endTime. Segments that overlap the boundary are included.
Example: Encrypted Streams (AES-128)
No special setup needed. The CacheFirstLoader automatically restores the IV from the cached entry on cache hits, so encrypted streams decrypt correctly after prefetch.
// AES-128 encrypted stream works as-is
var hls = new Hls();
hls.loadSource('https://example.com/encrypted/playlist.m3u8');
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED, function() {
// wsphls() caches segments; IV preserved automatically
hls.wsphls({ concurrency: 4 }).then(function(r) {
console.log('Encrypted stream fully cached', r);
});
video.play();
});
Promise Result Object
The Promise returned by wsphls() resolves with:
{ prefetched: number, total: number, failed: Array<{url, error}> }
| Field | Type | Description |
|---|---|---|
| prefetched | number | Total segments successfully fetched or already in cache. |
| total | number | Total segments in the queue (before dedup). Does not count segments that were already cached before the call. |
| failed | Array | Segments that failed after all retries. Each item: { url: string, error: string }. Empty array on full success. |
hls.wsphls().then(function(result) {
console.log(result.prefetched); // e.g. 120
console.log(result.total); // e.g. 120
console.log(result.failed); // [] or [{ url, error }]
if (result.failed.length > 0) {
console.warn('Some segments failed:', result.failed);
}
});
Key HLS Events
Standard hls.js events most commonly used alongside wsphls().
| Event | When to use with wsphls() |
|---|---|
| MANIFEST_PARSED | Best place to call wsphls() levels are available but no segments fetched yet. |
| LEVEL_LOADED | wsphls() waits for this internally if called before manifest is loaded. |
| FRAG_LOADED | Fires for each segment hls.js loads during normal playback. |
| ERROR | Network or decode errors handle separately from wsphls()'s onError. |
hls.on(Hls.Events.MANIFEST_PARSED, function(event, data) {
console.log('Levels:', data.levels.length);
hls.wsphls();
});
hls.on(Hls.Events.ERROR, function(event, data) {
if (data.fatal) {
console.error('Fatal HLS error:', data.type, data.details);
hls.destroy();
}
});
Browser Support
Check support at runtime with Hls.isSupported(). This build supports Chrome, Edge, Firefox, Safari (desktop & iOS) Hls.isSupported() returns true on iOS with this build, so wsphls() works there too.
Legal & Credits
hlsv2 (WSP-HLS) is released under the MIT License. You are free to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the software, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.
hlsv2 is a patch built on top of hls.js by video-dev and contributors, also released under the Apache 2.0 License.
The WSP-HLS patch adds wsphls(), prefetchAllSegments(), and
help() to Hls.prototype. No existing hls.js behaviour is modified.
This is an unofficial community build. It is not affiliated with or endorsed by the hls.js project or video-dev. Use in production at your own discretion.