Skip to main content
Back to Blog

Build a Streaming Quality Model Beyond Video Starts

A video start metric counts a session that froze twice and fell to 360p as a success. Split each session into eight contracts, assert each from the player's event log and buffer, and report the ones you cannot observe as NOT TESTED. Includes a Playwright and hls.js lab with one held segment.

Shashank Rawlani

Engineering Leader | Builder | Problem Solver | AI Engineer

Published Nov 21, 202617 min read
View AI-ready Markdown
A green strand enters from the left, passes a ringed green node and fans into eight lanes. Two run unbroken to green nodes; one breaks at two orange gaps and one thins to orange, both ending in crossed circles; four are dashed grey.
Quick answer: A video start metric answers one question: did a first frame play. A viewing session makes at least eight separate promises: startup, continuity, adaptation, audio and video sync, presentation and captions, entitlement, ads, and recovery. Each has its own signal in its own layer: the manifest, player events, the Media Source Extensions buffer, or the device. Assert each contract separately from the session's event log, report one with no signal as NOT TESTED rather than passing it, count waiting only after the first playing, and do not expect stalled to fire for an MSE player.

The dashboard tile says 99.4% of video starts succeeded, and the support queue is full of viewers saying the match froze. Both can be true at once. Take one session from the lab later in this article. The first frame plays 36 milliseconds after the page asks for it. Then the picture freezes twice, for six seconds in total, and the player drops from 720p to 360p and finishes there. A start-success metric counts that session as a success. A time-to-first-frame chart ranks it above the clean session, which took 204 milliseconds to start.

The start metric is not wrong. It measures one row of a table that has eight, and a team holding only that row cannot tell a frozen match from a good one. This article builds the table and computes it from a real browser session.

This is part 1 of an eight-part series on streaming and connected-TV quality. Later parts each take one area: manifest validation, startup percentiles, adaptive bitrate under controlled networks, DRM without leaking keys, server-side ad events, captions and A/V sync, and telemetry release gates. This part is the map they share.

Versions checked on 2026-11-18: ffmpeg 9.0.1, Node.js 26.12.1, Playwright 1.62.1 with its bundled Chromium 151.0.7922.34, and hls.js 1.7.4. The lab ran on macOS against http://localhost only, with synthetic ffmpeg testsrc2 and sine media. The cited MSE and EME documents are W3C Working Drafts dated 9 and 8 November 2026, and Media Playback Quality is an Editor's Draft; re-read them before relying on a detail.

Eight promises inside one viewing session

Each row below is a contract a viewer would describe in their own words. The third column is what a test can actually assert, and the fourth is the lowest layer where that signal exists.

ContractWhat the viewer noticesSignal a test can assertLayer that sees it
StartupA black screen after pressing playTime from the play request to the first playing eventPlayer events
ContinuityThe picture freezes mid-programmeEach waiting after the first playing, with currentTime against the end of video.bufferedPlayer events and MSE buffer
AdaptationA soft picture on a good connectionRendition switches and time spent on each rendition, against the BANDWIDTH each variant declaresPlayer and manifest
A/V syncLips and voice drift apartOffset between a known visual marker and a known audio marker in the decoded outputDevice output
Presentation and captionsJudder, or subtitles missing or in the wrong languagegetVideoPlaybackQuality() counters; subtitle renditions in the manifest and text tracks in the playerDecoder, manifest and player
Entitlement"Not available" for a paying viewerLicence response status and EME key statuses such as usable, expired and output-restrictedLicence service and the CDM
AdsThe break plays, but content resumes at the wrong point or the impression is never countedSplice markers in the playlist joined to the tracking beacons the player sentManifest and beacon collector
RecoveryThe player gives up where a retry would have workedFatal against non-fatal player errors, and time from a stall to the next playingPlayer

The layer column doubles as a routing table. A freeze where currentTime has reached the end of the buffered range means media did not arrive in time, which points at the CDN, the origin or the player's request scheduling. A freeze with seconds of media already buffered ahead points away from the network, towards the decoder or the player's own state. Team names differ between companies; what matters is that every row has one first responder and fails with the evidence that routes it.

What the manifest, the player and the device can each prove

The manifest proves what is offered, not what plays. RFC 8216 defines BANDWIDTH on a variant as its peak segment bit rate and warns that an inaccurate value can cause playback stalls or stop a client from playing the variant. A manifest check can catch that lie before it looks like an adaptation problem. It cannot fully check captions: an EXT-X-MEDIA entry with TYPE=CLOSED-CAPTIONS does not specify a rendition, because CEA-608 captions normally travel inside the video stream, so the playlist can only declare them. The same RFC states that the algorithms clients use to switch between variants are out of its scope. Adaptation behaviour therefore belongs to the player, and two players can make different choices from the same playlist without either breaking the protocol.

Player events prove what the element did. The HTML standard defines waiting as playback having stopped because the next frame is not available while the user agent expects it to arrive, and playing as playback being ready to start after a pause or a delay for lack of data. Those two events bracket every freeze. hls.js adds its own vocabulary and reports every problem through a single ERROR event whose fatal flag is true only after all of its recovery attempts have run out.

The MSE buffer proves why the element stopped. Logging video.buffered next to each waiting turns "it froze at 7.91 seconds" into "it froze at 7.91 seconds with media buffered only to 7.96", a delivery problem, not a decoder one.

The device proves what the viewer saw. Encrypted Media Extensions defines an output-restricted key status for a key whose output restrictions cannot currently be met, in which case the decrypted media may be blocked from presentation. A key can be usable in a desktop test browser and restricted on a viewer's television and display chain. Sync drift, decoder frame drops and output protection live here, out of reach of a headless browser. EME is also exposed only to secure contexts, so a browser entitlement lab must run from https or http://localhost, never file://.

Three media events that mislead a naive monitor

waiting fires before the first frame. When play() is called and the element's readyState is HAVE_NOTHING, HAVE_METADATA or HAVE_CURRENT_DATA, the HTML standard has it queue a waiting event. In the lab both sessions log one at 3 milliseconds, before the manifest is even parsed. A monitor that counts every waiting as a rebuffer reports a freeze in every session, and teams learn to ignore it.

stalled belongs to a code path MSE does not use. The HTML standard defines stalled inside the steps for fetching a remote resource: after a media element stall timeout of about three seconds with no data, the element fires it. The MSE specification says an attached MediaSource does not use those remote-mode steps, and that future versions will likely remove stalled for MSE playback, though today's browsers may still fire it. In the lab, Chromium 151 fired no stalled event during a freeze lasting six seconds. hls.js feeds the element through MSE, so a dashboard built on stalled can show zero freezes for a player like this one while viewers watch a frozen picture.

Dropped-frame counters are local and resettable. Media Playback Quality defines droppedVideoFrames as frames dropped before decode or for missing their display deadline, and resets both counters whenever the element's load algorithm runs, which includes assigning it a new source. Treat them as a property of the machine doing the decoding. Across four runs of the lab, the session with the held segment dropped 20, 0, 16 and 12 of 720 frames, and the clean session dropped none in any run. That is a desktop under test load, not evidence about a television.

A lab with one held segment

The lab plays the same 24-second stream twice in Playwright's Chromium. The first session is served cleanly. In the second, a local server sends the response headers for segment 4 (8 to 10 seconds of media) at once, then holds the body for 8 seconds, in every rendition. The fault is injected at the HTTP layer because packet-level loss needs root on macOS, and a response whose body arrives late is how slow delivery looks from the player's side. Both sessions start; the question is which contracts notice.

In a scratch directory, install the pinned packages:

npm init -y
npm i [email protected] [email protected]

Generate two renditions, 720p and 360p, as fragmented MP4 HLS with two-second segments and a keyframe every 60 frames, so segment boundaries line up across renditions:

mkdir -p media
ffmpeg -hide_banner -loglevel error -y \
  -f lavfi -i testsrc2=size=1280x720:rate=30:duration=24 \
  -f lavfi -i sine=frequency=1000:sample_rate=48000:duration=24 \
  -filter_complex "[0:v]split=2[a][b];[b]scale=640:360[b2]" \
  -map "[a]" -map "[b2]" -map 1:a -map 1:a \
  -c:v libx264 -profile:v main -preset veryfast -g 60 -keyint_min 60 -sc_threshold 0 \
  -b:v:0 2500k -b:v:1 700k -c:a aac -b:a 96k \
  -f hls -hls_time 2 -hls_playlist_type vod -hls_segment_type fmp4 \
  -var_stream_map "v:0,a:0 v:1,a:1" -master_pl_name master.m3u8 \
  -hls_segment_filename "media/v%v/seg%02d.m4s" media/v%v/index.m3u8

The server holds the body of any path ending in the configured suffix:

// Static server for the lab. serve("seg04.m4s=8000") sends the headers for
// any path ending in seg04.m4s at once, then holds the body for 8 s.
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { extname, join } from "node:path";

const TYPES = { ".html": "text/html", ".js": "text/javascript", ".m3u8": "application/vnd.apple.mpegurl",
  ".mp4": "video/mp4", ".m4s": "video/iso.segment" };
const FILES = { "/": "player.html", "/hls.min.js": "node_modules/hls.js/dist/hls.min.js" };

export function serve(delay = "") {
  const [suffix, ms] = delay ? delay.split("=") : [null, 0];
  const server = createServer(async (req, res) => {
    const path = req.url.split("?")[0];
    const file = FILES[path] ?? (path.startsWith("/media/") ? join(".", path) : null);
    let body;
    try { body = await readFile(file); } catch { res.writeHead(404).end(); return; }
    res.writeHead(200, { "content-type": TYPES[extname(file)] ?? "application/octet-stream" });
    if (suffix && path.endsWith(suffix)) {
      res.flushHeaders();
      setTimeout(() => res.end(body), Number(ms));
    } else {
      res.end(body);
    }
  });
  return new Promise((ok) => server.listen(0, "127.0.0.1", () => ok(server)));
}

The page logs every event with currentTime and the buffered ranges at that moment. It listens for stalled too, so its absence is measured, not assumed:

<!doctype html>
<meta charset="utf-8">
<video id="v" muted playsinline width="640"></video>
<script src="/hls.min.js"></script>
<script>
  const video = document.getElementById("v");
  const t0 = performance.now();
  const log = (window.__log = []);
  const ranges = () => Array.from({ length: video.buffered.length }, (_, i) =>
    [+video.buffered.start(i).toFixed(2), +video.buffered.end(i).toFixed(2)]);
  const rec = (type, extra = {}) =>
    log.push({ t: Math.round(performance.now() - t0), type, ct: +video.currentTime.toFixed(2), buf: ranges(), ...extra });

  for (const type of ["loadedmetadata", "playing", "waiting", "stalled", "ended", "error"]) {
    video.addEventListener(type, () => rec(type));
  }

  const hls = new Hls();
  hls.on(Hls.Events.MANIFEST_PARSED, (_, d) =>
    rec("manifest", { heights: d.levels.map((l) => l.height), subtitleTracks: hls.subtitleTracks.length }));
  hls.on(Hls.Events.LEVEL_SWITCHED, (_, d) => rec("level", { height: hls.levels[d.level].height }));
  hls.on(Hls.Events.ERROR, (_, d) => rec("hls-error", { details: d.details, fatal: d.fatal }));
  hls.loadSource("/media/master.m3u8");
  hls.attachMedia(video);
  video.play().catch((e) => rec("play-rejected", { name: e.name }));

  video.addEventListener("ended", () => {
    const q = video.getVideoPlaybackQuality();
    rec("quality", { total: q.totalVideoFrames, dropped: q.droppedVideoFrames });
    window.__done = true;
  });
</script>

Verdicts come only from that log, and a contract with no signal in this stream reports NOT TESTED:

// One verdict per contract, computed only from the session's event log.
// A contract with no signal in this stream says NOT TESTED; it never passes.
const POLICY = { startupMs: 3000, rebufferRatio: 0.005, droppedRatio: 0.01, recoveryMs: 10000, topHeight: 720, topShare: 0.8 };

export function verdicts(log) {
  const first = (type) => log.find((e) => e.type === type);
  const manifest = first("manifest");
  const playing = first("playing");
  const ended = first("ended");
  const quality = first("quality");

  // A stall is a `waiting` after playback began, closed by the next `playing`.
  const stalls = [];
  for (const e of log) {
    if (!playing || e.t <= playing.t) continue;
    if (e.type === "waiting") stalls.push({ from: e.t, at: e.ct, buf: e.buf, to: null });
    if (e.type === "playing" && stalls.at(-1)?.to === null) stalls.at(-1).to = e.t;
  }
  const stallMs = stalls.reduce((sum, s) => sum + ((s.to ?? ended.t) - s.from), 0);
  const watchMs = ended.t - playing.t;
  const ratio = stallMs / watchMs;
  // Share of the session, first `playing` to `ended`, spent on the top rendition.
  const levels = log.filter((e) => e.type === "level");
  let topMs = 0;
  levels.forEach((e, i) => {
    const from = Math.max(e.t, playing.t);
    const to = levels[i + 1]?.t ?? ended.t;
    if (e.height === POLICY.topHeight) topMs += Math.max(0, to - from);
  });
  const topShare = topMs / watchMs;
  const fatal = log.filter((e) => e.type === "hls-error" && e.fatal);
  const longest = Math.max(0, ...stalls.map((s) => (s.to ?? ended.t) - s.from));

  const row = (contract, verdict, evidence) => `${contract.padEnd(13)} ${verdict.padEnd(10)} ${evidence}`;
  const ok = (cond) => (cond ? "PASS" : "FAIL");
  return [
    row("contract", "verdict", "evidence"),
    row("video start", ok(!!playing), playing ? "playing fired" : "playing never fired"),
    row("startup", ok(playing.t <= POLICY.startupMs), `first playing at ${playing.t} ms (limit ${POLICY.startupMs})`),
    row("continuity", ok(ratio <= POLICY.rebufferRatio),
      `${stalls.length} stall(s), ${stallMs} ms of ${watchMs} ms = ${(ratio * 100).toFixed(2)}%` +
      stalls.map((s) => `; waiting at ${s.at}s, buffered ${JSON.stringify(s.buf)}`).join("")),
    row("adaptation", ok(topShare >= POLICY.topShare),
      `${levels.map((e) => `${e.height}p`).join(" -> ")}, ${(topShare * 100).toFixed(0)}% of session at ${POLICY.topHeight}p`),
    row("presentation", ok(quality.dropped / quality.total <= POLICY.droppedRatio),
      `${quality.dropped} of ${quality.total} frames dropped`),
    row("recovery", ok(fatal.length === 0 && longest <= POLICY.recoveryMs),
      `${fatal.length} fatal error(s), longest stall ${longest} ms`),
    row("captions", "NOT TESTED", `${manifest.subtitleTracks} subtitle rendition(s) in the manifest`),
    row("av sync", "NOT TESTED", "no sync marker in the media"),
    row("entitlement", "NOT TESTED", "clear stream, no key system"),
    row("ads", "NOT TESTED", "no ad markers in the playlist"),
  ];
}

The runner starts a fresh server per scenario and waits for ended:

// Plays the local stream once per scenario in Playwright's Chromium, prints
// the raw event log, then a verdict per contract.
import { chromium } from "playwright";
import { serve } from "./server.mjs";
import { verdicts } from "./contracts.mjs";

const scenarios = [
  { name: "clean", delay: "" },
  { name: "seg04-held-8s", delay: "seg04.m4s=8000" },
];

const browser = await chromium.launch();
console.log(`chromium ${browser.version()}`);
for (const s of scenarios) {
  const server = await serve(s.delay);
  const page = await browser.newPage();
  await page.goto(`http://localhost:${server.address().port}/`);
  await page.waitForFunction(() => window.__done === true, null, { timeout: 90_000 });
  const log = await page.evaluate(() => window.__log);
  console.log(`\n=== ${s.name} ===`);
  for (const e of log) console.log(JSON.stringify(e));
  console.log("");
  for (const row of verdicts(log)) console.log(row);
  await page.close();
  server.close();
}
await browser.close();
node session.mjs

Both sessions play in real time, so the run takes about 55 seconds. This is its output, unedited:

chromium 151.0.7922.34

=== clean ===
{"t":3,"type":"waiting","ct":0,"buf":[]}
{"t":5,"type":"manifest","ct":0,"buf":[],"heights":[360,720],"subtitleTracks":0}
{"t":35,"type":"loadedmetadata","ct":0,"buf":[]}
{"t":204,"type":"playing","ct":0,"buf":[[0,24.07]]}
{"t":204,"type":"level","ct":0,"buf":[[0,24.07]],"height":720}
{"t":24320,"type":"ended","ct":24.07,"buf":[[0,24.07]]}
{"t":24321,"type":"quality","ct":24.07,"buf":[[0,24.07]],"total":720,"dropped":0}

contract      verdict    evidence
video start   PASS       playing fired
startup       PASS       first playing at 204 ms (limit 3000)
continuity    PASS       0 stall(s), 0 ms of 24116 ms = 0.00%
adaptation    PASS       720p, 100% of session at 720p
presentation  PASS       0 of 720 frames dropped
recovery      PASS       0 fatal error(s), longest stall 0 ms
captions      NOT TESTED 0 subtitle rendition(s) in the manifest
av sync       NOT TESTED no sync marker in the media
entitlement   NOT TESTED clear stream, no key system
ads           NOT TESTED no ad markers in the playlist

=== seg04-held-8s ===
{"t":3,"type":"waiting","ct":0,"buf":[]}
{"t":4,"type":"manifest","ct":0,"buf":[],"heights":[360,720],"subtitleTracks":0}
{"t":25,"type":"loadedmetadata","ct":0,"buf":[]}
{"t":36,"type":"playing","ct":0,"buf":[[0,7.96]]}
{"t":36,"type":"level","ct":0,"buf":[[0,7.96]],"height":720}
{"t":7996,"type":"waiting","ct":7.91,"buf":[[0,7.96]]}
{"t":8007,"type":"hls-error","ct":7.91,"buf":[[0,7.96]],"details":"bufferStalledError","fatal":false}
{"t":8052,"type":"playing","ct":7.94,"buf":[[0,9.96]]}
{"t":10059,"type":"waiting","ct":9.92,"buf":[[0,9.96]]}
{"t":10107,"type":"hls-error","ct":9.92,"buf":[[0,9.96]],"details":"bufferStalledError","fatal":false}
{"t":16048,"type":"hls-error","ct":9.92,"buf":[[0,9.96]],"details":"bufferAppendNoProgress","fatal":false}
{"t":16049,"type":"level","ct":9.92,"buf":[[0,9.96]],"height":360}
{"t":16053,"type":"playing","ct":9.96,"buf":[[0,13.97]]}
{"t":30204,"type":"ended","ct":24.07,"buf":[[0,24.07]]}
{"t":30205,"type":"quality","ct":24.07,"buf":[[0,24.07]],"total":720,"dropped":12}

contract      verdict    evidence
video start   PASS       playing fired
startup       PASS       first playing at 36 ms (limit 3000)
continuity    FAIL       2 stall(s), 6050 ms of 30168 ms = 20.05%; waiting at 7.91s, buffered [[0,7.96]]; waiting at 9.92s, buffered [[0,9.96]]
adaptation    FAIL       720p -> 360p, 53% of session at 720p
presentation  FAIL       12 of 720 frames dropped
recovery      PASS       0 fatal error(s), longest stall 5994 ms
captions      NOT TESTED 0 subtitle rendition(s) in the manifest
av sync       NOT TESTED no sync marker in the media
entitlement   NOT TESTED clear stream, no key system
ads           NOT TESTED no ad markers in the playlist

What the two verdict tables say

Start and startup pass in both. The faulted session reported its first playing after 36 milliseconds, against 204 for the clean one. The head start is localhost noise, not a property of the stream, and a start chart cannot see anything after the first frame anyway.

Continuity fails, and the log shows why. The first freeze began at 7.91 seconds with media buffered to 7.96: the buffer ran dry exactly at the held segment, and that freeze lasted 56 milliseconds because the segment arrived 8 seconds after it was requested. The second freeze lasted 5,994 milliseconds and began at 9.92 seconds, after segment 4 was already in the buffer. Nothing in the fault explains a second freeze, so a second run added two listeners for hls.js fragment events, logging each fragment's sequence number and level index (0 is 360p, 1 is 720p):

for (const ev of ["FRAG_LOADING", "FRAG_LOADED"]) {
  hls.on(Hls.Events[ev], (_, d) => rec(ev, { sn: d.frag.sn, lvl: d.frag.level }));
}
{"t":39,"type":"FRAG_LOADING","ct":0,"buf":[[0,7.96]],"sn":4,"lvl":1}
{"t":8045,"type":"FRAG_LOADED","ct":7.84,"buf":[[0,7.96]],"sn":4,"lvl":1}
{"t":8051,"type":"FRAG_LOADING","ct":7.85,"buf":[[0,9.96]],"sn":4,"lvl":0}
{"t":16058,"type":"FRAG_LOADED","ct":9.92,"buf":[[0,9.96]],"sn":4,"lvl":0}
{"t":16059,"type":"hls-error","ct":9.92,"buf":[[0,9.96]],"details":"bufferAppendNoProgress","fatal":false}
{"t":16060,"type":"level","ct":9.92,"buf":[[0,9.96]],"height":360}

After segment 4 took 8 seconds at 720p, the player switched down and requested segment 4 again at 360p. The lab holds segment 4 in every rendition, so that request waited 8 seconds too, and playback froze until it arrived. Its append then produced bufferAppendNoProgress, which hls.js raises when appending a whole fragment does not extend the buffered coverage; 8 to 10 seconds was already buffered from the 720p copy. One slow response cost two freezes and a wasted download: the player's reaction cost more than the fault, and only the continuity row, read with the buffer, shows it.

Adaptation fails at 53%. From 16 seconds of wall clock the player showed 360p, and the rest of this short stream then loaded at 360p within milliseconds, leaving nothing to upgrade. The verdict is still the viewer's truth: almost half the session ran at the lower rendition on a connection that could carry the higher one.

Presentation is the noisy row. It failed here on 12 dropped frames, yet passed in another run of the same session. A row that flips on an unchanged stream belongs on the device it describes, not in a desktop gate.

Recovery passes. Both bufferStalledError events were non-fatal and the longest freeze stayed under 10 seconds. A test watching only for fatal errors would have passed this session outright.

Four rows say NOT TESTED. The stream has no subtitle rendition, no sync marker, no key system and no ad markers. Without those rows the clean session reads six out of six; with them, six of ten, which is what the lab actually knows.

What this model costs, and where it stops

The thresholds are policy. Three seconds to start, 0.5% rebuffering and 80% of the session on the top rendition are this lab's numbers, and no specification sets any of them. Derive yours from your own sessions before a verdict means anything.

One session is an anecdote. A rebuffer ratio becomes a gate only across many sessions, split by device family and network; the verdict table is the unit those aggregates are built from.

Real-time playback is the price of honest timing: 55 seconds for 48 seconds of media. Raising playbackRate changes how fast the buffer drains, which is the very thing continuity measures.

A desktop browser stops at the device boundary. Sync, decoder drops and output restrictions need the viewer's television, set-top box or phone; this lab tells you which rows still need that hardware. If you embed a third-party player you cannot instrument, keep its unobservable rows in the table as NOT TESTED so the gap stays visible.

Questions about modelling stream quality

Is a rebuffer ratio enough for continuity?

No. A ratio dilutes. One six-second freeze in a two-hour match is about 0.08% of the session, under a 0.5% target, and it is still the moment a goal was missed. Assert the longest single freeze and the number of freezes alongside the ratio.

Can CDN logs replace player-side signals?

They show that a segment response was slow, not whether the player was waiting for it; a player holding 30 seconds of media can absorb a slow segment unseen. In the lab, the CDN view would hold two 8-second responses with no hint that the second was a needless re-request. Joining both sides needs a shared session identifier.

Our TV app uses a native player, not hls.js. Does this transfer?

The contracts transfer; the signal sources do not. waiting, playing and buffered are HTML media element behaviour. LEVEL_SWITCHED and the fatal flag are hls.js vocabulary, and a native player reports rendition changes and unrecoverable errors in its own way, if at all. Map each row to what your player reports, and keep the row when it reports nothing.

Specifications behind the session contracts

Apply this now to your playback checks

  1. Put your current start metric in a table with the eight contracts beside it, and mark each row with the signal you collect today, or NOT TESTED.
  2. Change the rebuffer counter to count waiting only after the first playing, and remove any alert that depends on stalled for an MSE player.
  3. Log video.buffered and currentTime with every waiting, so each freeze arrives already routed to delivery or to the decoder.
  4. Run the held-segment session against your own player build and keep the raw event log with the CI run; the guide to retaining CI artifacts that explain failures covers how long and where. The JSON formatter makes a long log readable.
  5. Name one owner per row, and capture the table and the first held-segment verdicts as the baseline for the next release.