DEV Community

Mason K
Mason K

Posted on

Fix hls.js buffering at 2x playback speed with a rate-aware level cap

TL;DR

At 2x, a player needs twice the throughput, but hls.js 1.7.4 compares bandwidth to bitrate without the playback rate. We'll reproduce the stalls on a throttled local server, then fix them with a ~12-line autoLevelCapping helper. Result on a 4 Mbps link: 3 stalls (3.2 s) and 18 switches per minute became one sub-50 ms blip and 3 switches, at a steady 540p.

The speed menu is the player feature nobody load-tests. Let's build a tiny lab that can: an FFmpeg ladder, a Node server with a bandwidth cap, a page running hls.js, and a Playwright script that plays at 1x or 2x and logs what the ABR did.

Versions used: FFmpeg 6.1.1, Node 22.23.5, hls.js 1.7.4, Playwright 1.63.0 (Chromium 158).

1. Find the line 🔍

In hls.js 1.7.4, src/controller/abr-controller.ts, findBestLevel() boils down to:

// hls.js 1.7.4, abr-controller.ts (trimmed)
adjustedbw = upSwitch ? bwUpFactor * currentBw : bwFactor * currentBw;
const canSwitchWithinTolerance = adjustedbw >= bitrate && /* error + fetch-time checks */;
⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน ⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน

No playbackRate. The rate only appears in getStarvationDelay() (buffer length divided by rate) and in the emergency abandon rules. So hls.js notices speed once the buffer starts draining, not when it picks a rendition.

Defaults, from src/config.ts:

option default
abrBandWidthFactor 0.95
abrBandWidthUpFactor 0.7
maxBufferLength 30
capLevelToPlayerSize false

💡 Tip: the comment above the comparison still says "consider only 80% of the available bandwidth". The default is 0.95. Trust the config file.

2. Build a four-rung ladder 🎥

ffmpeg -f lavfi -i "testsrc2=size=1920x1080:rate=30,noise=alls=12:allf=t" \
  -f lavfi -i "sine=frequency=440:sample_rate=48000" -t 150 \
  -filter_complex "[0:v]split=4[a][b][c][d];[a]scale=640:360[v0];[b]scale=960:540[v1];[c]scale=1280:720[v2];[d]null[v3]" \
  -map "[v0]" -map "[v1]" -map "[v2]" -map "[v3]" -map 1:a \
  -c:v libx264 -preset veryfast -g 120 -keyint_min 120 -sc_threshold 0 \
  -b:v:0 600k  -maxrate:v:0 600k  -bufsize:v:0 1200k \
  -b:v:1 1200k -maxrate:v:1 1200k -bufsize:v:1 2400k \
  -b:v:2 2000k -maxrate:v:2 2000k -bufsize:v:2 4000k \
  -b:v:3 3500k -maxrate:v:3 3500k -bufsize:v:3 7000k \
  -c:a aac -b:a 96k -ac 2 \
  -f hls -hls_time 4 -hls_playlist_type vod -hls_segment_filename "hls/v%v/seg%03d.ts" \
  -master_pl_name master.m3u8 \
  -var_stream_map "v:0,agroup:aud v:1,agroup:aud v:2,agroup:aud v:3,agroup:aud a:0,agroup:aud,default:yes" \
  "hls/v%v/index.m3u8"
⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน ⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน

The noise filter keeps x264 from compressing the test pattern into nothing, so the renditions actually hit their bitrates. FFmpeg wrote these:

$ grep BANDWIDTH hls/master.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=765600,RESOLUTION=640x360,...
#EXT-X-STREAM-INF:BANDWIDTH=1425600,RESOLUTION=960x540,...
#EXT-X-STREAM-INF:BANDWIDTH=2305600,RESOLUTION=1280x720,...
#EXT-X-STREAM-INF:BANDWIDTH=3955600,RESOLUTION=1920x1080,...
⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน ⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน

On a 4 Mbps link, 720p (2.3 Mbps) is fine at 1x and needs ~4.6 Mbps at 2x. That's the trap.

3. A server with a bandwidth cap 🛠️

One shared token bucket, round-robin across in-flight segment responses:

// server.js
const http = require('http'), fs = require('fs'), path = require('path');
const BPS = Number(process.env.BPS || 4_000_000);
const TICK = 50; // ms
let tokens = 0; const queue = [];

setInterval(() => {
  tokens = Math.min(tokens + (BPS / 8) * (TICK / 1000), BPS / 8 / 4);
  while (queue.length && tokens > 0) {
    const job = queue[0];
    const n = Math.min(job.buf.length - job.off, tokens, 64 * 1024);
    job.res.write(job.buf.subarray(job.off, job.off + n));
    job.off += n; tokens -= n;
    if (job.off >= job.buf.length) { job.res.end(); queue.shift(); }
    else queue.push(queue.shift());
  }
}, TICK);

const types = { '.m3u8': 'application/vnd.apple.mpegurl', '.ts': 'video/mp2t', '.js': 'text/javascript', '.html': 'text/html' };
http.createServer((req, res) => {
  const p = path.join(__dirname, decodeURIComponent(req.url.split('?')[0]));
  fs.readFile(p, (err, buf) => {
    if (err) { res.writeHead(404); return res.end(); }
    res.writeHead(200, { 'Content-Type': types[path.extname(p)] || 'application/octet-stream', 'Content-Length': buf.length });
    if (p.endsWith('.ts')) queue.push({ res, buf, off: 0 }); else res.end(buf);
  });
}).listen(8080, () => console.log(`serving at ${BPS / 1e6} Mbps cap`));
⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน ⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน

Copy node_modules/hls.js/dist/hls.min.js next to it and start it:

$ BPS=4000000 node server.js
serving at 4 Mbps cap
⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน ⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน

4. An instrumented player page

?rate=2 sets the speed once playback starts; ?fix=2 turns on the cap we'll write in step 6.

<!-- page.html -->
<video id="v" muted playsinline></video>
<script src="/hls.min.js"></script>
<script src="/rate-cap.js"></script>
<script>
const q = new URLSearchParams(location.search);
const rate = Number(q.get('rate') || 1), fix = q.get('fix') || '0';
const v = document.getElementById('v');
const log = window.__log = { switches: [], stalls: 0, stallMs: 0, frags: [] };
const hls = window.hls = new Hls({ maxBufferLength: 30 });

hls.on(Hls.Events.LEVEL_SWITCHED, (_, d) => log.switches.push(d.level));
hls.on(Hls.Events.FRAG_LOADED, (_, d) => { if (d.frag.type === 'main') log.frags.push(d.frag.level); });

let stallStart = 0;
v.addEventListener('waiting', () => { if (v.currentTime > 0.5) { log.stalls++; stallStart = performance.now(); } });
v.addEventListener('playing', () => { if (stallStart) { log.stallMs += performance.now() - stallStart; stallStart = 0; } });

if (fix === '1') scaleAbrForRate(hls, v);   // step 6, attempt 1
if (fix === '2') attachRateCap(hls, v);     // step 6, the fix

hls.loadSource('/hls/master.m3u8');
hls.attachMedia(v);
hls.on(Hls.Events.MANIFEST_PARSED, () => v.play());
v.addEventListener('playing', () => { v.playbackRate = rate; }, { once: true });
</script>
⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน ⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน

5. Measure it 📊

// run.js  usage: node run.js <rate> <fix> <seconds>
const { chromium } = require('playwright');
(async () => {
  const [rate, fix, secs] = [process.argv[2] || '1', process.argv[3] || '0', Number(process.argv[4] || 60)];
  const browser = await chromium.launch();
  const page = await browser.newPage();
  await page.goto(`http://localhost:8080/page.html?rate=${rate}&fix=${fix}`);
  await page.waitForTimeout(secs * 1000);
  const log = await page.evaluate(() => window.__log);
  const pos = await page.evaluate(() => document.getElementById('v').currentTime);
  const fragsByLevel = {}; log.frags.forEach(l => (fragsByLevel[l] = (fragsByLevel[l] || 0) + 1));
  console.log(JSON.stringify({ rate, fix, mediaSecondsPlayed: +pos.toFixed(1), stalls: log.stalls,
    stallSeconds: +(log.stallMs / 1000).toFixed(1), fragsByLevel, switches: log.switches.length }));
  await browser.close();
})();
⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน ⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน

Baseline at 1x, then 2x, no fix:

$ node run.js 1 0 40
{"rate":"1","fix":"0","mediaSecondsPlayed":39.2,"stalls":0,"stallSeconds":0,"fragsByLevel":{"0":1,"2":17},"switches":2}

$ node run.js 2 0 60
{"rate":"2","fix":"0","mediaSecondsPlayed":112.2,"stalls":3,"stallSeconds":3.2,"fragsByLevel":{"0":5,"1":14,"2":17},"switches":18}
⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน ⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน

At 1x it settles on level 2 (720p) and stays there. At 2x it ping-pongs across three renditions and stalls three times. A second 2x run produced exactly the same numbers. Sampling hls.bandwidthEstimate every two seconds showed ~3.9 Mbps throughout, so the estimate is fine; the comparison just ignores speed.

6. The fix: cap the ladder by bitrate × rate

❌ First attempt: scale the ABR factors

// rate-cap.js (attempt 1)
function scaleAbrForRate(hls, video) {
  const base = { down: hls.config.abrBandWidthFactor, up: hls.config.abrBandWidthUpFactor };
  video.addEventListener('ratechange', () => {
    const r = Math.max(1, Math.abs(video.playbackRate) || 1);
    hls.config.abrBandWidthFactor = base.down / r;
    hls.config.abrBandWidthUpFactor = base.up / r;
  });
}
⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน ⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน
$ node run.js 2 1 60
{"rate":"2","fix":"1","mediaSecondsPlayed":116.9,"stalls":0,"stallSeconds":0,"fragsByLevel":{"0":38},"switches":1}
⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน ⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน

No stalls, but all 38 fragments at 360p. The up factor becomes 0.35, and 0.35 × 3.9 Mbps ≈ 1.36 Mbps is just below 540p's 1.43 Mbps, even though 540p at 2x (≈2.9 Mbps) fits the link. Overcorrected.

✅ What works: autoLevelCapping

// rate-cap.js (the fix)
function attachRateCap(hls, video, headroom = 0.9) {
  function capForRate() {
    const r = Math.max(1, Math.abs(video.playbackRate) || 1);
    if (r === 1) { hls.autoLevelCapping = -1; return; }   // uncapped at 1x
    const budget = hls.bandwidthEstimate * headroom;
    let cap = 0;
    hls.levels.forEach((l, i) => { if (l.bitrate * r <= budget) cap = i; });
    if (hls.autoLevelCapping !== cap) hls.autoLevelCapping = cap;
  }
  video.addEventListener('ratechange', capForRate);
  hls.on(Hls.Events.FRAG_LOADED, capForRate);            // follow the estimate
  return () => {
    video.removeEventListener('ratechange', capForRate);
    hls.off(Hls.Events.FRAG_LOADED, capForRate);
  };
}
⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน ⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน
$ node run.js 2 2 60
{"rate":"2","fix":"2","mediaSecondsPlayed":118.4,"stalls":1,"stallSeconds":0,"fragsByLevel":{"0":1,"1":36,"2":1},"switches":3}

$ node run.js 1 2 40
{"rate":"1","fix":"2","mediaSecondsPlayed":39.3,"stalls":0,"stallSeconds":0,"fragsByLevel":{"0":1,"2":17},"switches":2}
⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน ⭐ Must Read: masonwritescode/fix hlsjs buffering at x playback speed with a rate aware level cap jp - ประเด็นร้อน

36 of 38 fragments at 540p. The "1 stall" is a waiting event under 50 ms (it rounds to 0.0 s), right as the rate flips while a 720p fragment is already in flight. A repeat run gave the same result, and an earlier version of the harness gave 0 stalls. At 1x the cap turns itself off and behaves exactly like the baseline.

Results

4 Mbps link stalls stall time level switches main rendition
1x, stock 0 0 s 2 720p
2x, stock 3 3.2 s 18 mixed 360/540/720
2x, scaled factors 0 0 s 1 360p
2x, rate cap 1 blip (<50 ms) 0 s 3 540p

⚠️ Note: one steady synthetic link, headless Chromium, hls.js only. Safari's native HLS doesn't run this code. I didn't test 1.5x, but the same math applies when bitrate × 1.5 crosses your bandwidth.

What's next

  • Segment your QoE data by playbackRate. If you only track rebuffer ratio overall, the 2x cohort hides inside the average.
  • If you use capLevelToPlayerSize, know that its controller also writes hls.autoLevelCapping (see cap-level-controller.ts), so the two will overwrite each other. Turn it off and compute both caps yourself, taking the minimum.
  • Try the same lab against Shaka Player or dash.js. The server and Playwright script are player-agnostic; only page.html changes.

Drop your numbers in the comments if your player behaves differently. #webdev #javascript

Top comments (0)