A video platform is mostly a very large file and a very impatient viewer. This chapter designs its frontend for a phone on a 4G network, following the seven steps of the method chapter.
Step one lists what the viewer can do. A video product has two sides, browsing and watching, and the requirements name both.
Browse a catalogue of titles as a grid of thumbnails.
Open a title and watch it, with a start that feels quick.
Pause and seek, by touch or by keyboard.
Choose captions in English or Hindi, or none.
Let the quality follow the network, with a manual choice as well.
Come back later and continue from where you stopped.
Out of scope, said aloud: uploading and transcoding, which is the backend half and belongs to the video chapter of the System Design course; recommendations and search; live streams; downloads for offline use; ads and casting. Protected content is named and not built: playing paid video usually needs digital rights management (DRM), a separate system with its own player integration, and none of the code here depends on it.
Question
Because the answer changes
On demand or live?
the playlist type and how far ahead the player may buffer
How long is a typical title?
how much a viewer will want to seek, and how long a session is
Which devices and which video formats must play?
the codecs to offer and the support checks
Is the content protected?
signed links, DRM, and who may fetch segments
How expensive is mobile data for these viewers?
the default quality and whether the page respects a request for less data
Targets on 4G
The quality requirements need numbers. The ones below are our own targets for this design. No standard sets them, and a real product would tune them from its own field data.
Area
Target
How it is checked
Start
first frame within 3 s on 4G at the 75th percentile
time from the click to the first frame, in a throttled lab run and in field data
Stalls
less than 1% of watch time spent waiting for data
stall time divided by watch time, per session
Quality
start on a low rung, climb when the network allows, drop before the buffer empties
the rung chosen for each segment
Data
the viewer can see and cap quality; a request for less data is honoured
bytes per minute at each setting
Accessibility
captions; every control reachable and named; touch targets at least 24 by 24 CSS pixels
keyboard pass, role and name checks
Languages
caption languages chosen by the viewer; the interface in English and Hindi
render each
Offline
not required
listed as out of scope
Two quantities decide almost everything that follows: the bit rate of the video, and the speed of the network. The next page puts numbers on the first.
What a minute of video costs
A video is stored at several bit rates, which is how many bits one second of it takes. A higher rate means a sharper picture and a bigger download. The viewer pays for every byte, so the ladder of rates, one for each size of picture, is also a price list. The script turns a ladder into megabytes per minute, per 45-minute episode, and minutes of video in a daily allowance of 1.5 GB. The first three rungs are the peak rates of the files made for this chapter, in kilobits per second. The top two are round numbers chosen to complete the table, and no encoder was run for them.
js
const ladder = [
{ name: '240p', kbps: 314 }, { name: '360p', kbps: 673 },
{ name: '480p', kbps: 1156 }, { name: '720p', kbps: 2500 },
{ name: '1080p', kbps: 5000 },
]
const mb = (kbps, seconds) => (kbps * 1000 * seconds) / 8 / 1e6
const nf = new Intl.NumberFormat('en-IN', { maximumFractionDigits: 0 })
const plan = 1500// a 1.5 GB daily allowance, in MB
console.log('rung MB per min MB per 45 min minutes per 1.5 GB')
for (const r of ladder) {
const perMin = mb(r.kbps, 60)
console.log(r.name.padEnd(8) + perMin.toFixed(1).padStart(8) +
mb(r.kbps, 2700).toFixed(0).padStart(15) +
nf.format(plan / perMin).padStart(17))
}
ladder.mjs: bit rate in, megabytes out.
text
rung MB per min MB per 45 min minutes per 1.5 GB
240p 2.4106637
360p 5.0227297
480p 8.7390173
720p 18.884480
1080p 37.5168840
Output (Node 24)
At 480p, one minute is 8.7 MB and a 45-minute episode is 390 MB, so a 1.5 GB allowance gives about 173 minutes. At the lowest rung the same allowance gives more than ten hours, and at the top rung it gives 40 minutes. The numbers explain the design choices to come. Starting on a low rung costs little if the guess is wrong. A manual cap matters to a viewer on a small plan. And a prefetch that fetches a whole segment for a title the viewer never opens spends real money, which the catalogue lesson will weigh.
Why is the bit-rate ladder also a price list?
Each rung sets how many bytes a minute of video downloads, and the viewer pays for those bytes.
At 480p a minute is 8.7 MB in the run, and at 1080p it is 37.5 MB.
Why are the targets for start and stalls written as percentiles and ratios and not as "fast"?
A target needs a number and a way to check it, or nobody can say whether it was met.
Percentiles describe most viewers, and a ratio of stall time to watch time compares sessions of different length.
Why is DRM named in the requirements but not built?
It is a separate system with its own integration and licensing, and it would swamp the problem.
Naming it shows it was considered and left out on purpose.
Part 2 · Architecture and data model
The pieces of a player
Step two draws the client from the standard skeleton. A video client has two pipelines side by side. The catalogue is an ordinary list: the same views, store and data layer as the news feed chapter. The player is the unusual part, so most of the drawing goes there.
A CDN, a content delivery network, is a set of servers close to viewers that hold copies of the files. The player talks to it with ordinary HTTP requests for small files, which is why video can ride on the same infrastructure as the rest of the web. The browser does the heavy work: it decodes video, draws frames and keeps the decoded data. The page's job is to feed it the right bytes at the right time, and to show what is happening.
Piece
Its job
Segment loader
reads playlists, picks a rendition for each segment, fetches and appends it
MediaSource and SourceBuffer
the browser objects that accept appended segments and play them
Player state
turns the video element's events into a state the controls can show
Controls
play, pause, seek, captions, quality; keyboard and touch
Progress tracker
saves where the viewer is, and reads it when a title opens
Entities and where state lives
Step three names the entities. A title is something to watch, with a thumbnail, a duration, a playlist address and a list of captions. A rendition is one rung of the ladder. Progress says how far a viewer got. The types are in one file.
ts
importtype { Progress } from'./resume.ts'exporttype { Progress }
exporttype Image = { url: string; width: number; height: number }
exporttype Caption = {
language: string // a BCP 47 tag, such as 'en' or 'hi'
label: string // what the menu shows
url: string // a WebVTT file
}
exporttype Title = {
id: string
name: string
durationSec: number
thumbnail: Image
playlist: string // the multivariant playlist
captions: Caption[]
}
exporttype Rendition = {
uri: string
bandwidth: number // peak bit rate, bits per second
width: number
height: number
}
exporttype PlayerState =
| 'idle' | 'loading' | 'playing' | 'buffering'
| 'paused' | 'ended' | 'error'
types.ts: the things the screens are made of.
Three details matter. Times are in seconds, as numbers, because the media element counts that way. The caption language is a BCP 47 tag, the same kind of tag the srclang attribute takes. And the player state is a union of seven names, so the controls can be checked for every case.
State
Home
Why
Catalogue, titles, saved progress
server, copied into the cache
the server decides what exists and how far you got
Current time, buffered ranges, volume
the video element
the browser owns playback; the page reads it
Player state (loading, playing...)
local UI state, derived from events
it is a view of the element, not a copy of it
Chosen caption language, quality cap
local storage as a preference
it should survive a reload and needs no server
Which title is open
the URL
a link should open the same title
Where to resume
Opening a title that the viewer has started raises a small question with real edge cases: where should playback begin? The answer is a pure function of the saved progress, so it can be tested without a browser. Starting a few seconds in is not worth a jump, and a title that was watched to the end should start again from the beginning.
ts
const NEAR_START = 10// seconds: too early to resumeconst NEAR_END = 30// seconds: near enough to count as watchedexportfunction resumeAt(p: Progress | null): number {
if (p === null) return0const { positionSec: pos, durationSec: dur } = p
if (!Number.isFinite(pos) || !Number.isFinite(dur)) return0if (dur <= 0) return0if (pos < NEAR_START) return0if (pos >= dur - NEAR_END) return0// watched: start againreturn Math.floor(pos)
}
// the newer record wins, wherever it was savedexportfunction newest(a: Progress | null, b: Progress | null) {
if (a === null) return b
if (b === null) return a
return Date.parse(a.updatedAt) >= Date.parse(b.updatedAt) ? a : b
}
resume.ts: where playback should start.
Two copies of progress can exist, for example one saved on a phone and one on a television. The newer one wins. The driver tries ten inputs, including the ones that real data produces: nothing saved, a position beyond the end, a negative one, and a number that is not a number.
text
never watched -> 04 s in -> 023 minutes in -> 13833 s before the end -> 029 s before the end -> 031 s before the end -> 2669
position past the end -> 0
negative position -> 0
NaN position -> 0
zero duration -> 0
phone 600 s vs tv 900 s, newest: 900
same time, first wins : 1
one side missing : 900
Output (Node 24)
Twenty-three minutes in resumes at 1,383 seconds, rounded down. Four seconds in, three seconds before the end, and 29 seconds before the end all start from zero, and 31 seconds before the end resumes at 2,669, so the boundary is exactly where the constant says. A position past the end, a negative one, a missing number and a duration of zero all start from zero and never throw. For two saved copies, the one with the later updatedAt won, a tie kept the first, and a missing one left the other.
Time stamps from devices come from their own clocks, which can disagree, so a careful server stamps the time itself when it stores progress. The compiler also checks the shape of the input.
text
bad-resume.ts(2,39): error TS2322: Type 'string' is not assignable to
type 'number'.
Output (tsc 7.0.2, --strict)
A viewer was 3 seconds from the end last time. Where does the title start, and why?
At zero. Inside the last 30 seconds counts as watched, so starting there would play only the credits.
The boundary is a constant and the run shows it: 29 seconds before the end gives 0, 31 gives 2,669.
Why does the media element, and not the page, own the current time?
The browser plays the media, so only it knows the true position, including time spent stalled.
The page reads the value and never keeps a second copy that could drift.
Two saved positions came from a phone and a television. Which wins, and what is the weakness?
The one with the later updatedAt wins.
Device clocks can disagree, so a server should stamp the time when it stores progress.
Part 3 · Adaptive streaming
Why the video is cut into pieces
One video file cannot suit every viewer. A phone on a weak signal needs a small file, a television on fibre wants a large one, and the speed of a single viewer changes during a film. The answer is adaptive bitrate streaming: store the video at several bit rates, cut each one into short segments, and let the player choose, segment by segment, which rendition to fetch next.
HLS, HTTP Live Streaming, is one way to do this, described in RFC 8216. It runs over plain HTTP, so a segment is just a small file that any web server or CDN can serve and cache. The description of the stream is also plain text, in two kinds of file called playlists. A multivariant playlist lists the renditions, each with its bit rate, picture size and codecs. RFC 8216 calls this file a master playlist, and the newer draft of the specification calls it multivariant, so you will meet both names. A media playlist lists the segments of one rendition in order.
The files for this chapter come from ffmpeg, with a generated test pattern and a tone as the source, so nothing is downloaded or copyrighted. The script makes one rendition as fragmented MP4 segments of 4 seconds. Fragmented MP4 is a container whose pieces can be appended to a browser buffer one by one, which the player below needs.
make-media.sh: one rendition, 24 s, in 4 s segments.
The keyframe settings, -g 96 and -sc_threshold 0, put a keyframe every four seconds at 24 frames a second and nowhere else. RFC 8216 says a server should divide the source at points where a segment can be decoded on its own, and EXT-X-INDEPENDENT-SEGMENTS (which this lab's playlists carry) declares that every segment can be decoded without the others. For video that means a keyframe at the start of each segment. The RFC also requires every rendition to have the same target duration. It does not demand aligned cut points, but this lab cuts every rendition at the same times, which keeps a switch between renditions clean. The script ran three times: 240p at 250 kbit/s, 360p at 600 kbit/s and 480p at 1,100 kbit/s, which are the targets given to the encoder.
The two playlists
A script wrote the multivariant playlist from the real segment files, so that the numbers in it describe what is on disk. The long lines are wrapped for the page.
BANDWIDTH is the peak segment bit rate of the stream, in bits per second, and AVERAGE-BANDWIDTH is the average, both from RFC 8216. The peak matters most to a player, because a rendition must be sustained through its biggest segment. These came from the segment sizes, so they are higher than the 250 kbit/s the encoder was asked for: the audio is in the file as well, and the encoder's targets are loose. CODECS lets a player skip a rendition it cannot decode. Each rendition has a media playlist.
media playlist for the 360p rendition, first 11 lines.
Tag
What it says
EXT-X-TARGETDURATION
the maximum segment duration, in seconds
EXT-X-MAP
where the initialisation section is: the header a decoder needs before any segment
EXTINF
the duration of the segment named on the next line
EXT-X-ENDLIST
no more segments will be added: this is an on-demand stream, not a live one
Reading playlists and choosing a rendition
The player reads both kinds of playlist with a small parser, and chooses with one rule: take the highest rung whose peak bit rate fits inside a share of the measured throughput. The share, 0.8 here, leaves room for the network to wobble. Starting from the lowest rung means that a very slow network still plays something.
js
const attrs = (line) => {
const out = {}
const text = line.slice(line.indexOf(':') + 1)
for (const m of text.matchAll(/([A-Z0-9-]+)=("[^"]*"|[^,]*)/g)) {
out[m[1]] = m[2].replace(/^"|"$/g, '')
}
return out
}
const lines = (text) => {
const all = text.split(/\r?\n/).map((l) => l.trim()).filter(Boolean)
if (all[0] !== '#EXTM3U') {
thrownew Error('not a playlist: no #EXTM3U')
}
return all
}
hls.mjs: two helpers. Attributes are NAME=value pairs.
js
exportfunction parseMultivariant(text) {
const all = lines(text)
const ladder = []
for (let i = 0; i < all.length; i++) {
if (!all[i].startsWith('#EXT-X-STREAM-INF:')) continueconst a = attrs(all[i])
const uri = all[i + 1]
if (!uri || uri.startsWith('#')) {
thrownew Error('no URI after STREAM-INF')
}
if (!/^\d+$/.test(a.BANDWIDTH ?? '')) {
thrownew Error('no BANDWIDTH')
}
const size = (a.RESOLUTION ?? '0x0').split('x').map(Number)
ladder.push({ bandwidth: Number(a.BANDWIDTH),
width: size[0], height: size[1], codecs: a.CODECS ?? '', uri })
}
if (ladder.length === 0) thrownew Error('no renditions')
return ladder.sort((x, y) => x.bandwidth - y.bandwidth)
}
hls.mjs: the multivariant playlist, lowest rung first.
js
exportfunction parseMedia(text) {
const all = lines(text)
const media = { target: 0, init: null, segments: [], ended: false }
let duration = nullfor (const line of all) {
if (line.startsWith('#EXT-X-TARGETDURATION:')) {
media.target = Number(line.split(':')[1])
} elseif (line.startsWith('#EXT-X-MAP:')) {
media.init = attrs(line).URI
} elseif (line.startsWith('#EXTINF:')) {
duration = Number(line.slice(8).split(',')[0])
if (!(duration > 0)) thrownew Error('bad EXTINF duration')
} elseif (line === '#EXT-X-ENDLIST') {
media.ended = true
} elseif (!line.startsWith('#')) {
if (duration === null) thrownew Error('segment without EXTINF')
media.segments.push({ uri: line, duration })
duration = null
}
}
if (media.segments.length === 0) thrownew Error('no segments')
return media
}
hls.mjs: the media playlist.
js
exportfunction pick(ladder, throughput, share = 0.8) {
let best = ladder[0]
for (const r of ladder) {
if (r.bandwidth <= throughput * share) best = r
}
return best
}
hls.mjs: the choice, one rule.
The parser refuses what it cannot use, with an error that says which part was missing, because a half-read playlist leads to a player that fails in a confusing place later. The driver reads the real files and then feeds in bad text.
text
ladder, lowest first:
240p/index.m3u8 314474 bit/s 426x240
360p/index.m3u8 672862 bit/s 640x360
480p/index.m3u8 1156002 bit/s 854x480
media playlist: 6 segments, target 4 s, init init.mp4 ended true
throughput -> pick (share 0.8)
150000 -> 240p/index.m3u8
400000 -> 240p/index.m3u8
900000 -> 360p/index.m3u8
1500000 -> 480p/index.m3u8
20000000 -> 480p/index.m3u8
bad input:
empty text: not a playlist: no #EXTM3U
no header: not a playlist: no #EXTM3U
no renditions: no renditions
no uri: no URI after STREAM-INF
no bandwidth: no BANDWIDTH
bandwidth is text: no BANDWIDTH
a media playlist: no renditions
media, segment first: segment without EXTINF
media, duration is text: bad EXTINF duration
media, no segments: no segments
a multivariant playlist: segment without EXTINF
CRLF, comma in CODECS, blank line: 500000 avc1.42c01e,mp4a.40.2
https://cdn.example.com/a/index.m3u8
nothing fits: 240p/index.m3u8
Output (Node 24)
The ladder is sorted from the lowest rate. The media playlist has six segments with a target duration of 4 seconds, an init file and an end marker. At 150 kbit/s nothing fits within the share, so the player takes the lowest rung. At 400 kbit/s the 240p rung fits, because 0.8 times 4,00,000 is 3,20,000 and the rung needs 3,14,474. At 900 kbit/s it takes 360p, and from 1.5 Mbit/s up it takes 480p. Each bad input was refused with a message that says what was missing: empty text, no header, no renditions, a missing address, a missing or non-numeric bit rate, a duration that is not a number, no segments, and a media playlist handed to the multivariant parser or the other way round. A playlist with Windows line endings, a blank line, and a quoted CODECS value that contains a comma was read correctly. This parser covers only what the lab files use: no byte ranges, discontinuities, encryption or live playlists, and it needs the RFC for those.
Why does the lab put a keyframe at the start of every segment of every rendition?
A segment that starts on a keyframe can be decoded on its own, which is what EXT-X-INDEPENDENT-SEGMENTS declares.
With every rendition cut at the same times, the player can change rung between any two segments without a gap or an overlap.
Why is the peak bit rate, and not the average, used to choose a rung?
The rendition must be sustained through its biggest segments.
A rung chosen by its average would stall on every large segment.
At 150 kbit/s the run chose 240p, which needs 314 kbit/s. Why?
Nothing fits inside the share, so the rule falls back to the lowest rung.
Starting from the lowest rung means that a very slow network still plays something.
Part 4 · A player on MediaSource
MediaSource and a segment loop
Browsers play HLS natively in some places and not in others, so a page that wants control builds the player itself with Media Source Extensions (MSE). The page creates a MediaSource, hands the video element a link to it, creates a SourceBuffer for the media type, and appends bytes. MDN describes MSE as giving finer control over how much content is fetched and how often. The first check is whether the browser can play the type at all.
In Chrome 157 here, MediaSource.isTypeSupported('video/mp4; codecs="avc1.42c01e,mp4a.40.2"') returned true. The page first needs a place to fetch from. The loader below remembers every answer by address, so that the warm-up in the catalogue lesson and the player share one set of requests. It checks the status, because fetch does not fail on a 404: the error page would otherwise be handed to the buffer as if it were video. It tries a failed request once more, and it does not remember a failure, so the next call asks again. Addresses in a playlist are relative to the playlist that names them, so the player resolves them with new URL(address, playlistUrl) and never by cutting up strings.
js
exportfunction createLoader({ tries = 2 } = {}) {
const memo = new Map()
const fetchOnce = async (url) => {
const res = await fetch(url)
if (!res.ok) thrownew Error(`${res.status} for ${url}`)
return res.arrayBuffer()
}
const fetchRetry = async (url) => {
for (let attempt = 1; ; attempt++) {
try { returnawait fetchOnce(url) } catch (e) {
if (attempt >= tries) throw e
awaitnew Promise((r) => setTimeout(r, 200 * attempt))
}
}
}
const bytes = (url) => {
if (!memo.has(url)) {
const p = fetchRetry(url)
memo.set(url, p)
p.catch(() => memo.delete(url)) // a failure is not remembered
}
return memo.get(url)
}
return { bytes, has: (url) => memo.has(url),
text: async (url) => new TextDecoder().decode(await bytes(url)) }
}
player.mjs: one place that fetches, so that answers are shared and failures are not.
player.mjs: playlist addresses, then a MediaSource and a way to append to it.
Appending is asynchronous. The buffer accepts one chunk at a time and fires updateend when it is ready for the next, so append returns a promise for that event. The loop below does the real work for each segment: pick a playlist, append the init section if the rendition changed, fetch the segment and time it, update the throughput, append, and choose the rung for the next one. If anything throws, the catch ends the stream with the network error, so that the video element fires its own error event and the controls can show it.
js
for (let i = 0; ; i++) {
const rungUrl = at(rung.uri, masterUrl)
const list = (media[rungUrl] ??=
parseMedia(await loader.text(rungUrl)))
if (i >= list.segments.length) breakif (shown !== rung) { // a new rendition needs its initif (!list.init) thrownew Error('no EXT-X-MAP: fMP4 only')
await append(await loader.bytes(at(list.init, rungUrl)))
shown = rung
}
const url = at(list.segments[i].uri, rungUrl)
const warm = loader.has(url) // an answer we already hadconst t0 = performance.now()
const data = await loader.bytes(url)
const secs = (performance.now() - t0) / 1000const bps = data.byteLength * 8 / secs
if (!warm) {
const smooth = throughput ? 0.5 * throughput + 0.5 * bps : bps
throughput = rule === 'cautious'
? Math.min(smooth, bps) : smooth
}
await append(data)
log({ i, rung: `${rung.height}p`, warm,
kb: Math.round(data.byteLength / 1024),
kbps: Math.round(bps / 1000), ahead: +ahead().toFixed(1) })
if (i === 0 && play) video.play()
if (throughput) rung = pick(ladder, throughput)
}
ms.endOfStream()
player.mjs: the segment loop.
js
} catch (e) {
// tell the element, so that it fires `error` for the controlsif (ms.readyState === 'open') ms.endOfStream('network')
throw e
}
}
player.mjs: a failure ends the stream with an error.
Stepping down when the network falls
The throughput estimate has a rule of its own. The first version averaged each new measurement with the old estimate, half and half. The second takes the lower of the average and the latest measurement, so it believes bad news at once. A local server sends each segment at a fixed rate, 4 Mbit/s at first, and the driver drops it to 500 kbit/s after the third segment. The player runs once with each rule.
text
rule: average (rate drops to 500 kbit/s after segment 2)
seg rung kB kbit/s buffered (s)
0 240p 154315241 480p 551317582 480p 5583233123 480p 555421164 480p 564406205 360p 31740524
Output (Chrome 157, lab, this machine): averaged
text
rule: cautious (rate drops to 500 kbit/s after segment 2)
seg rung kB kbit/s buffered (s)
0 240p 154309841 480p 551319182 480p 5583237123 480p 555422164 240p 148405205 240p 14440224
Output (Chrome 157, lab, this machine): cautious
Both climb from 240p to 480p after the first segment, when the measure is about 3 Mbit/s. After the drop, the segment that was already requested at 480p crawls in at about 420 kbit/s with either rule, and nothing can speed that up. The averaged rule then fetched a second slow 480p segment, because half of the old, fast estimate was still in the average, and stepped down only at the sixth. The cautious rule dropped to 240p straight after the first slow segment. The numbers vary by a few per cent between runs, and the order does not.
A segment that is gone
The first version of the loader had no status check, and a test with a missing segment found it. The driver makes the 480p segment 2 answer 404 in the browser, once in one run and every time in another, and plays at 8 Mbit/s.
When the 404 came once, the retry fetched the segment and all six segments were appended, with two requests for the one address. When it came every time, the player stopped after two segments with the error naming the status and the address, and the video element reported error code 2, which is a network error, so the controls reach their error state. In the first version, run with the every-time case, the four-byte error body was appended as if it were segment 2. Nothing failed, four seconds of video were missing, and the tiny body made the throughput estimate collapse, so the player dropped to 240p for nothing. A player that appends whatever it is given hides the fault where it happened.
The step down, in scenes
Animated sceneA slow segment, and a step down0:24
Watch for the slow segment that makes the player step down
Read it as steps
The player climbs while the network is good and drops after one slow segment.
Animated sceneChoosing the rung for the next segment0:16
Next segment from: 240p (the only rung whose peak fits the planned rate)
Read it as steps
The planned rate is the measure times 0.8. Only 240p fits.
The estimate scene shows why. At about 420 kbit/s a 480p segment takes about 11 seconds to arrive and holds four seconds of video, so the buffer drains. A 240p segment arrives in about three. The segment length is a trade-off in its own right: shorter segments let the player react sooner, and cost more requests and more headers.
In the run, why did the averaged rule fetch a second slow segment at 480p?
Half of the estimate was still the old fast measurement, so the average stayed high after one slow segment.
Taking the lower of the average and the latest measurement believes bad news at once.
Why must the player append the init section again when it changes rung?
The init section is the header a decoder needs, and each rendition has its own.
Without it the segments of the new rendition could not be decoded.
The segment that was already on its way when the network fell could not be sped up. What does that say about segment length?
A shorter segment limits the damage of a drop, because less is in flight at any moment.
It also means more requests and more headers, so the length is a trade-off.
Part 5 · Deep dive: the player
From events to states
The video element does not have a "state" property that says "buffering". It fires events, and the controls need a state. The first job of a player is to fold the events into a small set of states that the screen can show: idle, loading, playing, buffering, paused, ended and error. The page wires the events to a log, and a function turns each event into the next state.
controls.html: the markup the player code works on.
js
exportfunction next(state, name, { paused }) {
switch (name) {
case'loadstart': return'loading'case'error': return'error'case'ended': return'ended'case'playing': return'playing'case'waiting': return state === 'loading' ? 'loading' : 'buffering'case'canplay':
return state === 'loading' || (state === 'buffering' && paused)
? 'paused' : state
case'pause': return state === 'ended' ? 'ended' : 'paused'default: return state // play, seeking, seeked: no change
}
}
states.mjs: the media element's events, folded into states.
Two events need the element's paused flag. A seek on a paused video fires waiting and then canplay, and the state must go back to paused, not to playing. And pause fires just before ended, so ended wins. The driver runs a real clip through seven scenarios in Chrome and applies the function to the events as they arrive.
The run, and the scene
text
load loadstart loadedmetadata canplay
-> loading, paused
play play playing
-> playing
seek, playing seeking waiting seeked canplay playing
-> buffering, playing
pause pause
-> paused
seek, paused seeking seeked canplay
-> (no change)
to the end seeking play waiting seeked canplay playing pause ended
-> buffering, playing, paused, ended
bad source loadstart error
-> loading, error
final state: error
Output (Chrome 157)
Loading fired loadstart and then canplay, which gave loading and then paused. A click gave playing. A seek while playing fired waiting and then playing again, which is buffering and back. A seek while paused fired no waiting event, which fits a clip from a local server whose data was already in the buffer. Playing to the end passed through buffering, playing, paused and then ended. A broken source went to loading and then error.
Animated sceneThe states of a player0:23
Watch for the buffering state that a seek or a slow network causes
Read it as steps
The events of a real run, folded into states. A seek and a slow network both cause buffering.
The scene follows that run. Buffering appears twice in it, for a seek. A slow network causes it as well, which the adaptive streaming lessons measured.
Starting: preload
The preload attribute tells the browser how much to fetch before the viewer presses play. MDN calls it a hint that the browser is free to ignore, and says the default differs between browsers. The three values are none, metadata and auto. The driver opens the 20-second, 1.6 MB lab clip with each value, ten times, each in a new page, waits 1.5 seconds without playing, and counts what Chrome received.
text
preload KB received (10 runs, sorted) buffered s (10 runs, sorted)
none 00000000000.00.00.00.00.00.00.00.00.00.0
metadata 38238238238242072810241024114912124.84.84.84.85.28.912.812.814.314.7
auto 160616061606160616061606160616061606160620.020.020.020.020.020.020.020.020.020.0
Output (Chrome 157, this machine)
With none nothing was fetched and the element had no data. With auto Chrome fetched the whole file every time. With metadata it fetched between 382 and 1,212 KB, and buffered between 4.8 and 14.7 seconds, with four runs at the bottom of the range and the rest scattered above it. Other runs of the same script gave as little as 125 KB. That is enough to know the duration and to draw a frame, and the amount differs each time, which is the meaning of "hint". These are Chrome's choices on one machine, and another browser may do something else. The design consequence is for the catalogue: a title page with a player in it can use metadata to show the first frame and the duration cheaply, and none for the many players on a page that the viewer may never touch.
MDN notes that modern browsers block video with an unmuted audio track from playing on its own, so the lab pages use muted, and a real player starts on a click or a tap.
Captions
Captions are text tracks. A <track> element inside the video points to a WebVTT file: a text file that starts with the word WEBVTT, followed by cues, each with a start time, an end time and the text. The file for this chapter is nine lines.
text
WEBVTT
00:00:00.500 --> 00:00:03.000
Welcome to the sample clip.
00:00:04.000 --> 00:00:07.000
The test pattern is made on this machine.
00:00:09.000 --> 00:00:12.000
These captions come from a WebVTT file.
captions-en.vtt
The kind says what the track is for: captions include sound cues as well as speech, and subtitles translate speech. MDN says srclang must be defined when kind is subtitles, and the lab sets it on both tracks. Only one track per media element may carry default. The driver lists the tracks, switches one on, reads what is showing at one second, and then adds a track whose file has no header.
text
tracks after load:
captions/en showing cues=3
subtitles/hi disabled cues=none
after hidden on hi:
captions/en showing cues=3
subtitles/hi hidden cues=3
at 1 s, active cue (en): Welcome to the sample clip.
at 1 s, active cue (hi): नमूना क्लिप में आपका स्वागत है।
at 3.5 s, active cues : 0
file without header : error event, readyState 3
Output (Chrome 157)
The English track was showing with three cues, because of default. The Hindi track was disabled and had no cues at all: a disabled track is not even loaded. Setting its mode to hidden loaded the three cues without drawing them, which is how a custom caption display reads cues. showing lets the browser draw them. At one second the English cue and the Hindi cue were the two lines of the same moment, and at 3.5 seconds, between cues, there were none. A file without the WEBVTT line fired an error event and ended with readyState 3, which is "error", so a player should listen for it and tell the viewer the captions did not load.
Keyboard controls
A video player is a widget, and widgets must work by keyboard. The usual keys are Space or K to play and pause, the arrow keys to seek five seconds, and M to mute. They are handled on the player's container. The first version of the handler had a bug that a short run found.
controls.html, script: the key handler. The lab page keeps a flag to run it with and without the check.
text
ArrowRight t=5 paused=true muted=true
m t=5 paused=true muted=false
Space t=5 paused=false muted=false
Space again t=5 paused=true muted=false
typing "a b", first version : "ab", playing=true
typing "a b", with the check: "a b", playing=false
Output (Chrome 157)
The first four lines are the handler working on the player: the arrow moved the clip from 0 to 5 seconds, m unmuted it, Space started it and Space again paused it. The last two lines show the bug. A note box sits inside the player, and a viewer typing "a b" in it triggered the handler on the space: the text became "ab", and the video started playing. With the check that leaves typing and buttons alone, the text was "a b" and the video stayed paused. A handler on a container sees the keys of everything inside it, so it must look at where the key came from. A second bug showed up when the keys were pressed before the video had metadata: its duration is NaN, and assigning NaN to currentTime throws a TypeError. The seek now returns early until the duration is a finite number, and play() is given a catch because it returns a promise that rejects when there is nothing to play.
Why does the state function need the element's paused flag for the canplay event?
After a seek on a paused video, canplay arrives and the state must return to paused.
After a seek on a playing video, a playing event follows, so the state stays buffering until then.
In the run the Hindi track had no cues until its mode was set. Why?
A disabled track is not loaded. Hidden loads the cues without drawing them.
Showing draws them, and the English track was showing because of default.
What went wrong when the viewer typed a space in the note box, and what fixes it?
The handler on the container saw the space, called preventDefault and toggled playback.
Return early when the key comes from a button or an input.
Part 6 · Deep dive: the catalogue and a fast start
A grid of thumbnails
The catalogue is the page the viewer sees first, and it is a list like the one in the news feed chapter. Titles come as pages from a cursor API, each row on the page (new releases, continue watching) is its own list, and rows below the first screen load when they come near. The new part is what each card carries: a thumbnail, a name and a duration.
The thumbnail is most of the weight of the page. A card is about 160 CSS pixels wide on a phone, and a sharp thumbnail for a screen with three device pixels per CSS pixel needs three times that many pixels across. The performance chapter worked out srcset and sizes. Here they are applied to the card, with candidates 160, 320, 480 and 640 pixels wide, and a slot that is 45% of the viewport on a phone and 220 CSS pixels on a wide screen.
The script opens the page at four screen settings and reads which file the browser chose. A phone 360 pixels wide at three device pixels per pixel has a 162-pixel slot, needs 486 pixels, and took the 640 file. At two device pixels it needed 324 and took 480. A 1280-pixel desktop at one device pixel needed 220 and took 320. The same slot at two device pixels needed 440 and took 480. MDN says the user agent chooses among the candidates at its discretion. Chrome here took the smallest candidate that was at least as wide as the need, and another browser may choose differently. The saving is a few kilobytes per card, and a card grid of thirty adds up. The alt is empty because the title's name sits next to the picture, and the width and height are there for the layout shift reason from the news feed chapter.
Starting before the click
Starting a video takes several round trips: the multivariant playlist, a media playlist, the init section and the first segment. The cold run on the next page spent about 870 ms on these against a local server, and a real network adds its own latency to each. The viewer's intent shows before the click. A pointer that rests on a card for a few hundred milliseconds, or a card that gets keyboard focus, is a strong hint. The page can fetch the playlists and the first segment of the lowest rung then, and keep the answers for the player to use.
js
exportfunction onIntent(card, warm, delay = 300) {
let timer = nullconst enter = (e) => {
if (saveData()) return// the viewer wants less dataif (e.pointerType && e.pointerType !== 'mouse') return// no hover
clearTimeout(timer)
timer = setTimeout(warm, delay)
}
const leave = () => clearTimeout(timer)
card.addEventListener('pointerenter', enter)
card.addEventListener('pointerleave', leave)
card.addEventListener('focus', enter)
card.addEventListener('blur', leave)
}
intent.mjs: warm things up when a pointer or focus rests on a card.
Four rules are in that function. It waits 300 ms, so a pointer sweeping across the grid starts nothing. It cancels if the pointer leaves first. It ignores touch, where pointerenter fires on the press and there is no hover to read. And it does nothing when navigator.connection.saveData is true, which is how some browsers let a viewer ask for less data. MDN lists navigator.connection as limited availability, so it is a hint that exists in some browsers only. The player and the warm-up share one loader that remembers each answer, so the warm-up's fetches are the player's.
text
what the hover did requests
rested 100 ms, then left 0
rested 900 ms 4 /master.m3u8 /240p/index.m3u8
/240p/init.mp4 /240p/seg0.m4s
keyboard focus for 900 ms 4
Save-Data on, rested 900 ms 0
Output (Chrome 157)
The driver loads a page with one card and tries four things. A pointer that rested 100 ms and then left made no requests. One that rested 900 ms made four: the multivariant playlist, the 240p playlist, its init section and its first segment. Keyboard focus for 900 ms made the same four. With Save-Data switched on, nothing was fetched. The lab page sets navigator.connection.saveData to true by script, since headless Chrome has no data-saver setting to switch.
What it bought, and what it cost
The second part of the driver measures the time from the click to the first segment appended, with and without the warm-up. Each sample uses a fresh browser, because repeated media pages in one browser crashed the renderer in an earlier version of this run. The server sends segments at 2 Mbit/s.
text
ms from click to first segment (5 runs each, sorted)
cold 863868888894896
warm 44666
Output (Chrome 157, lab, this machine, 2 Mbit/s)
Without the warm-up the first segment arrived 863 to 896 ms after the click in five runs, and a second run of five gave 868 to 878 ms. With the warm-up it took 4 to 6 ms in both, because every answer was already in the loader. The click had nothing left to wait for except the append. These are lab numbers on one machine against a local server, and a real network makes the gap larger, since each of the four requests has its own round trip.
The cost is also real, and it is paid by the viewer. The warm-up fetched a 154 KB segment and three small files for a title that the viewer might never open, and the ladder lesson showed what 154 KB is worth on a small plan. A sensible policy is narrow: warm only one title at a time, only the lowest rung, only after a real pause, and never on Save-Data or on touch. Stopping at the first segment keeps the waste to what the run fetched: one 154 KB segment and three small files.
Why does the warm-up wait 300 ms before fetching?
A pointer that sweeps across the grid would otherwise start a download for every card it crosses.
The run shows it: resting 100 ms made no request, resting 900 ms made four.
Why does the card ignore touch for the warm-up?
A touch has no hover, and pointerenter fires when the finger lands, so it would warm every tapped card.
Keyboard focus is a second signal that works for people who do not use a pointer.
The warm start took 4 to 6 ms and the cold start about 870. What does that gap not tell you?
How a real network behaves. These are lab numbers against a local server, and a real network adds a round trip to each request.
It also does not show the cost: the bytes fetched for titles the viewer never opens.
Part 7 · Progress, checks and trade-offs
Saving where the viewer is
Resuming needs progress to be saved on a timer while the video plays, and at the moment the viewer leaves. The second case is the hard one, because a closing page cannot be trusted to finish a normal request. MDN's advice is to send the data from a visibilitychange handler when the page becomes hidden, using navigator.sendBeacon(), which queues a small POST (the total payload is limited to 64 KiB) and lets the browser send it without holding up the next page.
js
exportfunction trackProgress(video, titleId, every = 10000) {
// a counter that restarts at 0 on every page load is older than the// server's last save, so it is kept across loadsconst key = `progress-seq:${titleId}`let seq = Number(localStorage.getItem(key) ?? 0)
const save = () => {
localStorage.setItem(key, String(++seq))
const body = JSON.stringify({ titleId, seq,
positionSec: Math.floor(video.currentTime) })
// sendBeacon queues the request and survives the page going awayconst queued = navigator.sendBeacon('/api/progress',
new Blob([body], { type: 'application/json' }))
// false: not queued, so fall back to a normal requestif (!queued) fetch('/api/progress', { method: 'POST', body,
keepalive: true }).catch(() => {})
}
const timer = setInterval(() => { if (!video.paused) save() }, every)
const onHide = () => {
if (document.visibilityState === 'hidden') save()
}
document.addEventListener('visibilitychange', onHide)
// a plain request with a chosen seq, to play the part of a late tabconst send = (seq, positionSec) => fetch('/api/progress', {
method: 'POST',
body: JSON.stringify({ titleId, seq, positionSec }) })
return { save, send, stop: () => {
clearInterval(timer)
document.removeEventListener('visibilitychange', onHide)
} }
}
progress.mjs: save on a timer and when the page is hidden.
Each save carries a sequence number that only goes up. Requests can arrive out of order, for example from a second tab, so the server keeps the highest number and ignores older ones. The driver plays the clip with a one-second timer, sends a late request with an old number, and then navigates away.
text
after 3.6 s of playing, saved by the timer:
seq 1 at 0 s: saved
seq 2 at 1 s: saved
seq 3 at 2 s: saved
a late save from an older tab:
seq 1 at 1 s: ignored, older
after leaving the page:
seq 4 at 3 s: saved
stored position: 3 s, seq 4
the next visit, 2.5 s of playing:
seq 5 at 1 s: saved
seq 6 at 1 s: saved
Output (Chrome 157)
The timer saved three times, at 0, 1 and 2 seconds. A late save from an older tab, number 1, arrived after number 3 and was ignored. Leaving the page sent a final save, number 4 at 3 seconds, from the hidden handler. A plain fetch in the handler would also have arrived here, because a loopback server answers in a millisecond. The reason to prefer a beacon is the guarantee on slow networks, which MDN gives and this lab cannot measure.
Two details came from a probe. The sequence number is kept in localStorage, not in a variable: a counter that restarts at 1 on every page load is older than the server's last save, so the first saves of the next visit would be ignored. The run ends with the second visit: the first version printed ignored, older for its saves, which restarted at 1, and the fixed one saved seq 5 and seq 6. And sendBeacon returns false when the browser could not queue the request, so the code then falls back to a fetch with keepalive, which MDN names as the alternative. Two tabs that share a counter can still collide, so a server that must be exact stamps the order itself.
Measuring the experience
A design needs a way to say whether it works. For video the measures are about what the viewer felt: how long the start took, how often playback stopped, and how long it stayed stopped. A short function computes them from the events and segments that the player already has.
js
exportfunction qoe(startAt, events, segments, segSeconds = 4) {
const first = events.find(([, n]) => n === 'playing')
if (!first) return { startupMs: null, note: 'never started' }
let stalls = 0, stallMs = 0, since = null, seeking = falsefor (const [t, name] of events) {
if (t < first[0]) continueif (name === 'seeking') seeking = trueif (name === 'waiting' && !seeking) { stalls++; since = t }
if (name === 'playing') {
if (since !== null) stallMs += t - since
since = null
seeking = false
}
}
const last = events[events.length - 1][0]
if (since !== null) stallMs += last - since // stalled at the endconst watchMs = last - first[0]
const kbit = segments.reduce((a, s) => a + s.kb * 8 * 1.024, 0)
return {
startupMs: Math.round(first[0] - startAt),
stalls, stallMs,
rebufferRatio: +(stallMs / watchMs).toFixed(3),
switches: segments.filter((s, i) =>
i && s.rung !== segments[i - 1].rung).length,
avgKbps: Math.round(kbit / (segments.length * segSeconds)),
}
}
qoe.mjs: start time, stalls, rebuffer ratio from a playback log.
A waiting event that follows a seek is the viewer's own action, so it is not a stall, and a stall still going when the log ends is counted up to the last event. The driver plays the six-segment lab video, drops the network to 300 kbit/s after the third segment, and lets the buffer play out.
text
events (ms from start):
486 waiting
533 playing
12550 waiting
21737 playing
25743 waiting
26745 playing
30714 waiting
31626 playing
35706 pause
35706 ended
segments: 0:240p 1:480p 2:480p 3:480p 4:240p 5:240p
{
startupMs: 533,
stalls: 3,
stallMs: 11101,
rebufferRatio: 0.316,
switches: 2,
avgKbps: 720
}
Output (Chrome 157, lab, this machine, the first of three runs)
text
run startupMs stalls stallMs rebufferRatio switches
15333111010.316221301398020.289235283106650.3072
The three runs
What the run says
The first frame came after about half a second. The first stall began at 12.6 seconds, when the playhead reached the end of the 12 seconds already buffered. The fourth segment, a 555 KB file at 480p, had been requested just before the network fell, and it had not arrived. Playback resumed at 21.7 seconds, and two shorter stalls followed at 240p. The player chose 240p after the slow segment, as designed, but even the lowest rung needs more than 300 kbit/s of the network, because its peak rate is 314 kbit/s.
Three stalls and 11.1 seconds of waiting in 35.2 seconds of watching is a rebuffer ratio of 0.316, which is a long way from the 1% target. Two more runs gave 0.289 and 0.307 with the same three stalls, and starts of 1.3 s and 528 ms. The run is deliberately cruel; the metric catches what the eye would and points at the causes. The segment in flight at the collapse could not be cancelled, the buffer was only twelve seconds deep, and the lowest rung was not low enough. Each is a design lever: a shorter segment limits the damage of a drop, a deeper buffer on a good network gives more room, and a lower rung gives the player somewhere to go.
The lab player does not abandon a slow request and start the same segment at a lower rung. That is the most useful next step.
Checks and trade-offs
Check
For this player
Performance
a low first rung, a warm-up on intent, thumbnails with srcset, a buffer target of ten to twenty seconds
Accessibility
captions on and off by keyboard, every control named, keys that do not steal typing
Internationalisation
caption languages by choice; the interface and durations in the viewer's language
Security
links to segments that expire, checked by the CDN; DRM named, not built; no tokens in the page URL
Observability
report start time, stalls, rebuffer ratio, rung changes and playback errors by title and rung
Choice
Alternative rejected
Reason
What it costs
Adaptive segments over HTTP
one progressive file
the network changes during a title
playlists, a loader and a player to build
A player on MediaSource
the browser's own HLS support
the same behaviour in every browser we target
we own the buffering rules
Start on the lowest rung
start on the highest
a bad guess costs a little
a soft picture for the first segment
Believe bad news at once
average every measurement
a drop is noticed after one segment
a rung may flip on one slow reply
Warm up on intent
fetch nothing until the click
a start in a few milliseconds
bytes for titles that are not opened
Beacon on hide
save only on a timer
the last seconds are not lost
a small request on every exit
Adaptive segments over HTTP
Alternative rejectedone progressive file
Reasonthe network changes during a title
What it costsplaylists, a loader and a player to build
A player on MediaSource
Alternative rejectedthe browser's own HLS support
Reasonthe same behaviour in every browser we target
What it costswe own the buffering rules
Start on the lowest rung
Alternative rejectedstart on the highest
Reasona bad guess costs a little
What it costsa soft picture for the first segment
Believe bad news at once
Alternative rejectedaverage every measurement
Reasona drop is noticed after one segment
What it costsa rung may flip on one slow reply
Warm up on intent
Alternative rejectedfetch nothing until the click
Reasona start in a few milliseconds
What it costsbytes for titles that are not opened
Beacon on hide
Alternative rejectedsave only on a timer
Extensions follow from the run. Abandon a slow segment and refetch it lower. Use the Network Information API's hints for the first rung, where the browser offers them. Preload the next episode near the end of the current one. Add a quality menu that caps the ladder. And for protected content, integrate DRM through the browser's own interface, which is a separate project.
A second tab saved progress after the first, but its request arrived earlier. Which save does the server keep, and why?
The one with the higher sequence number, so a late older request cannot overwrite a newer one.
The run shows number 1 arriving after number 3 and being ignored.
Why does the quality-of-experience function ignore a waiting event that follows a seek?
The viewer caused it, so it is not the player failing to keep up.
Counting it would make a rebuffer ratio depend on how much someone scrubs.
In the run the rebuffer ratio was 0.316. Name two design levers that would have lowered it.
Shorter segments, so a drop costs less, and a deeper buffer while the network was good.
Abandoning the slow segment and refetching it at a lower rung is a third.