Sub topic 18
Adaptive streaming and Media Source Extensions
This chapter assumes you know the video element, the src attribute, the HTMLMediaElement API, fetch, promises and async/await, and the basics of CORS and range requests from earlier chapters.
Why a single file stops being enough
A plain <video src="movie.mp4"> downloads one file at one quality. The browser uses range requests to seek and to fetch only part of the file. This works well for short clips. It fails in three situations:
- The viewer's bandwidth changes during playback. A file encoded at 8 Mbps stalls on a weak mobile connection, and a file encoded at 500 kbps looks poor on fast broadband.
- The file is very long. Seeking works, but the browser has no way to switch to a cheaper version of the file.
- You need live content. A live stream has no final file to point at.
Adaptive streaming solves these problems. The same content is encoded at several quality levels and cut into short segments, usually 2 to 10 seconds each. The player requests one segment at a time and picks the quality for each request from its current network conditions.
The pieces of an adaptive stream
| Piece | What it is |
|---|---|
| Rendition | One encoding of the content at a given resolution and bitrate, such as 360p at 800 kbps. |
| Segment | A short chunk of one rendition, usually a fragmented MP4 (fMP4) or an MPEG-TS file. |
| Manifest | A text file that lists renditions and segment URLs. HLS uses `.m3u8`. MPEG-DASH uses `.mpd`. |
| Player logic | Script that reads the manifest, measures throughput, and chooses the next segment. |
HLS (HTTP Live Streaming) and DASH (Dynamic Adaptive Streaming over HTTP) are two competing formats for the manifest and segments. Both run over ordinary HTTP, so any static file server or CDN can deliver them.
Native HLS versus Media Source Extensions
Safari on macOS and iOS can play HLS directly. You set src to the .m3u8 URL and the browser does the rest:
<video controls src="https://example.com/stream/master.m3u8"></video>Chrome, Firefox, and Edge on desktop do not play HLS natively. They give scripts a lower-level tool instead: Media Source Extensions (MSE). MSE is an API that lets JavaScript build the media stream itself. The page fetches segments, then feeds the bytes to the video element. The element still decodes, renders, and exposes its normal controls and events.
The main objects are:
MediaSource: an object you attach to a media element in place of a file URL.SourceBuffer: created bymediaSource.addSourceBuffer(type). You append segment bytes to it withappendBuffer().URL.createObjectURL(mediaSource): produces ablob:URL that you assign tovideo.src.
A minimal MSE player
The example below plays a fragmented MP4 as one initialization segment followed by numbered media segments. It does no quality switching. You need init.mp4 and seg1.m4s, seg2.m4s, and so on, all encoded with the codecs named in mime. A regular MP4 will not work. MSE requires fragmented MP4, which stores its metadata and sample data in repeating moof and mdat boxes.
<video id="player" controls width="640"></video>
<script>
const video = document.querySelector('#player');
const mime = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
const segments = ['init.mp4', 'seg1.m4s', 'seg2.m4s', 'seg3.m4s'];
function append(sourceBuffer, bytes) {
return new Promise((resolve, reject) => {
sourceBuffer.addEventListener('updateend', resolve, { once: true });
sourceBuffer.addEventListener('error', reject, { once: true });
sourceBuffer.appendBuffer(bytes);
});
}
async function start() {
if (!('MediaSource' in window) || !MediaSource.isTypeSupported(mime)) {
console.warn('MSE or this codec combination is not supported');
return;
}
const mediaSource = new MediaSource();
video.src = URL.createObjectURL(mediaSource);
await new Promise((resolve) => {
mediaSource.addEventListener('sourceopen', resolve, { once: true });
});
const sourceBuffer = mediaSource.addSourceBuffer(mime);
for (const url of segments) {
const response = await fetch(url);
if (!response.ok) throw new Error(`Failed to fetch ${url}`);
await append(sourceBuffer, await response.arrayBuffer());
}
mediaSource.endOfStream();
}
start().catch((err) => console.error('Streaming failed:', err));
</script>Three details in this code matter in practice:
- Wait for
sourceopen. You cannot calladdSourceBuffer()until theMediaSourceis attached to the element and has opened. - Never append while
updatingis true.appendBuffer()is asynchronous. A second call beforeupdateendthrows anInvalidStateError. Theappend()helper serializes the calls. - Check support first.
MediaSource.isTypeSupported()is the MSE counterpart ofcanPlayType()and takes the same kind of MIME string with acodecsparameter. UnlikecanPlayType(), it returns a plain boolean.
Choosing a quality level
The adaptive part is the logic that picks which rendition to request next. A common approach is to measure how fast the last segment arrived and choose the highest rendition that fits under that speed with a safety margin.
const renditions = [
{ name: '360p', bitsPerSecond: 800_000 },
{ name: '720p', bitsPerSecond: 2_500_000 },
{ name: '1080p', bitsPerSecond: 5_000_000 },
];
function pickRendition(measuredBitsPerSecond) {
const usable = measuredBitsPerSecond * 0.8;
let choice = renditions[0];
for (const r of renditions) {
if (r.bitsPerSecond <= usable) choice = r;
}
return choice;
}
console.log(pickRendition(4_000_000).name); // "720p"Real players also look at buffer level. If the buffer is nearly empty, they drop quality quickly to avoid a stall. If it is full, they can try a higher rendition. Writing that logic well is the hard part, which is why most teams use a library.
Using a library
Writing a production player yourself means handling manifest parsing, quality switching, live edge tracking, error recovery, and browser quirks. Established open-source players handle these for you:
- hls.js plays HLS through MSE in browsers without native HLS support.
- dash.js is the reference player for MPEG-DASH.
- Shaka Player supports both HLS and DASH.
A common pattern with hls.js is to use native playback where it exists and fall back to MSE otherwise. This feature check uses canPlayType():
const video = document.querySelector('video');
const url = 'https://example.com/stream/master.m3u8';
if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = url;
} else if (window.Hls && Hls.isSupported()) {
const hls = new Hls();
hls.loadSource(url);
hls.attachMedia(video);
}This snippet assumes you have loaded the hls.js script before it runs.
Failure modes and gotchas
- Wrong container. Appending a regular MP4 or an MP3 with the wrong type string fails. The
SourceBufferfires anerrorevent, and the media element reports aMediaError. - Codec mismatch. The
codecsstring you pass toaddSourceBuffer()must match the actual encoding. A mismatch can fail at append time or produce silent video. QuotaExceededError. EachSourceBufferhas a memory limit. Long sessions require removing old data withsourceBuffer.remove(start, end)once the playhead has passed it.- Segment alignment. Each segment should begin on a keyframe. Switching renditions mid-stream otherwise causes visual glitches.
- CORS. Your script fetches segments with
fetch(), so a CDN on another origin must sendAccess-Control-Allow-Origin. The earlier chapter on cross-origin media covers this. A missing header breaks the stream even though a plain<video src>would play. - iPhone Safari. Older iPhone versions did not offer
MediaSource. Newer Safari versions provideManagedMediaSource, a variant where the browser can ask the page to stop or resume buffering. Native HLS remains the dependable path on Apple devices. - Protected content. Playing DRM-protected streams needs Encrypted Media Extensions (EME). It is a separate API and is not covered here.
When to use adaptive streaming
| Situation | Recommended approach |
|---|---|
| Short clip, a few megabytes | Plain `<video src>` or `<source>` elements |
| Long video on varied networks | HLS or DASH with a library |
| Live broadcast | HLS or DASH with a library |
| Apple devices only | Native HLS through `src` |
| You need fine control over buffering | Your own MSE code |
Plain files are simpler to build, easier to debug, and cheaper to operate. Add adaptive streaming only when stalls, file size, or live delivery become real problems.
Exercise
A teammate's MSE player calls appendBuffer() on a SourceBuffer for segment 2 immediately after calling it for segment 1, and the console shows an InvalidStateError. What causes this, and how do you fix it?
Show answer
appendBuffer() is asynchronous, and the SourceBuffer's updating flag stays true until it fires updateend. Calling appendBuffer() again while updating is true throws InvalidStateError. Fix it by waiting for the updateend event before appending the next segment, for example by wrapping each append in a promise that resolves on updateend, or by keeping a queue of segments that is drained one at a time.
Exercise
Your page loads HLS segments with fetch() from a CDN on another origin. A plain video element pointed at the same CDN plays fine, but your MSE player fails. Why, and what does the CDN need to change?
Show answer
The video element can load cross-origin media without CORS headers, but fetch() from script is subject to the same-origin policy. The CDN must send an Access-Control-Allow-Origin header that permits your page's origin on the manifest and segment responses.