Sub topic 11
How adaptive bitrate playback works
Adaptive bitrate (ABR) playback lets a video player change quality while the video plays. The player switches between the renditions you built earlier, so the stream keeps going when the network slows down and looks better when the network recovers. This chapter covers the client-side logic and what it requires from the rest of the platform.
This chapter assumes you know what a bitrate ladder is, how HLS or DASH segments and playlists are laid out, and that segments are served over plain HTTP through a CDN. You should be able to read short Python snippets.
The core idea: the player decides
In HLS and DASH, the server does not push a chosen quality to the client. The server only publishes files: a master playlist (or DASH manifest) and many short segments per rendition. Every decision about which rendition to fetch next is made by the player.
This has three consequences for your design:
- The origin and CDN stay stateless. They serve cacheable files and do not track viewers' quality.
- Adding viewers does not add per-viewer server logic. It adds only bandwidth.
- Playback quality depends heavily on client code, so you need client-side metrics to see problems (covered in the observability chapter).
The playback loop
A player repeats the same cycle for the whole session.
Step by step:
- The player downloads the master playlist and learns which renditions exist, with their
BANDWIDTH,RESOLUTIONandCODECS. - It drops renditions the device cannot decode or display. It checks
CODECSagainst what the hardware supports and may cap resolution at the screen size. - It picks a starting rendition and downloads that rendition's media playlist.
- It fetches segments in order and appends them to a buffer, which is the video already downloaded but not yet played.
- After each segment, it re-evaluates which rendition to request next.
Switching works only because of the packaging choices made earlier. Every segment starts on a keyframe (the -g 48 -keyint_min 48 -sc_threshold 0 flags in the transcoding example), and segment boundaries line up across renditions. The player can therefore request segment 17 from 720p after segment 16 from 360p, and the decoder starts cleanly. If keyframes drifted between renditions, switches would produce glitches or stalls.
Measuring throughput
The simplest signal is how fast the last segment arrived:
sample (bits per second) = segment size in bits / download time in secondsA single sample is noisy. A CDN cache miss, a TCP slow start, or a brief Wi-Fi dip can make one segment look much slower or faster than the connection really is. Players therefore smooth samples, commonly with an exponentially weighted moving average (EWMA). Many use two averages, a fast one and a slow one, and take the lower of the two, so a drop in speed is noticed quickly but a spike does not cause over-optimism.
Throughput measurement has known pitfalls:
- Small segments finish before TCP reaches full speed, so they underestimate capacity.
- A player that is already full (see the buffer section) idles between requests. The idle gaps do not affect the sample, but throughput measured on short on/off bursts can still differ from sustained throughput.
- Measuring only the body download time and ignoring time to first byte hides slow origins. Cache misses show up as latency before any data arrives.
A throughput-based rule
The most direct strategy picks the highest rendition that fits under the measured throughput, with a safety margin. The margin exists because the estimate is a prediction about the next few seconds, and bitrate is an average. A 3 Mbps rendition has segments that are larger than average during complex scenes.
def pick_rendition(renditions, throughput_bps, safety=0.8):
"""renditions: list of dicts sorted by ascending 'bandwidth' (bits per second)."""
usable = throughput_bps * safety
best = renditions[0]
for r in renditions:
if r["bandwidth"] <= usable:
best = r
return best
ladder = [
{"name": "360p", "bandwidth": 800_000},
{"name": "720p", "bandwidth": 3_000_000},
{"name": "1080p", "bandwidth": 6_000_000},
]
print(pick_rendition(ladder, 4_500_000)["name"]) # 720pAt 4.5 Mbps measured throughput, the usable budget is 3.6 Mbps. That fits 720p (3 Mbps) but not 1080p (6 Mbps). If throughput falls below 1 Mbps, the function falls back to 360p, the lowest rendition, even if that does not fit. Returning the lowest rendition is the right fallback because there is nothing cheaper to switch to.
The buffer as a second signal
Throughput alone causes problems. The estimate can swing, which makes quality oscillate, and it says nothing about how much cushion the viewer has. The buffer level answers a different question: how long can the player survive a slow download before playback stalls?
Buffer-based algorithms treat buffer occupancy as the main input:
- When the buffer is low, choose a low rendition so segments download quickly and the buffer refills.
- When the buffer is high, there is room to take risks, so choose a higher rendition.
Most production players combine both signals. They use throughput to propose a rendition and the buffer to veto or allow the move. The following code adds an estimator and two buffer rules to the previous function:
class ThroughputEstimator:
def __init__(self, alpha=0.3):
self.alpha = alpha
self.estimate = None
def add_sample(self, size_bytes, seconds):
sample = size_bytes * 8 / seconds
if self.estimate is None:
self.estimate = sample
else:
self.estimate = self.alpha * sample + (1 - self.alpha) * self.estimate
return self.estimate
def pick_rendition(renditions, throughput_bps, safety=0.8):
usable = throughput_bps * safety
best = renditions[0]
for r in renditions:
if r["bandwidth"] <= usable:
best = r
return best
def choose(renditions, throughput_bps, buffer_s, current,
safety=0.8, panic_s=5, up_switch_s=10):
# Buffer nearly empty: drop to the lowest rendition immediately.
if buffer_s < panic_s:
return renditions[0]
target = pick_rendition(renditions, throughput_bps, safety)
# Do not switch up until the buffer is comfortable.
if target["bandwidth"] > current["bandwidth"] and buffer_s < up_switch_s:
return current
return target
ladder = [
{"name": "360p", "bandwidth": 800_000},
{"name": "720p", "bandwidth": 3_000_000},
{"name": "1080p", "bandwidth": 6_000_000},
]
est = ThroughputEstimator()
bps = est.add_sample(size_bytes=1_500_000, seconds=2.0) # 6 Mbps sample
print(choose(ladder, bps, buffer_s=12, current=ladder[1])["name"]) # 720p
print(choose(ladder, bps, buffer_s=4, current=ladder[1])["name"]) # 360pIn the first call, the 6 Mbps estimate gives a 4.8 Mbps budget, so 720p is chosen. The player cannot reach 1080p because 6 Mbps exceeds the budget. In the second call, the buffer is under the 5 second panic threshold, so the player drops to 360p regardless of throughput.
Startup and switching behavior
Startup
The player has no throughput history at the start. Common choices are a low initial rendition for fast first frame, or a rendition chosen from a cached estimate from the previous session. Starting low gives a quick start, and the player climbs after the first few segments. Starting high risks a long wait for the first frame.
Up-switch and down-switch asymmetry
Good players switch down quickly and up slowly. A stall (rebuffering) is far more annoying than a few seconds of lower quality. Common techniques include:
- Require several consecutive segments with enough headroom before switching up.
- Switch down after a single slow segment if the buffer is low.
- Add hysteresis, meaning different thresholds for going up and going down, so the player does not flip back and forth at a boundary.
Abandoning a download
If a segment is taking far longer than expected, a player can cancel the request and re-request that segment from a lower rendition. This costs the bytes already received but avoids a stall.
What the platform must provide
ABR only works if the server side cooperates:
| Requirement | Why the player needs it |
|---|---|
| Aligned keyframes across renditions | Clean switches at segment boundaries |
| Consistent segment duration (for example 4 seconds) | Predictable buffer math and switch points |
| Accurate `BANDWIDTH` and `CODECS` in the master playlist | Correct filtering and selection |
| Cacheable segments with long TTLs | Cache hits keep time to first byte low and throughput samples honest |
| A ladder with sensible gaps between steps | Each switch is a visible improvement, not a tiny change |
Segment duration involves a trade-off. Short segments (2 seconds) let the player react quickly and start fast, but they increase request count, playlist size and per-request overhead. Long segments (10 seconds) reduce overhead but make adaptation sluggish. Four to six seconds is a common middle ground.
Common errors
- Trusting a single throughput sample, which causes constant quality flapping.
- Switching up too eagerly after a startup burst from a warm CDN cache, then stalling on the next cache miss.
- Ignoring the device. A phone with a small screen gains nothing from 1080p, and a decoder without support for a codec cannot play that rendition at all.
- Serving manifests with the wrong cache headers. A master playlist cached for too long hides a ladder change, and a media playlist (for live) cached too long stalls playback.
Exercise
A player has a 4 second buffer, a measured throughput of 10 Mbps, and is currently playing the 720p rendition from the ladder above. Using the choose function with default settings, which rendition is requested next, and why?
Show answer
360p. The buffer (4 s) is below the 5 s panic threshold, so choose returns the lowest rendition immediately, even though the throughput would otherwise allow 1080p. A nearly empty buffer means a stall is the main risk, so the player prioritizes fast downloads to refill it.
Exercise
Why does ABR depend on keyframes being aligned at the same timestamps across all renditions?
Show answer
Switching renditions happens at segment boundaries. Each segment must start with a keyframe so the decoder can start without earlier frames. If renditions had keyframes at different times, segment boundaries would not match across renditions, and switching would cause visual glitches or require extra downloading.