Sub topic 18
Adaptive streaming and Media Source Extensions
This chapter assumes you know the video element, its src attribute, and basic JavaScript with async/await. It explains why a plain src is sometimes not enough, and what to use instead.
The limit of a single file
A src pointing at one MP4 file plays at one quality. A viewer on a slow mobile connection stalls, and a viewer on fibre never gets a better picture than the file you chose. Adaptive streaming fixes this. You encode the video at several bitrates and cut each version into short segments, usually a few seconds long. The player measures download speed and picks the best bitrate for each next segment.
Two common delivery formats are HLS and MPEG-DASH. Each uses a manifest, which is a text file listing the available bitrates and segment URLs.
Two ways to play it
- Native playback. Safari plays HLS directly. Set
srcto the.m3u8manifest and the browser does the rest. - Media Source Extensions (MSE). Most other browsers cannot read manifests. Instead, JavaScript downloads the segments and feeds them to the
videoelement through the MSE API.
A minimal MSE example
This code appends one initialization segment and one media segment of a fragmented MP4. Plain MP4 files do not work with MSE. They must be fragmented.
const video = document.querySelector('video');
const mime = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
function append(buffer, data) {
return new Promise((resolve) => {
buffer.addEventListener('updateend', resolve, { once: true });
buffer.appendBuffer(data);
});
}
if (!('MediaSource' in window) || !MediaSource.isTypeSupported(mime)) {
console.warn('MSE or this format is not supported');
} else {
const mediaSource = new MediaSource();
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', async () => {
URL.revokeObjectURL(video.src);
const buffer = mediaSource.addSourceBuffer(mime);
for (const url of ['init.mp4', 'segment-1.m4s']) {
const response = await fetch(url);
await append(buffer, await response.arrayBuffer());
}
mediaSource.endOfStream();
});
}The video element's src is a temporary blob: URL that represents the MediaSource object. A SourceBuffer accepts only one append at a time, so the code waits for updateend before the next one.
What a real player adds
A production player does much more than this example: it parses manifests, estimates bandwidth, switches bitrates, removes old buffered data, and handles errors. Writing that yourself is rarely worthwhile. Libraries such as hls.js and dash.js do it on top of MSE.
Common errors
- Appending before
sourceopen. CallingaddSourceBuffertoo early throws an error. - Unfragmented files. The append succeeds or fails silently, and nothing plays.
- Wrong codec string.
isTypeSupportedreturnsfalse, or the buffer errors on append. - Assuming MSE everywhere. Older iPhones lack it. Fall back to native HLS where it exists.
- Cross-origin segments. They need the CORS headers covered in the previous chapter.
Exercise
A page sets the video's src to a blob URL from a MediaSource and appends a regular, non-fragmented MP4 file to a SourceBuffer. Playback fails. What is the likely cause, and what should you change?
Show answer
MSE requires fragmented MP4 (an initialization segment followed by media segments). Re-encode or repackage the file as fragmented MP4, then append the init segment first and the media segments after it.