Skip to main content

03 - Video Streaming for Education: WebRTC vs HLS vs DASH

WebRTC for conversations, HLS and DASH for large audiences: how to choose, with an HLS ladder built with FFmpeg and a quality-selection rule actually run.

What do you think about this article?

At a Glance

WebRTC for conversations, HLS and DASH for large audiences: how to choose, with an HLS ladder built with FFmpeg and a quality-selection rule actually run.

A live lesson and a recording need different protocols

The question "which protocol do I use for video?" has a short answer: WebRTC for conversations, HLS or DASH for everything that is watched by many and does not require an immediate reply, and a complete platform uses all three. The reason is that two needs pull in opposite directions. An algebra lesson with thirty students raising their hands needs the question to reach the teacher while it is still on topic; a recording watched by three thousand students needs the stream to go through a distribution network that knows nothing about video, because it is made of plain HTTP servers. The first scenario sacrifices scale to cut delay, the second sacrifices delay in order to scale.

The article walks through the three protocols in this order, and for each one shows an executed listing: the room logic of a live lesson, an HLS quality ladder really produced with FFmpeg, and a quality selector that uses the generated files. It assumes HTTP and the idea of a codec; no streaming skills are needed. If you are interested in where video files live in a platform with several customers, read Scalable LMS Architecture first; for the whiteboard and shared edits during a lesson, Real-Time Collaboration in EdTech.

WebRTC: making two browsers talk to each other

WebRTC is a set of browser interfaces for real-time audio, video and data, today a W3C Recommendation (the version cited in the sources is dated 13 March 2025). The starting point for understanding it is that two browsers, to talk directly, must first exchange information about themselves: which codecs they support and at which network addresses they can be reached. The standard does not say how: the W3C specification states that communications are coordinated by control messages exchanged over a signaling channel "provided by unspecified means", usually a page script with a server behind it, for example over WebSocket. The signaling, therefore, you write yourself.

The second problem is the network. Almost no device has an address reachable from outside, because it sits behind a NAT. The ICE protocol (RFC 8445) tries several routes, called candidates: the local address, the one seen by a STUN server outside the network, and an address on a TURN server, which the same RFC defines as a "relayed candidate", that is, an address obtained from a relay. The relay forwards traffic when a direct connection is impossible, and for that reason it is the candidate that costs: your students' video goes through your bandwidth. There is no number valid for everyone on how many connections need the relay; in your case it is measured from the browser's statistics.

The topology remains. With the mesh every participant sends their own video to all the others: with 10 people that is 9 outgoing streams for each and 90 streams overall, growing as n · (n - 1). An SFU (Selective Forwarding Unit) is a server that receives a single stream from each participant and distributes it to the others: everyone's outgoing traffic stays a single stream, and the cost moves to the server. For two-person tutoring the mesh is enough, for a class you need an SFU. The listing that follows does not open WebRTC connections (it would need a browser): it implements the part the signaling server must decide, that is who may enter a room, as a pure function that returns a new state without modifying the previous one.

TypeScript - Admission to the rooms of a live lesson, with fallback to HLS
type Role = 'host' | 'student';

interface Room {
  readonly host: string;
  readonly participants: ReadonlySet<string>;
  readonly max: number;
}

type Outcome =
  | { readonly outcome: 'ok'; readonly rooms: ReadonlyMap<string, Room> }
  | { readonly outcome: 'error' | 'use-hls'; readonly rooms: ReadonlyMap<string, Room>; readonly reason: string };

// Pure function: given the state of the rooms, it decides who gets in. No mutation.
function join(rooms: ReadonlyMap<string, Room>, room: string, socket: string, role: Role, max = 3): Outcome {
  const current = rooms.get(room);
  if (!current) {
    if (role !== 'host') return { outcome: 'error', rooms, reason: 'room does not exist' };
    const created = new Map(rooms).set(room, { host: socket, participants: new Set(), max });
    return { outcome: 'ok', rooms: created };
  }
  if (current.participants.size >= current.max) {
    return { outcome: 'use-hls', rooms, reason: 'room full: the client switches to watching over HLS' };
  }
  const updated = { ...current, participants: new Set(current.participants).add(socket) };
  return { outcome: 'ok', rooms: new Map(rooms).set(room, updated) };
}

let s: ReadonlyMap<string, Room> = new Map();
const moves: Array<[string, string, Role]> = [
  ['algebra-3A', 'teacher', 'host'],
  ['algebra-3A', 'anna', 'student'],
  ['algebra-3A', 'bruno', 'student'],
  ['algebra-3A', 'carla', 'student'],
  ['algebra-3A', 'dario', 'student'],
  ['history-2B', 'eva', 'student'],
];
for (const [room, who, role] of moves) {
  const r = join(s, room, who, role);
  s = r.rooms;
  console.log(`${who.padEnd(8)} -> ${room.padEnd(11)} ${r.outcome}${'reason' in r ? ' (' + r.reason + ')' : ''}`);
}
console.log('participants in algebra-3A:', [...(s.get('algebra-3A')?.participants ?? [])]);

// Output:
// teacher  -> algebra-3A  ok
// anna     -> algebra-3A  ok
// bruno    -> algebra-3A  ok
// carla    -> algebra-3A  ok
// dario    -> algebra-3A  use-hls (room full: the client switches to watching over HLS)
// eva      -> history-2B  error (room does not exist)
// participants in algebra-3A: [ 'anna', 'bruno', 'carla' ]

The listing was run with Node 24 and the output shows the server's three decisions. The teacher (host) creates the room; whoever arrives first in a nonexistent room as a student gets an error, because the lesson has not started yet; when the room is full (here max = 3, to show the case) the fourth student is not rejected but receives use-hls: the client switches to watching the same lesson over HLS, with more delay but without participant limits. The limit of 3 is demonstrative, not a recommended value: yours depends on how many streams your SFU sustains, and you measure it. The forwarding of offer, answer and ICE candidates between the two browsers, and the wiring with Socket.io, are the pattern to adapt: they require a server and two browsers, and were not run.

One last detail that matters in production: if the connection drops, there is no need to restart the session. The W3C specification provides the iceRestart: true option in the offer, which renegotiates the ICE credentials and candidates on the same RTCPeerConnection. It is the right mechanism for a network change (the student moves from Wi-Fi to mobile data), and if that fails too the fallback is exactly watching over HLS.

HLS: the lesson as a sequence of small files

HTTP Live Streaming, born at Apple, is described by RFC 8216 (August 2017): an RFC of the Informational category, not an IETF standard, as the document itself says. The idea is deceptively simple. The video is cut into segments of a few seconds, each an ordinary file downloadable over HTTP; a textual playlist lists the segments in the order in which they are to be played; the player downloads the playlist and then the segments, one after the other. Since they are ordinary files, any server or distribution network serves them without special software, and that is the reason HLS scales where WebRTC does not.

To adapt to the connection the video is encoded several times, at different qualities (the ladder). A master playlist lists the versions, each with its declared bandwidth (BANDWIDTH), and the player chooses. The command that follows builds a real three-rung ladder, 720p, 480p and 240p, starting from a synthetic 12-second source (a test signal and a 440 Hz tone, so no video files are needed). Two choices matter more than the others. With -g 100 -keyint_min 100 -sc_threshold 0 the keyframe arrives every 100 frames, that is every 4 seconds at 25 per second, so that every segment of -hls_time 4 starts with a keyframe and the player can switch rung at every segment boundary without artifacts. With -maxrate and -bufsize the bitrate stays under a predictable ceiling, and without that ceiling the declared BANDWIDTH would be a lie.

Shell - A three-rung HLS ladder with FFmpeg
ffmpeg -hide_banner -loglevel error -y \
  -f lavfi -i "testsrc2=size=1280x720:rate=25:duration=12" \
  -f lavfi -i "sine=frequency=440:duration=12" \
  -filter_complex "[0:v]split=3[v1][v2][v3];[v1]scale=-2:720[v720];[v2]scale=-2:480[v480];[v3]scale=-2:240[v240]" \
  -map "[v720]" -map "[v480]" -map "[v240]" -map 1:a -map 1:a -map 1:a \
  -c:v libx264 -preset veryfast -g 100 -keyint_min 100 -sc_threshold 0 \
  -b:v:0 1500k -maxrate:v:0 1600k -bufsize:v:0 3000k \
  -b:v:1 800k  -maxrate:v:1 856k  -bufsize:v:1 1600k \
  -b:v:2 300k  -maxrate:v:2 321k  -bufsize:v:2 600k \
  -c:a aac -b:a 64k -ac 2 \
  -f hls -hls_time 4 -hls_playlist_type vod -hls_flags independent_segments \
  -hls_segment_filename "hls/v%v_%03d.ts" -master_pl_name master.m3u8 \
  -var_stream_map "v:0,a:0 v:1,a:1 v:2,a:2" "hls/v%v.m3u8"

# Output:
# --- master.m3u8 ---
# #EXTM3U
# #EXT-X-VERSION:6
# #EXT-X-STREAM-INF:BANDWIDTH=1605520,AVERAGE-BANDWIDTH=1596621,RESOLUTION=1280x720,CODECS="avc1.64001f,mp4a.40.2"
# v0.m3u8
#
# #EXT-X-STREAM-INF:BANDWIDTH=908792,AVERAGE-BANDWIDTH=898263,RESOLUTION=854x480,CODECS="avc1.64001e,mp4a.40.2"
# v1.m3u8
#
# #EXT-X-STREAM-INF:BANDWIDTH=414352,AVERAGE-BANDWIDTH=395426,RESOLUTION=426x240,CODECS="avc1.640015,mp4a.40.2"
# v2.m3u8
# --- segments (bytes) ---
# 800880 v0_000.ts
# 802760 v0_001.ts
# 791292 v0_002.ts
# 451200 v1_000.ts
# 454396 v1_001.ts
# 441800 v1_002.ts
# 189316 v2_000.ts
# 207176 v2_001.ts
# 196648 v2_002.ts

The command was run with FFmpeg and libx264 and produces the listed files: three 4-second segments for each rung, plus one playlist per rung and the master. In the master, the BANDWIDTH values (1,605,520, 908,792, 414,352 bits per second) are higher than the requested video bitrate (1500k, 800k, 300k) because they include the audio and the container, and this is the value the player compares with the available bandwidth. The segments of the top rung weigh about 791-803 thousand bytes: note that they are not all the same, because the bitrate is an average over time. The numbers in this output are those of a synthetic source, and with a real lesson video the weights will differ.

What lies behind the distance from "live"? RFC 8216 says, in the section on playback, that in a live playlist the client should not start from a segment that begins less than three target durations from the end of the playlist, because it risks stalls. With 4-second segments the player therefore starts at least 12 seconds behind the real moment: that is why standard HLS is not suited to a conversation. The next edition of the protocol, still an IETF draft (version 22 is dated 1 May 2026), introduces a low-latency mode, but it requires a server and a distribution network that support it, and it was not tried here.

ABR: who picks the rung, and what happens at low bandwidth

The choice of the rung is made by the player, not the server. The listing shows the simplest possible rule, useful for understanding the principle: it reads the master playlist generated above, sorts the rungs by declared bandwidth and takes the highest one that fits inside the measured bandwidth multiplied by a margin (margin=0.8), because real bandwidth fluctuates and it is better not to travel at the limit. Then, using the real sizes of the files produced, it computes how long it takes to download the first segment at that speed, and compares it with the 4 seconds of video it contains: if the download lasts longer, the buffer runs dry and the video stops.

Python - Choosing the rung from the master playlist and checking against the real segments
import os, re

def read_master(path):
    """Extracts the renditions from the master playlist (RFC 8216): declared bandwidth, resolution, playlist."""
    lines = open(path).read().splitlines()
    ladder = []
    for i, line in enumerate(lines):
        if line.startswith("#EXT-X-STREAM-INF:"):
            bandwidth = int(re.search(r"(?<![-A-Z])BANDWIDTH=(\d+)", line).group(1))
            res = re.search(r"RESOLUTION=(\d+x\d+)", line).group(1)
            ladder.append({"bandwidth": bandwidth, "resolution": res, "playlist": lines[i + 1]})
    return sorted(ladder, key=lambda x: x["bandwidth"])

def choose(ladder, throughput_bps, margin=0.8):
    """The highest rendition whose declared bandwidth fits within throughput * margin."""
    fits = [r for r in ladder if r["bandwidth"] <= throughput_bps * margin]
    return fits[-1] if fits else ladder[0]     # below the minimum: stay on the lowest rung

ladder = read_master("hls/master.m3u8")
print("ladder:", [(r["resolution"], r["bandwidth"]) for r in ladder])

for mbps in (3.0, 1.2, 0.6, 0.3):
    r = choose(ladder, mbps * 1_000_000)
    first = os.path.getsize("hls/" + r["playlist"].replace(".m3u8", "_000.ts"))
    download = first * 8 / (mbps * 1_000_000)
    verdict = "holds" if download < 4.0 else "DOES NOT hold (the buffer runs dry)"
    print(f"{mbps:>3} Mbit/s -> {r['resolution']:<9} first segment {first:>7} bytes, download {download:4.1f} s for 4 s of video: {verdict}")

# Output:
# ladder: [('426x240', 414352), ('854x480', 908792), ('1280x720', 1605520)]
# 3.0 Mbit/s -> 1280x720  first segment  800880 bytes, download  2.1 s for 4 s of video: holds
# 1.2 Mbit/s -> 854x480   first segment  451200 bytes, download  3.0 s for 4 s of video: holds
# 0.6 Mbit/s -> 426x240   first segment  189316 bytes, download  2.5 s for 4 s of video: holds
# 0.3 Mbit/s -> 426x240   first segment  189316 bytes, download  5.0 s for 4 s of video: DOES NOT hold (the buffer runs dry)

The first three lines of the output show the system working: at 3 Mbit/s 720p is chosen and the first segment arrives in 2.1 seconds; at 1.2 Mbit/s it drops to 480p (3.0 seconds, close to the limit); at 0.6 Mbit/s to 240p. The fourth line is the one to remember: at 0.3 Mbit/s even the lowest rung does not hold, because its declared bandwidth (414 kbit/s) is greater than the available one, and downloading a 4-second segment takes 5. The design consequence is that the ladder must have a rung below the lowest useful one for your students with the worst connections (for example an audio-only stream with the slides), and you choose the size of the rung from the statistics of your own users, not from a generic figure. The listing is the idea, not the algorithm of a real player: hls.js, in its documented options, computes bandwidth with moving averages and has many tuning parameters.

In the browser you do not write the algorithm yourself: you use a library. The following pattern, to adapt because it requires a browser and hls.js (it was not run), follows the order of the hls.js documentation: first it checks whether the browser supports Media Source Extensions with Hls.isSupported(), and only otherwise tries native playback with canPlayType. The capLevelToPlayerSize option, which by default is false, limits the automatic choice to the rungs that the size of the video box needs: on a phone it avoids downloading a 720p for a small box.

TypeScript - Attaching an HLS video to the page (pattern to adapt, not run)
import Hls from 'hls.js';

export function attachVideo(video: HTMLVideoElement, src: string): Hls | null {
  if (Hls.isSupported()) {
    // MSE available: hls.js downloads the segments and feeds them to the video
    const hls = new Hls({ capLevelToPlayerSize: true });
    hls.loadSource(src);
    hls.attachMedia(video);
    return hls;                 // the caller must call hls.destroy() when leaving the page
  }
  if (video.canPlayType('application/vnd.apple.mpegurl')) {
    video.src = src;            // the browser's native HLS (Safari)
  }
  return null;
}

The destroy() line mentioned in the comment is not a detail: without it, in a single-page application every lesson opened leaves an instance that keeps downloading segments. Call it when the component is destroyed.

MPEG-DASH: the same idea with a different manifest

MPEG-DASH follows the same scheme as HLS (HTTP segments, several representations, choice on the player side) with a manifest in XML format, the .mpd file, in place of the .m3u8 playlist. It is an ISO standard, and it is not tied to a vendor. The open-source reference player, dash.js, works in browsers that support Media Source Extensions and Encrypted Media Extensions: the latter are the entry point of content protection (DRM). That is why the choice between HLS and DASH in real projects is not about video quality: it is decided by the devices to reach and the content protection systems your catalog requires. Browser and DRM compatibility change with versions, and a table copied from an article ages quickly: check the vendors' pages before deciding.

The hybrid architecture and slow connections

A complete platform assigns to each situation the protocol that respects its dominant constraint. The table summarizes it with the reasons and without latency figures, which I have not measured and which change with the network.

SituationProtocolDeciding constraint
One-to-one tutoringWebRTC, meshConversation; only two streams
Interactive classWebRTC with SFU, HLS fallback beyond the server's limitReal-time questions, number of outgoing streams
Lesson broadcast to manyHLS (or DASH) from a distribution networkScale; a delay of tens of seconds is acceptable
RecordingsHLS with a quality ladderScale, costs, playback on every device
Catalog with DRMDASH or HLS depending on the systems to supportContent protection requirements

The table shows that the choice is made on a single criterion per row, and it is the one that would cost the most if you got it wrong: in the interactive class the delay, in the broadcast the scale, in the protected catalog compatibility with DRM. Whoever tries to pick a single protocol for everything usually ends up paying where they did not want to: either on the server (WebRTC for a thousand viewers), or on the experience (HLS for a conversation). The automatic fallback seen above, from the full room to HLS, is the concrete way to hold the two worlds together without letting the student feel the difference.

For slow connections, three measures come straight from the listings. A ladder that descends far enough, down to a rung for those with little bandwidth, with an honest declared bandwidth (maxrate and bufsize). The cap on size (capLevelToPlayerSize), because there is no point in downloading a 720p for a 300-pixel box. And prefetching the next lesson only when the connection allows it, because on a weak network the prefetch takes bandwidth away from the current lesson. How many students in your audience have a limited connection is a datum you must collect yourself: this article cites none, because I have neither a measurement nor a primary source.

What you can do now

You can choose the protocol of a lesson starting from the constraint that matters, and explain why standard HLS cannot be interactive (at least three target durations behind live). You can produce an HLS ladder with FFmpeg and read its master playlist, compute whether a rung holds at a given bandwidth, and design the fallback from WebRTC to HLS. The next article in the series moves the focus from broadcasting to the exam: AI Proctoring Systems. To make recordings viewable even without a network, go to Mobile-First EdTech.

Frequently asked questions

Can WebRTC serve a class of a thousand students?

It is not advisable: every WebRTC viewer consumes resources on the server, and the architecture scales with an SFU and with more servers, at high cost. For a large audience you use HLS or DASH from a distribution network, accepting several seconds of delay, and you reserve WebRTC for those who must speak up.

Why does HLS have so much delay compared with live?

Because the stream is divided into segments and RFC 8216 recommends that the player not start from a segment less than three target durations from the end of the playlist. With 4-second segments that is at least 12 seconds behind live. The low-latency mode of the second edition reduces the delay but requires a compatible server and network.

Is HLS or DASH better for a course catalog?

It depends on the devices and the DRM required, not on quality. Check compatibility on the pages of the browser and protection-system vendors, because it changes with versions. Many platforms produce both formats from the same segments.

Before this article in the series: Adaptive Learning: IRT, BKT and DKT in Production.

Sources

The FFmpeg command, abr.py and rooms.ts were run (FFmpeg with libx264, Python 3, Node 24) and the outputs are the real ones; the video source is synthetic and the segment weights change with a real video. The ISO page of MPEG-DASH is not reachable: the qualification as an ISO standard was not verified at the source. The block with hls.js is a pattern to adapt and was not run. No figure on WebRTC latency, on the share of users with a slow network or on the link between buffering and course completion is reported, because no primary source was found.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects