Test Adaptive Bitrate With Time Windows, Not Exact Seconds
A check that the player is on 360p at a given second flakes, and it misses the real defect: hls.js fetching its 720p rendition on a 1.2 Mbps link after a dropped segment, then freezing. Shape the network with a token-bucket proxy and assert time windows instead.

A test asserts that 18 seconds after the network drops from 8 to 1.2 Mbps, the viewer is watching the 360p rendition. It passes three runs out of five. Someone moves the instant to 21 seconds and it passes five out of five. In the same five runs, hls.js 1.7.4 with its default configuration requested its 4.46 Mbps rendition three times during the 1.2 Mbps stretch, and in three of them the picture froze for more than five seconds. The exact-second assertion never notices, because the question it asks has nothing to do with the defect.
This is part 4 of an eight-part series on streaming and CTV quality. Part 1 named adaptation as one contract in a session, part 2 checked what a manifest promises, and part 3 measured startup under fixed network profiles. This part tests the player when the network changes mid-session.
testsrc2 and sine sources and is served from http://localhost. Loss is simulated by cutting HTTP responses, not by dropping packets, because packet-level shaping on macOS needs root. The hls.js behaviour described below is read from the 1.7.4 source and changes between releases; re-run the lab when you upgrade.What CDP throttling cannot replay
Part 3 showed that Chrome DevTools Protocol throttling treats latency as a floor and applies packetLoss to WebRTC only. For adaptive bitrate it has three further gaps.
It has no timeline. Network.emulateNetworkConditions sets one condition; a profile means calling it again from a timer in the test process, so the moment of the change depends on that timer, not on the stream. It cannot fail a response halfway: there is no parameter that sends half a segment and closes the connection, which is the loss a player actually sees over HTTP. And it shapes only the Chromium instance the test drives. A smart TV, a set-top box or a phone app cannot be pointed at it.
Its offline switch also changes the player's path. The deprecated command affects navigator state, unlike emulateNetworkConditionsByRule, and hls.js retries a status-0 failure only when navigator.onLine is false. An "offline" test exercises a retry; a connection dropped while the browser thinks it is online does something else, shown below.
A shaper with one bucket for every connection
The shaper is a Node HTTP server. Every response joins one queue, and a timer refills a single token bucket every 5 ms at the rate the profile gives for the current second. Sharing the bucket matters: hls.js can have a segment and a playlist in flight at once, and a per-connection limit would let them add up to more than the link. The profile clock starts at the first multivariant playlist request.
export const PROFILE = [
{ from: 0, mbps: 8.0, abortEvery: 0 },
{ from: 20, mbps: 1.2, abortEvery: 3 }, // every 3rd segment response is cut off mid-body
{ from: 45, mbps: 6.0, abortEvery: 0 },
];
const timer = setInterval(() => {
const p = profile[phaseAt(now())];
tokens = Math.min(BURST_BYTES, tokens + (p.mbps * 1e6 / 8) * (TICK_MS / 1000));
while (tokens > 0 && queue.length) {
const w = queue.shift(); // round-robin across open responses
const n = Math.min(CHUNK, tokens, w.end - w.off);
w.res.write(w.buf.subarray(w.off, w.off + n));
w.off += n;
tokens -= n;
if (w.off < w.end) queue.push(w);
else if (w.cut) w.res.destroy(); // headers promised the full length
else w.res.end();
}
}, TICK_MS);
A cut response sends 200 with the full Content-Length, writes 40% of the body and destroys the socket. To the player that is a network error with status 0 halfway through a segment. Cutting every third segment request is deterministic on purpose: a random loss rate would make two runs differ for a reason that is not the player. A stalled body on an open socket is the other HTTP-level failure, but the default fragLoadPolicy only times it out after 120,000 ms, so it needs a longer session than this one.
The ladder, and the events worth recording
Three renditions, two-second segments, a keyframe every 60 frames so boundaries line up, and noise so the synthetic picture does not compress to nothing:
ffmpeg -hide_banner -loglevel error -y \
-f lavfi -i "testsrc2=size=1280x720:rate=30:duration=96" \
-f lavfi -i "sine=frequency=440:sample_rate=48000:duration=96" \
-filter_complex "[0:v]noise=alls=40:allf=t,split=3[a][b][c];[a]scale=640:360[v0];[b]scale=960:540[v1];[c]copy[v2]" \
-map "[v0]" -map 1:a -map "[v1]" -map 1:a -map "[v2]" -map 1:a \
-c:v libx264 -preset veryfast -profile:v main -g 60 -keyint_min 60 -sc_threshold 0 \
-b:v:0 500k -maxrate:v:0 500k -bufsize:v:0 500k \
-b:v:1 1500k -maxrate:v:1 1500k -bufsize:v:1 1500k \
-b:v:2 4000k -maxrate:v:2 4000k -bufsize:v:2 4000k \
-c:a aac -b:a 96k -ac 2 \
-f hls -hls_time 2 -hls_playlist_type vod -hls_segment_type fmp4 \
-master_pl_name master.m3u8 -var_stream_map "v:0,a:0 v:1,a:1 v:2,a:2" \
-hls_segment_filename "media/r%v_%03d.m4s" -hls_fmp4_init_filename "init_%v.mp4" \
media/r%v.m3u8
ffmpeg wrote BANDWIDTH=614332, 1599884 and 4462008. The player compares its estimate with those, not with the encoder targets. RFC 8216 defines BANDWIDTH as the peak segment bit rate including container overhead but excluding HTTP, TCP and IP overhead, so the link must carry a little more than the number in the playlist.
The page records every event with Date.now() so the test can line it up with the shaper's clock:
hls.on(Hls.Events.LEVEL_SWITCHING, (_, d) => push("LEVEL_SWITCHING", { level: d.level }));
hls.on(Hls.Events.LEVEL_SWITCHED, (_, d) => push("LEVEL_SWITCHED", { level: d.level }));
hls.on(Hls.Events.FRAG_LOADING, (_, d) => push("FRAG_LOADING", { level: d.frag.level, sn: d.frag.sn }));
hls.on(Hls.Events.FRAG_LOADED, (_, d) => push("FRAG_LOADED", {
level: d.frag.level, sn: d.frag.sn, bytes: d.frag.stats.total,
ms: Math.round(d.frag.stats.loading.end - d.frag.stats.loading.start),
bwe: Math.round(hls.bandwidthEstimate / 1000),
}));
hls.on(Hls.Events.FRAG_LOAD_EMERGENCY_ABORTED, (_, d) => push("EMERGENCY_ABORT", { level: d.frag.level, sn: d.frag.sn }));
hls.on(Hls.Events.ERROR, (_, d) => push("ERROR", { details: d.details, fatal: d.fatal, code: d.response?.code }));
The page also samples video.buffered every 250 ms. Under Media Source Extensions it is the intersection of the active source buffers, so the buffer ahead is whichever of audio or video is shorter.
Two of these are easy to confuse. LEVEL_SWITCHING fires when the player decides to load a different rendition. LEVEL_SWITCHED fires, in the 1.7.4 stream controller, when the fragment at the playback position changes rendition: the moment the viewer sees it. The gap between them is roughly the buffer. In the run below, the decision to load 540p after recovery came at 51.63 s and the picture changed at 81.74 s, because 30 seconds of 360p were already buffered. Assert decisions against the network timeline and use the switched event only for what the viewer saw.
The FRAG_LOADED handler reads d.frag.stats. The 1.7.4 API document lists stats on the event data itself, but the type in the source has no such property, so d.stats.total throws. hls.js catches an exception thrown by any listener and re-emits it as an ERROR with details: "internalException" and fatal: false. Reading d.stats logged 56 of them in one 96-second session of this lab, each one the harness's bug counted as a player error.
One session, read line by line
The first of five runs with hls.js defaults, with fragment loads shown only around the low-bandwidth phase:
18.07s 8.0 Mbps FRAG_LOADED level=2 sn=15 bytes=1078884 ms=1215 bwe=7261
19.04s 8.0 Mbps FRAG_LOADED level=2 sn=16 bytes=838969 ms=964 bwe=7270
21.70s 1.2 Mbps FRAG_LOADED level=2 sn=17 bytes=1083229 ms=2667 bwe=7259
28.69s 1.2 Mbps FRAG_LOADED level=2 sn=18 bytes=925944 ms=6984 bwe=5430
28.69s 1.2 Mbps LEVEL_SWITCHING level=1
31.67s 1.2 Mbps FRAG_LOADED level=1 sn=18 bytes=393251 ms=2973 bwe=1936
31.67s 1.2 Mbps ERROR details=bufferAppendNoProgress fatal=false level=1 sn=18
31.67s 1.2 Mbps LEVEL_SWITCHING level=0
32.10s 1.2 Mbps LEVEL_SWITCHING level=2
32.10s 1.2 Mbps ERROR details=fragLoadError fatal=false code=0 level=0 sn=18
33.10s 1.2 Mbps LEVEL_SWITCHING level=0
33.10s 1.2 Mbps EMERGENCY_ABORT level=2 sn=19
33.11s 1.2 Mbps ERROR details=aborted fatal=false level=2 sn=19
35.31s 1.2 Mbps FRAG_LOADED level=0 sn=18 bytes=143429 ms=2205 bwe=614
35.32s 1.2 Mbps ERROR details=bufferAppendNoProgress fatal=false level=0 sn=18
36.23s 1.2 Mbps LEVEL_SWITCHING level=2
36.23s 1.2 Mbps ERROR details=fragLoadError fatal=false code=0 level=0 sn=19
36.54s 1.2 Mbps LEVEL_SWITCHED level=0
37.23s 1.2 Mbps LEVEL_SWITCHING level=0
37.23s 1.2 Mbps EMERGENCY_ABORT level=2 sn=19
37.24s 1.2 Mbps ERROR details=aborted fatal=false level=2 sn=19
38.40s 1.2 Mbps waiting ct=37.930867
38.42s 1.2 Mbps ERROR details=bufferStalledError fatal=false
40.56s 1.2 Mbps FRAG_LOADED level=0 sn=19 bytes=145984 ms=3318 bwe=524
40.57s 1.2 Mbps playing ct=37.973541
41.93s 1.2 Mbps LEVEL_SWITCHING level=2
41.93s 1.2 Mbps ERROR details=fragLoadError fatal=false code=0 level=0 sn=20
42.56s 1.2 Mbps waiting ct=39.914736
42.62s 1.2 Mbps ERROR details=bufferStalledError fatal=false
42.94s 1.2 Mbps LEVEL_SWITCHING level=0
42.94s 1.2 Mbps EMERGENCY_ABORT level=2 sn=20
42.94s 1.2 Mbps ERROR details=aborted fatal=false level=2 sn=20
45.49s 6.0 Mbps FRAG_LOADED level=0 sn=20 bytes=148809 ms=2550 bwe=394
45.50s 6.0 Mbps playing ct=39.957497
46.39s 6.0 Mbps FRAG_LOADED level=0 sn=21 bytes=146100 ms=898 bwe=434
47.11s 6.0 Mbps FRAG_LOADED level=0 sn=22 bytes=145376 ms=715 bwe=541
47.78s 6.0 Mbps FRAG_LOADED level=0 sn=23 bytes=141946 ms=672 bwe=644
48.33s 6.0 Mbps FRAG_LOADED level=0 sn=24 bytes=145861 ms=544 bwe=736
48.81s 6.0 Mbps FRAG_LOADED level=0 sn=25 bytes=149144 ms=485 bwe=834
49.09s 6.0 Mbps FRAG_LOADED level=0 sn=26 bytes=147278 ms=274 bwe=933
49.30s 6.0 Mbps FRAG_LOADED level=0 sn=27 bytes=146940 ms=216 bwe=1048
49.52s 6.0 Mbps FRAG_LOADED level=0 sn=28 bytes=147238 ms=218 bwe=1165
49.73s 6.0 Mbps FRAG_LOADED level=0 sn=29 bytes=143238 ms=200 bwe=1279
49.94s 6.0 Mbps FRAG_LOADED level=0 sn=30 bytes=145826 ms=209 bwe=1388
50.15s 6.0 Mbps FRAG_LOADED level=0 sn=31 bytes=147220 ms=209 bwe=1497
50.36s 6.0 Mbps FRAG_LOADED level=0 sn=32 bytes=149420 ms=211 bwe=1603
50.57s 6.0 Mbps FRAG_LOADED level=0 sn=33 bytes=146523 ms=208 bwe=1708
50.78s 6.0 Mbps FRAG_LOADED level=0 sn=34 bytes=146162 ms=211 bwe=1809
50.99s 6.0 Mbps FRAG_LOADED level=0 sn=35 bytes=142055 ms=206 bwe=1905
51.63s 6.0 Mbps LEVEL_SWITCHING level=1
52.20s 6.0 Mbps ERROR details=bufferAppendNoProgress fatal=false level=1 sn=38
81.74s 6.0 Mbps LEVEL_SWITCHED level=1
101.66s 6.0 Mbps ended ct=96.066666
shaper cut r0_018.m4s at 32.10s after 57371 of 143429 bytes
shaper cut r0_019.m4s at 36.23s after 58393 of 145984 bytes
shaper cut r0_020.m4s at 41.93s after 59523 of 148809 bytes
Four things in that log decide how the assertions must be written.
The player keeps loading 720p for almost nine seconds after the drop. Segment 18 at the top rendition took 6,984 ms at 1.2 Mbps, and the first switch request came at 28.69 s. hls.js did not abandon the fragment: its emergency switch-down check returns early while the estimated time to finish it is shorter than the buffer left, and with over 20 seconds buffered it was. That is correct behaviour, and it puts a floor under any "switched down by" window.
A cut segment on the lowest rendition sends the player to the highest. At 32.10 s a load fails with code=0 on L0 and, in the same millisecond, LEVEL_SWITCHING level=2. hls.js does not retry status 0 unless the browser reports itself offline. It records a load error on the failing rendition and looks for an alternate, starting one rendition below the current one and wrapping around. From the bottom of the ladder, the first candidate is the top. One second later the emergency check aborts that 720p fragment and the player requests 360p again. The cycle repeated at 36.23 s and 41.93 s, and each round spent a second of a 1.2 Mbps link on bytes that were thrown away.
That cycle, not the bandwidth, caused the freezes. The buffer ran out at 38.40 s and again at 42.56 s, and playback resumed at 40.57 s and 45.50 s: 5.11 seconds of frozen picture inside a phase where 360p fits the link with room to spare.
The run logged 12 non-fatal errors and no fatal one. bufferAppendNoProgress appears when a segment is reloaded at a lower rendition, bufferStalledError with each freeze. "No errors" is the wrong assertion; "no fatal error" plus an inventory of the non-fatal ones by details is the useful one.
The exact-second check beside the bounded contract
The exact assertion is the one written after watching a single run. The bounded version states a contract against the profile and allows the time the player legitimately needs.
// Flaky by construction: one instant, read off one observed run.
const exact = (r) => r.levelSeenAt(41) === 0;
// Bounded: each check names a window measured from a profile boundary.
const DROP_AT = 20, RECOVER_AT = 45;
const fits = (level, t) => levels[level].bitrate <= rateAt(t);
const bounded = [
["no fatal error", (r) => r.fatal.length === 0],
["rebuffering after first frame <= 2.0 s", (r) => r.stallSec <= 2.0],
["fitting rendition requested <= 15 s after drop", (r) => r.down && r.down.t - DROP_AT <= 15],
["higher rendition loaded <= 20 s after recovery", (r) => r.up && r.up.t - RECOVER_AT <= 20],
["fetching above shaped rate <= 15 s at a time", (r) => r.worst <= 15],
["nothing above shaped rate once a fit was found", (r) => r.aboveAfterDown.length === 0],
];
r.down is the first LEVEL_SWITCHING after the drop to a rendition whose BANDWIDTH fits the shaped rate. r.up is the first FRAG_LOADED above L0 after recovery: a fragment actually delivered, because a requested switch that ends in an emergency abort has not recovered anything. r.worst is the longest continuous stretch in which the most recent FRAG_LOADING was for a rendition above the shaped rate.
Five runs with hls.js defaults, 8 minutes 24 seconds of wall time:
hls.js defaults, 5 runs
run down-req down-seen up-loaded stalls stall-s over-bw-s above-after-down fatal non-fatal
1 31.67 36.54 52.19 2 5.11 11.70 3 0 12
2 33.07 40.43 52.35 1 1.51 13.10 3 0 9
3 32.95 40.43 52.34 1 1.50 13.00 3 0 9
4 31.53 36.44 52.24 2 5.22 11.55 3 0 12
5 32.30 36.44 52.34 2 5.38 12.30 3 0 12
exact: viewer on L0 at t=38.0s PASS FAIL FAIL PASS PASS
exact: viewer on L0 at t=41.0s PASS PASS PASS PASS PASS
bounded: no fatal error PASS PASS PASS PASS PASS
bounded: rebuffering after first frame <= 2.0 s FAIL PASS PASS FAIL FAIL
bounded: fitting rendition requested <= 15 s after drop PASS PASS PASS PASS PASS
bounded: higher rendition loaded <= 20 s after recovery PASS PASS PASS PASS PASS
bounded: fetching above shaped rate <= 15 s at a time PASS PASS PASS PASS PASS
bounded: nothing above shaped rate once a fit was found FAIL FAIL FAIL FAIL FAIL
The viewer saw the switch to 360p at 36.44 s in some runs and 40.43 s in others, depending on where the dropped segments fell against the buffer. An instant inside that spread, 38 s, fails two runs in five. An instant after it, 41 s, passes all five with 0.57 s to spare on the slowest run, and fails as soon as anything moves the spread later. The bounded rows fail on the two real defects: every run went back to a rendition above the link after finding one that fit, and three runs froze for over five seconds.
Changing the player, then rerunning the same windows
Both defects start from one decision: a dropped connection is not retried. hls.js lets a RetryConfig override that with shouldRetry. The API document gives its fourth argument as an HTTP status, but the 1.7.4 source passes the loader response object, so read response?.code:
const hls = new Hls({
fragLoadPolicy: { default: {
maxTimeToFirstByteMs: 10000, maxLoadTimeMs: 120000,
timeoutRetry: { maxNumRetry: 4, retryDelayMs: 0, maxRetryDelayMs: 0 },
errorRetry: { maxNumRetry: 6, retryDelayMs: 1000, maxRetryDelayMs: 8000,
shouldRetry: (cfg, count, isTimeout, response, retry) =>
retry || (response?.code === 0 && count < cfg.maxNumRetry) },
} },
});
The other values repeat the documented defaults. Five runs with this configuration, 8 minutes 5 seconds of wall time:
retry-dropped config, 5 runs
run down-req down-seen up-loaded stalls stall-s over-bw-s above-after-down fatal non-fatal
1 31.46 36.54 46.69 0 0.00 11.50 0 0 8
2 30.98 36.44 46.97 0 0.00 11.00 0 0 7
3 30.39 36.44 47.09 0 0.00 10.40 0 0 6
4 30.62 36.44 47.13 0 0.00 10.65 0 0 6
5 30.55 36.43 47.11 0 0.00 10.55 0 0 6
exact: viewer on L0 at t=38.0s PASS PASS PASS PASS PASS
exact: viewer on L0 at t=41.0s PASS PASS PASS PASS PASS
bounded: no fatal error PASS PASS PASS PASS PASS
bounded: rebuffering after first frame <= 2.0 s PASS PASS PASS PASS PASS
bounded: fitting rendition requested <= 15 s after drop PASS PASS PASS PASS PASS
bounded: higher rendition loaded <= 20 s after recovery PASS PASS PASS PASS PASS
bounded: fetching above shaped rate <= 15 s at a time PASS PASS PASS PASS PASS
bounded: nothing above shaped rate once a fit was found PASS PASS PASS PASS PASS
Every cut segment was retried at 360p, no request went above the shaped rate after the first fit, nobody saw a freeze, and the player loaded 540p about two seconds after the recovery instead of seven. Both exact checks now pass every run, because the switch time stopped wandering. Their failure rate followed the defect without describing it: a red exact check would have sent someone to tune the instant, not to read the error controller.
The change has a cost. hls.js declines to retry status 0 because that is also how a CORS failure reaches it, and this configuration retries those too: up to six more attempts, with delays starting at 1 second and capped at 8, on a request that will never succeed. Check a related default in the same test: a rendition with a load error is excluded from up-switch selection, and errorPenaltyExpireMs defaults to 0, which keeps it excluded for the rest of the session. A positive value lets it back after that many milliseconds, but does not stop the jump to the top rendition.
Where the window sizes come from
Derive each bound from the ladder and the player's documented rules before the first run.
- Down-switch window. The worst case is a top-rendition segment that has just started when the rate drops: 2 seconds of 4.46 Mbps media at 1.2 Mbps is about 7.4 seconds. hls.js then has to see slower fragments before the estimate falls; its VoD estimator blends half-lives of 3 and 9 seconds. One more middle-rendition fragment at 1.2 Mbps is about 2.7 seconds. 15 seconds covers that with margin.
- Recovery window. Up-switching needs
abrBandWidthUpFactor(0.7) times the estimate to exceed the next rendition'sBANDWIDTH. At 6 Mbps that allows 540p but not the 4.46 Mbps 720p, because 0.7 × 6 is 4.2. Assert "above the lowest rendition", not "back to the top"; the latter fails forever on this ladder. - Rebuffering. With a 30-second
maxBufferLengthand a 25-second dip, a player that drops to 360p should not stall at all. The 2-second limit allows for one segment lost at the wrong moment.
Recompute the windows when the profile, segment duration or buffer changes. Never loosen one because a run failed it; read the timeline first.
Runtime, and what the lab leaves out
The session plays in real time: about 100 seconds per run and 8 minutes for five. That is a nightly or pre-release job, not a pull request check. Sessions run in parallel need a proxy and bucket each, or they share one link.
The shaper models throughput and HTTP failure, not TCP: no round-trip growth, no slow start after idle, no reordering, and loopback hides a distant CDN's time to first byte. Treat it as a regression check on the player's decisions, and take absolute switch timings from field data.
Questions about testing adaptive bitrate
Should loss be random instead of every third segment?
Not in a regression test: a fixed pattern makes a failure reproducible. Run randomised profiles as a separate exploratory job and turn its failures into fixed profiles.
Does this apply to Shaka Player, dash.js or a native TV player?
The proxy and the windows do. The defects here belong to hls.js 1.7.4's error controller; other players have their own retry and penalty rules, so read them for the version you ship.
Can the test force a level instead of waiting for ABR?
Setting hls.currentLevel flushes the buffer and loads immediately, which tests switching mechanics, not the ABR decision. Use it for a separate check that every rendition decodes and plays, and leave the adaptive test in automatic mode.
Sources for the adaptive bitrate checks
- hls.js 1.7.4 API documentation. Switch events, the
fatalflag, ABR factors and half-lives, load policies,shouldRetryanderrorPenaltyExpireMs. - hls.js 1.7.4 error controller. The alternate search that wraps from the lowest rendition to the highest.
- hls.js 1.7.4 error helper. No retry for status 0 unless offline, and the response object passed to
shouldRetry. - hls.js 1.7.4 ABR controller. The emergency switch-down check that waits while the buffer outlasts the fragment.
- hls.js 1.7.4 stream controller.
LEVEL_SWITCHEDfired when the playing fragment changes rendition. - hls.js 1.7.4 Hls class. Listener exceptions re-emitted as
internalExceptionerrors. - hls.js 1.7.4 event types.
FragLoadedDatawithout astatsproperty. - The HLS specification, RFC 8216.
BANDWIDTHas peak segment bit rate without delivery overhead. - W3C Media Source Extensions. The element's buffered ranges as the intersection of the active source buffers.
- Chrome DevTools Protocol definition. Aggregated throughput,
navigatorstate, and no mid-response failure option.
Apply this now to your ABR checks
- Search your playback tests for assertions on a rendition, resolution or level at a fixed number of seconds. Each one becomes a window measured from a network event.
- Put a shaping proxy in front of a test copy of your ladder, with a single bucket for all connections and a deliberate mid-body cut for some segments. Point a real device at it as well as the browser.
- Log
LEVEL_SWITCHING,LEVEL_SWITCHED,FRAG_LOADING,FRAG_LOADEDand everyERRORwith itsfatalflag and response code, and keep the timeline as a CI artifact. - Check your player's error recovery: after a dropped segment on the lowest rendition, which rendition does it request next, and can it climb again once the network recovers?
- Write the bounds down with the arithmetic that produced them, next to the profile they belong to.