AlgoViz

How Video Streaming Works

easy 45 min

A film is far too large to send as plain pictures, so a codec keeps only what is new in each frame.

Video lesson · Chapter 1 of 5

A school play on a moving train

0:00 / 5:38

Adaptive video playback

1:27Reel

Parallel video transcoding

1:19Reel

Theory

Read or listen first. About 3 min.

What it is

Video streaming means watching a film while it is still arriving. The film is compressed, made in several qualities, and cut into short segments of a few seconds. A manifest lists them. The player downloads a little ahead of what you see and chooses a quality for every next segment. Choosing like this is called adaptive bitrate, or ABR.

This page follows one film all the way. Asha films a school play with a phone: 10 minutes, 1080p, 30 frames per second, a file of 400 MB. Later 300 parents watch it: 90 on trains, 150 on kitchen tablets and 60 on big TVs. Here 1 MB means 1,000,000 bytes and 1 Mbit/s means 1,000,000 bits per second.

Our system makes four qualities: 270p at 0.4, 540p at 1.2, 720p at 2.4 and 1080p at 4.8 Mbit/s. Each segment is 4 seconds, so there are 150. These numbers are ours, chosen so that you can compute with them. Real services choose their own.

Why it exists

Without compression the ten minutes would be 112 GB. Without several qualities, one size must fit a train and a TV, and it fits neither. Without segments, a viewer would need the whole file, or a server that remembers every viewer.

Segments over plain HTTP solve a surprising number of problems together. Every segment is an ordinary file, so any cache can keep it. The server needs no memory of who is watching. A player can jump to minute five by asking for another file name, and it can change quality at every border.

A short history

  1. 1995

    ITU-T H.262 is published in July. The same video standard is known as MPEG-2.

  2. 2003

    The first edition of ITU-T H.264, Advanced video coding, is dated May 2003.

  3. 2009

    Apple's first Internet-Draft for HTTP Live Streaming is dated 1 May. It became RFC 8216 in August 2017.

  4. 2012

    ISO ratifies MPEG-DASH in April, as the DASH Industry Forum tells it. The forum is incorporated in September.

  5. 2014

    Researchers from Stanford and Netflix publish a buffer-based way to choose the bitrate at SIGCOMM in August, tested with real Netflix users.

  6. 2016

    Media Source Extensions become a W3C Recommendation on 17 November: a web page may feed a video element itself.

  7. 2018

    CMAF, one format of segments for HLS and DASH, has its first published edition. AOMedia releases the AV1 codec on 28 March.

  8. 2022

    RFC 9317, from October, describes how streaming video loads networks, with caching, ABR and live latency.

Words to know

Frame, frame rate
One still picture, and how many are shown in a second. Ours: 30.
Codec
The method that compresses and decompresses, for example H.264 or AV1.
Container
The file that holds compressed video, sound and times, for example MP4.
Keyframe
A frame that can be decoded alone. Playing can start here.
GOP
Group of pictures: a keyframe and the frames that follow it until the next one.
Rendition, rung, ladder
One quality of the film, the same thing seen as a step, and all steps together.
Segment
A few seconds of one rendition as a file. Ours: 4 seconds.
Manifest or playlist
The text that lists renditions and segments. HLS says playlist, DASH says MPD.
Buffer
Seconds of film that were downloaded and not yet shown.
Rebuffering or stall
The buffer is empty while the viewer wants to watch, so the picture stands still.
Origin, edge
Where the files really live, and the cache near the viewer.

How it works

Step through the idea, or press Play.

Step 1 of 3

Encode in parallel. One upload becomes many independent jobs, one per piece and quality. The transcoding reel shows nine from one 4K upload. Each result is recorded, so one failed job is repeated while the others stay.

Understand it

Start here

A comic strip and the courier ponies

Asha draws a long comic strip in a house on a hill. Lee reads it aloud to children far down the road, one page after another, without a break. Ponies carry the pages. The road is sometimes dry and sometimes deep in mud.

A comic strip by pony
empty traypages1 to 150One giant scroll

The house only draws and stores. The choice of size is made by the reader, page by page.

From zero

What a video is

A flip of a page in a notebook full of drawings looks like movement. A video is the same: still pictures, called frames, shown quickly. Asha's phone takes 30 of them in a second, so every picture stays for about 33 milliseconds.

A frame is a grid of pixels, tiny coloured points. 1080p usually means 1,920 pixels across and 1,080 down. A screen makes each colour by mixing red, green and blue light. With 8 bits, which is 256 steps, for each of the three, a pixel takes 24 bits.

How big is the play as plain pictures?

1920×1080=2,073,600 pixels×3 bytes=6,220,800 bytes per frame1920 \times 1080 = 2{,}073{,}600\ \text{pixels} \qquad \times 3\ \text{bytes} = 6{,}220{,}800\ \text{bytes per frame}
Times 30 frames is 186,624,000 bytes a second, or 1,493 Mbit/s. Times 600 seconds is 111,974,400,000 bytes: about 112 GB for ten minutes.

Asha's file has 400 MB. Something made it about 280 times smaller. That something is the rest of this half of the page.

First saving

Less colour than light: 4:2:0

When you colour a detailed pencil drawing with a thick crayon, it still looks sharp, because the pencil lines carry the detail. Eyes are like that: we see small differences of light better than small differences of colour.

So the picture is first rewritten. Instead of red, green and blue, every pixel gets one value for brightness, called luma or Y, and two for colour, called Cb and Cr. Then a block of 2 by 2 pixels keeps all four luma values, but shares one Cb and one Cr. This is called 4:2:0 chroma subsampling.

Why 8-bit 4:2:0 is 12 bits a pixel

(4 Y+1 Cb+1 Cr)×8 bits4 pixels=484=12 bits per pixel\frac{(4\,Y + 1\,C_b + 1\,C_r) \times 8\ \text{bits}}{4\ \text{pixels}} = \frac{48}{4} = 12\ \text{bits per pixel}
Half of 24. One frame is now 3,110,400 bytes, one second is 746.5 Mbit/s and the whole play is 55.99 GB.

The play at each step

FormPer secondTen minutes
Red, green, blue, 24 bits1,493 Mbit/s111.97 GB
4:2:0, 12 bits746.5 Mbit/s55.99 GB
Asha's file, picture and sound5.33 Mbit/s400 MB
Our 1080p rung, picture only4.8 Mbit/s360 MB
Our 270p rung, picture only0.4 Mbit/s30 MB
The 1080p rung has 4,800,000 / (2,073,600 x 30) = 0.077 bits per pixel instead of 12. That is about 156 times smaller.

Second saving

How a codec shrinks pictures

If you describe your room to a friend every minute, you do not start again each time. You say: the same as before, but the cat moved to the chair. A codec does this with blocks of pixels.

One block on its way

  1. 1

    Cut into blocks

    The frame is divided into squares. VP8, for example, uses macroblocks of 16 by 16 luma pixels. Newer codecs use larger squares and split them where there is detail.

  2. 2

    Predict in space

    A wall continues as a wall. The block is guessed from pixels above and to the left in the same frame. This is intra prediction.

  3. 3

    Predict in time

    The actor stood two pixels to the left a moment ago. The block is copied from another frame, moved by a motion vector. This is inter prediction.

  4. 4

    Subtract

    The encoder keeps only the residual: the real block minus the guess. With a good guess it is almost zero everywhere.

  5. 5

    Transform

    The residual is rewritten as a sum of patterns, from smooth to very fine. A discrete cosine transform, DCT, or a relative of it does this. Most of the content usually lands in a few numbers.

  6. 6

    Quantise

    Each number is divided by a step and rounded. Many become zero. This is the place where detail is lost, and the size of the step is the main quality knob.

  7. 7

    Pack

    The remaining numbers, the vectors and the choices are written with few bits for common values. Nothing is lost here.

The encoder decodes too

The encoder predicts from the decoded frame, not from the perfect original. Otherwise the guesses of encoder and decoder would drift apart.
Python
residual = [96, -23, 12, 6, -3, 2, 1, 0]      # after the transform (invented values)for step in (4, 10, 30):    stored = [round(v / step) for v in residual]   # quantise: small numbers become 0    back = [v * step for v in stored]              # what the decoder gets    error = sum(abs(a - b) for a, b in zip(residual, back))    print("step", step, stored, "zeros:", stored.count(0), "error:", error)
A larger step gives more zeros and fewer bits, and a larger error. Blocks with too large steps look like little tiles.
Edit and run it in your browser

Frame types

I, P and B frames

  • I frame

    Uses only itself. It is the largest, and decoding may start here if it is a real restart point. In H.264 that restart point is an IDR picture: nothing decoded later looks back past it.

  • P frame

    Predicts from frames that were decoded earlier. Much smaller, but useless without them.

  • B frame

    Can predict from two frames at once, usually one that is shown before it and one that is shown after it. Often the smallest.

  • GOP

    From one keyframe up to the next. Ours has 60 frames, which is 2 seconds. The ten minutes have 300 groups.

One GOP of our 1080p rung, with invented sizes

FramesHow manyEachTogether
I1152 KB152 KB
P2130 KB630 KB
B3811 KB418 KB
All601,200 KB in 2 s
1,200 KB x 8 / 2 s = 4.8 Mbit/s. If all 60 frames were I frames of 152 KB, the same two seconds would need 9,120 KB, which is 36.5 Mbit/s.

Now a small puzzle. A B frame may need a frame that is shown later. The decoder must have that one first. So frames travel in decode order and are shown in show order, and each frame carries two times: when to decode and when to show.

Show order and decode order

Order1st2nd3rd4th5th6th7th
ShownI1B2B3P4B5B6P7
DecodedI1P4B2B3P7B5B6
P4 jumps ahead, because B2 and B3 look at I1 and at P4. The decoder must hold P4 for a moment, which costs a little delay. That is one reason why video calls often avoid B frames.

Groups

Closed and open groups

In a closed GOP no frame looks outside its own group. In an open GOP, some B frames that are shown just before the next keyframe may look back into the group before. That can save some bits.

Closed GOP, for streaming

  • Decoding can start at every group
  • Cutting here is safe: each piece is complete
  • The player may change rungs at the border
  • Independent workers can encode the groups

Open GOP at a segment border

  • After a jump, the frames that lean backwards cannot be decoded
  • After a change of rung, the old group belongs to another rendition
  • Some pictures must be skipped, so the border may show a hiccup

How far apart should keyframes be?

DistanceFramesGoodPrice
1 s30Quick jumps, fine thumbnails, short segmentsMore large I frames for the same quality
2 s, ours60Two groups fit exactly into a 4 s segmentA compromise
4 s120Fewer I framesA jump may decode up to 119 frames that nobody sees
10 s300Good compression of calm scenesSegments of at least 10 s if each starts with a keyframe
Apple's authoring specification asks for keyframes every 2 seconds as a SHOULD, and says that a video segment MUST start with an IDR frame. A 4-second segment is our choice, its suggested duration is 6.

Two words

Container and codec

A lunch box says nothing about the language written on the paper inside it. MP4 is a box, H.264 is a language. The container holds tracks, times and an index. The codec is how the pictures inside are written. An .mp4 file can hold H.264, HEVC or AV1, so a file name does not say whether a device can play it.

The choice of codec

CodecReachLicenceUse it when
H.264 / AVCAll major browsers and very many devices, often in hardwarePatents. MDN says the licence pool asks no fee for internet video that is free for end usersYou want one answer for everybody
HEVC / H.265Common on phones and TVs. In browsers it depends on version, system and hardwarePatents, several parties4K and high dynamic range on devices that have it
VP9Wide support in browsersOpen and free of royaltiesWeb delivery beside H.264
AV1Browsers support it, but some, such as Safari, only on devices with an AV1 decoder in hardwareDesigned to be free of royaltiesVery popular films, where fewer bits repay the dearer encoding
Support as described by MDN when we opened it. Check again before you promise anything, and ask a lawyer about licences.

Hardware decoding means that a special part of the chip decodes. Without it the general processor must do the work, so a phone gets warm, the battery empties and frames may be dropped. navigator.mediaCapabilities.decodingInfo() answers three questions for a given size, rate and codec: supported, smooth, power efficient. A smaller file that a device decodes badly is not a win.

Is another codec worth it?

saved delivery=views×GB per view×share saved×price per GB\text{saved delivery} = \text{views} \times \text{GB per view} \times \text{share saved} \times \text{price per GB}
Compare it with the extra encoding and the extra storage, because the old codec usually stays for old devices. For 300 views the answer is often no, for 3 million it is often yes.

Rate control

Same bits, same quality, or a lid

Painting a blank wall needs little paint and a crowded market needs much. Should each get one pot of paint, or as much as it needs?

ModeHolds steadyGood forDanger
Constant bitrate, CBRBits per secondLive lines of fixed sizeCalm scenes waste bits, wild scenes look bad
Constant quality, for example CRF in x264Quality, roughlyArchives, mastersA wild scene can be many times larger than a rung allows
Capped qualityQuality, below a lidStreaming rungsThe lid shows in the wildest scenes
Two-pass averageTotal sizeA promised file sizeReads the film twice
A lid is a rate together with a virtual buffer: in FFmpeg maxrate with bufsize. Short peaks may pass the rate, the buffer limits for how long. In our bash run, a segment was 2.58 MB although 2.4 MB is the average under the lid.

Our four numbers are lids: the rung never averages much above them. A quiet scene may need far less, so a player that knows real segment sizes can do better than one that only knows the advertised rate. In the simulations below every segment is exactly at its rung, to keep the arithmetic clean.

The ladder

Why several renditions

Our ladder

RungPixelsMbit/sOne segment, 4 sTen minutesBits per pixel
270p480 x 2700.40.2 MB30 MB0.103
540p960 x 5401.20.6 MB90 MB0.077
720p1280 x 7202.41.2 MB180 MB0.087
1080p1920 x 10804.82.4 MB360 MB0.077
Our own ladder, picture only. Sound is a separate file of 128 kbit/s: 64 KB a segment and 9.6 MB in all, shared by all rungs. All four rungs together are 660 MB.

How to choose a ladder

  1. 1

    The lowest rung keeps the story alive

    It must fit through the worst network you want to serve. On our train, the tunnel still gives 0.5 Mbit/s, so 0.4 survives. With sound it is 0.528, a little too much. Good services therefore also think about the sound.

  2. 2

    The highest rung stops at the source

    Asha filmed 1080p at about 5.3 Mbit/s. A 4K rung, or 1080p at 10 Mbit/s, cannot contain detail that was never recorded.

  3. 3

    The steps are clearly different

    A factor of 1.5 to 3 is our rule of thumb. Smaller steps cost storage and make restless switching. Larger steps waste a good line.

  4. 4

    Fewer bits, fewer pixels

    At a low rate a smaller picture, enlarged by the screen, usually looks better than a large one full of tiles.

Per-title encoding. A drawing film and a football match do not need the same ladder. One can encode a title at many sizes and rates, plot quality against rate, and keep the points on the outer edge of all curves, the convex hull. Published research calls the complete search the most reliable way and also very costly, so people predict the hull instead. Some systems decide for every scene.

What a plainer title could save

60 TVs×600 s×(4.8−3.2) Mbit/s÷8=7,200 MB=7.2 GB60\ \text{TVs} \times 600\ \text{s} \times (4.8 - 3.2)\ \text{Mbit/s} \div 8 = 7{,}200\ \text{MB} = 7.2\ \text{GB}
Assumption: the play has a still stage and looks as good at 3.2 Mbit/s as a lively film at 4.8. That is our invention, only a quality check can tell.

Pipeline

From one upload to many small files

How the 400 MB reach storage safely is the topic of how large uploads work. It is even the same file. When the upload is finished, a job goes into a queue, and the pipeline begins.

From phone to files

Asha's phone uploads the 400 MB film to storage in our system. A job goes to the inspect and split service. From there pieces go to encoders for 1080p, for 540p and 720p, and for 270p, which work side by side. All send their results to the packager, which writes segments and lists. The result is 762 files in storage.
762 files: 600 video segments, 150 sound segments, 5 init segments, 5 media playlists, 1 master playlist and 1 DASH manifest.

The stations

  1. 1

    Inspect

    Read the box: codec, size, rotation, frame rate, sound, length. Phones often write a variable frame rate and a turned picture. Refuse what cannot be read, with a clear reason.

  2. 2

    Split at keyframes

    Cut the source where a frame stands alone. Our assumption: Asha's phone writes a keyframe every second, so cuts at every fourth second are possible without decoding. If it did not, the piece must be decoded from the keyframe before and trimmed.

  3. 3

    Encode in parallel

    150 pieces times 4 rungs are 600 tasks that do not need each other. All use the same settings and a fixed keyframe distance. The transcoding reel shows the same idea smaller: nine jobs from one 4K upload.

  4. 4

    Sound, captions, thumbnails

    Sound is encoded once as one track, because cutting sound into separately encoded pieces can leave clicks. Captions become WebVTT text. One small picture every 10 seconds makes 60 pictures on one sheet for the seek bar.

  5. 5

    Check

    Count frames, compare lengths, look for black or silent parts, and measure quality against the source.

  6. 6

    Package

    Write segments, init segments and manifests. The manifest is published last, so nobody sees a list of files that do not exist.

The graph of tasks

An arrow means: needs the result of. A graph like this without circles is called a DAG. Whatever is ready may start.

How long does it take?

150×(1+2+4+8) s=2,250 s2,25050 workers=45 s150 \times (1 + 2 + 4 + 8)\ \text{s} = 2{,}250\ \text{s} \qquad \frac{2{,}250}{50\ \text{workers}} = 45\ \text{s}
Assumptions: a 4-second piece takes 1, 2, 4 and 8 seconds of one worker for 270p, 540p, 720p and 1080p. Inspect, split and package take 5 seconds each, so the full ladder is ready after 5 + 5 + 45 + 5 = 60 s. With one worker, encoding alone takes 37.5 minutes.

A first playable version early. Nobody has to wait for 1080p. Do 270p and 540p first: 150 x (1 + 2) = 450 worker seconds, or 9 s on 50 workers. After 5 + 5 + 9 + 5 = 24 s parents can watch, and better rungs join the master playlist later. Viewers who come after that see all rungs.

One task fails, one task is repeated

The retry costs 8 worker seconds, not 2,250. The same piece and settings always go to the same name, so doing it twice does no harm. See idempotency.

Why is the split safe? Every piece starts with a closed group and every worker uses the same settings. Still, a rate lid knows nothing about the piece before it. Some systems give each worker a little of the neighbouring film, or plan the bits for all pieces first. YouTube went a step further for its scale: in 2021 Google described its own chips for video encoding, called VCU, and reported 20 to 33 times better efficiency than its earlier software system.

Quality

Is the copy good enough?

A judge who holds the original and the copy side by side sees more than one who only looks at the file size. A quality metric is such a judge, made of arithmetic.

What the numbers are

  • PSNR compares pixel by pixel
  • SSIM, from 2004, compares structure in small windows
  • VMAF, from Netflix, combines several measures with a model trained on viewers' scores

What they are not

  • Not a promise: a high average can hide one terrible second, so look at the lowest parts too
  • Not comparable across different sources or models without care
  • Blind to a missing sound track or wrong captions. Check those separately

Compare at the same size: first enlarge the 720p result to 1080p, then compare with the source, because that is what a TV shows. In our own run on a moving test picture, the 720p rung got a mean VMAF of 86.2 and an SSIM of 0.971. Those numbers belong to that test picture only.

Files

Segments and manifests

A manifest is a table of contents. In HLS there are two levels. The master playlist, which newer documents call the multivariant playlist, lists the renditions. Each has a media playlist that lists its segments.

Text
#EXTM3U#EXT-X-VERSION:7#EXT-X-INDEPENDENT-SEGMENTS#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="sound",NAME="English",DEFAULT=YES,AUTOSELECT=YES,URI="audio/list.m3u8"#EXT-X-STREAM-INF:BANDWIDTH=1628000,AVERAGE-BANDWIDTH=1328000,RESOLUTION=960x540,FRAME-RATE=30.000,CODECS="avc1.64001f,mp4a.40.2",AUDIO="sound"540p/list.m3u8#EXT-X-STREAM-INF:BANDWIDTH=628000,AVERAGE-BANDWIDTH=528000,RESOLUTION=480x270,FRAME-RATE=30.000,CODECS="avc1.640015,mp4a.40.2",AUDIO="sound"270p/list.m3u8#EXT-X-STREAM-INF:BANDWIDTH=3128000,AVERAGE-BANDWIDTH=2528000,RESOLUTION=1280x720,FRAME-RATE=30.000,CODECS="avc1.64001f,mp4a.40.2",AUDIO="sound"720p/list.m3u8#EXT-X-STREAM-INF:BANDWIDTH=6128000,AVERAGE-BANDWIDTH=4928000,RESOLUTION=1920x1080,FRAME-RATE=30.000,CODECS="avc1.640028,mp4a.40.2",AUDIO="sound"1080p/list.m3u8
Our master playlist. BANDWIDTH is the peak segment rate with sound: here we assume peaks of 1.25 times the rung, plus 128,000. Wrong values can cause stalls, says RFC 8216. Apple's rules call the first variant in the list the default one.
Text
#EXTM3U#EXT-X-VERSION:7#EXT-X-TARGETDURATION:4#EXT-X-MEDIA-SEQUENCE:0#EXT-X-PLAYLIST-TYPE:VOD#EXT-X-MAP:URI="init.mp4"#EXTINF:4.000,seg000.m4s#EXTINF:4.000,seg001.m4s...#EXTINF:4.000,seg149.m4s#EXT-X-ENDLIST
One media playlist, shortened at the dots. ENDLIST says that nothing more will come. File names count from 0, so the 77th segment is seg076.m4s.

The same ideas in two standards

IdeaHLSDASH
Table of contentsMaster and media playlists, plain textOne MPD, in XML
A stretch of timeThe parts between discontinuitiesPeriod
Things that can replace each otherVariant streamsAdaptation set
One qualityRendition in its media playlistRepresentation
Start dataEXT-X-MAPInitialization segment
Segment addressesA line for each, or byte rangesOften a template, for example seg$Number$.m4s
The words are only roughly equal. DASH leaves the codec open. HLS on Apple devices follows Apple's authoring rules.
  • Init segment

    Data that a decoder needs before any picture: codec settings, track numbers, time scale. One small file per rendition, loaded once and again after a change of rung.

  • Aligned keyframes

    Every rung starts a new group at 0, 2, 4 and 6 seconds and cuts at 0, 4 and 8. So the player can put the end of one rung next to the start of another.

  • Segment length

    Short: quick reaction and less to lose. Long: fewer requests and fewer keyframes. All media playlists share one target duration, and times must match, says RFC 8216.

  • CMAF

    One rule for fragmented MP4 pieces. The same segment files can be listed by an HLS playlist and a DASH MPD. Without it, two formats of the same film are stored and cached twice.

Counting files

600 s4 s=150150×4+150 sound=750750+5+5+1+1=762\frac{600\ \text{s}}{4\ \text{s}} = 150 \qquad 150 \times 4 + 150\ \text{sound} = 750 \qquad 750 + 5 + 5 + 1 + 1 = 762
With two complete sets, one for each standard, there would be about 1,500 media files and twice the cache misses.

A plain MP4 with byte ranges also works for small sites. Put its index at the front, with FFmpeg's -movflags +faststart. Otherwise the player may have to look for the index at the end before it can show anything.

Player

What happens in the browser

Press play on a web page. Safari can take an HLS address directly. In other browsers a script usually does the work through Media Source Extensions, MSE. The script fetches bytes and hands them to a SourceBuffer. The browser decodes and shows them.

Inside one player

The CDN edge sends a segment to the page script on the viewer's device. The script chooses and fetches, then appends the bytes to the SourceBuffer in the browser. Frames go from there to the decoder, and pictures go to the viewer.
The script never touches a pixel. It only decides which bytes come next and when.

From click to picture

Requests wait for each other at the start. That is why start time is full of round trips. See latency.

A start on a good train

5×0.1 s+0.2 MB×86 Mbit/s=0.5+0.27=0.77 s5 \times 0.1\ \text{s} + \frac{0.2\ \text{MB} \times 8}{6\ \text{Mbit/s}} = 0.5 + 0.27 = 0.77\ \text{s}
Assumptions: five round trips one after another, 0.1 s each, 6 Mbit/s. If the first segment were 1080p, it would be 0.5 + 3.2 = 3.7 s. Decoding and connecting are left out.

The rules of a SourceBuffer

  1. 1

    One append at a time

    appendBuffer returns at once and works in the background. The next call must wait for updateend.

  2. 2

    It can be full

    Then it throws QuotaExceededError. The script removes film that was already shown and tries again.

  3. 3

    Order is free

    A segment says itself where on the time line it belongs. So after a jump, pieces from the middle may be appended first.

  4. 4

    New rung, new settings

    Append the init segment of that rung before its first media segment.

  5. 5

    Phones have their own wish

    ManagedMediaSource lets the browser say when it wants data and throw film away to save power. On Safari it needs remote playback to be off, or an AirPlay source.

Seeking. Lee drags the bar to 5:07, which is second 307. Segment number 307 / 4 = 76, counted from 0, starts at 304. It has keyframes at 304 and 306. The decoder starts at 306 and works silently through the 30 frames up to 307. The bytes of 304 to 306 were downloaded only because they are in the same file. If second 307 is not buffered, the player waits with the state HAVE_METADATA until new data comes.

Which segment holds second t?

n=⌊t4⌋⌊3074⌋=7676×4=304 sn = \left\lfloor \frac{t}{4} \right\rfloor \qquad \left\lfloor \frac{307}{4} \right\rfloor = 76 \qquad 76 \times 4 = 304\ \text{s}
The little thumbnails over the bar come from the sheet of 60 small pictures, so no film has to be loaded while the finger is still moving. Thumbnail 30 belongs to 5:00 to 5:10.

The heart

Adaptive bitrate

You carry water to a garden that drinks one bucket every four seconds. A large bucket is nicer for the plants but slow to carry. Two things tell you which bucket to take: how fast you walked lately, and how much water still stands in the barrel.

  • Throughput

    Bits of a segment divided by its download time. It is a fact about the past. Very small segments, waiting and the sharing of a line make it jump around.

  • Buffer

    Seconds that are ready. It grows by 4 with each segment and shrinks by the download time. It is the time you have for being wrong.

  • Hysteresis

    Going up needs more proof than staying. Otherwise a speed near a border makes the picture jump up and down.

  • Device cap

    A phone screen with 540 rows gains little from 1080p. Do not fetch more rows than you can show, or a codec that the device cannot decode smoothly.

The buffer equation

Bnew=max⁡(0, B−d)+4stall=max⁡(0, d−B)d=4×rungspeedB_{\text{new}} = \max(0,\ B - d) + 4 \qquad \text{stall} = \max(0,\ d - B) \qquad d = \frac{4 \times \text{rung}}{\text{speed}}
B is the buffer before, d the download time in seconds. This holds once playing has begun. With B = 4, 1080p and 1.6 Mbit/s: d = 19.2 / 1.6 = 12 s, so the stall is 8 s.

Our buffer-aware rule

All thresholds are ours, for a buffer of at most 24 s. The harmonic mean gives slow downloads more weight than the plain average.

Worked trace

Two minutes on the train

The train gives 6 Mbit/s for 16 s, then 1.6 for 16 s, then a tunnel with 0.5 for 12 s, then 3.6 for 36 s, and 8 after that. We invented this ride. Four players fetch the same 30 segments. Playing starts when the first segment has arrived.

The ride, four players

PlayerStartStallsStalledRebuffer ratioMean rungSwitches
Fixed 1080p3.2 s826.7 s18.2%4.80 Mbit/s0
Fixed 540p0.8 s00 s0%1.20 Mbit/s0
Throughput only0.3 s29.3 s7.2%3.08 Mbit/s5
Buffer aware0.3 s00 s0%2.27 Mbit/s8
From the program in the Code tab, without round trips and sound. Rebuffer ratio is stalled time divided by stalled plus played time: 26.7 / (26.7 + 120). The buffer-aware player switches most often, mostly on its careful way up.

The buffer-aware player, the interesting segments

SegmentStarts atBuffer beforeRungDownloadSpeed seenBuffer after
10.0 s0270p0.3 s6.04.0 s
51.1 s15.2 s540p0.8 s6.018.4 s
74.3 s20.0 s1080p3.2 s6.020.8 s
1016.3 s20.0 s1080p12.0 s1.612.0 s
1128.3 s12.0 s720p11.0 s0.95.0 s
1239.3 s5.0 s270p3.2 s0.55.8 s
1444.2 s8.0 s270p0.4 s3.611.6 s
1746.5 s17.8 s720p2.7 s3.619.1 s
2992.3 s20.0 s1080p2.4 s8.021.6 s
Speeds in Mbit/s. Segment 10 was chosen before the weak part was known. The full buffer pays for that mistake: 20 - 12 + 4 = 12. At 8 Mbit/s, 1080p comes back only when three fast downloads are in the memory.

The throughput-only player asked for 1080p while it had 7.3 s ready. Then the speed fell to 1.6 Mbit/s and the download took 12 s: 12 - 7.3 = 4.7 s of stall. It had no barrel, only a guess about the next walk.

Published ideas, in one line each

IdeaMain signalWhat the authors report
Buffer-based, BBA, 2014Buffer alone in steady state, speed only during start-up10 to 20% fewer rebuffers than Netflix's default of that time, in field tests with 4-second chunks
BOLA, 2016Buffer, with a proof of near-optimal utilityNeeds no prediction of bandwidth. Part of the dash.js reference player
Pensieve, 2017A neural network learns from many observations12 to 25% better average quality of experience than the best compared method, in its tests
Percentages are the authors' own, for their own tests and scores. Do not add or compare them with each other.

The life of a player

Starting and seeking also wait for data, but they are counted apart from stalls: the viewer asked for them.

CDN

Copies near the viewers

Segments never change and everybody gets the same bytes. That is the best case for a cache. How a CDN works inside is told in CDN. Here are the numbers for our film.

One film, 300 parents

The origin with 762 files sends 0.63 GB to an origin shield in the CDN. The shield sends 1.89 GB in all to three edge sites, A, B and C. The edge sites send 56.7 GB in all to 300 parents: 90 on trains, 150 with tablets and 60 with TVs.
Video segments only. Each edge site serves 100 parents: 30 on trains, 50 with tablets, 20 with TVs.

Cache arithmetic

PlaceRequests inFound therePassed onBytes sent out
Three edge sites300 x 150 = 45,00043,650, which is 97%3 x 450 = 1,35056.7 GB
Origin shield1,3509004501.89 GB
Origin450all0.63 GB
Assumptions: everybody stays on one rung (540p, 720p or 1080p), nothing is thrown out, and parallel misses are joined into one. 450 is 150 segments times 3 rungs. 45,000 down to 450: the origin sees 1% of the requests.

Bytes to the parents

90×90+150×180+60×360=56,700 MB90×1.2+150×2.4+60×4.8=756 Mbit/s90 \times 90 + 150 \times 180 + 60 \times 360 = 56{,}700\ \text{MB} \qquad 90 \times 1.2 + 150 \times 2.4 + 60 \times 4.8 = 756\ \text{Mbit/s}
756 Mbit/s if all watch together. The sound adds 300 x 9.6 MB = 2.88 GB.

Two viewers, one miss

Joining equal misses is called request collapsing. Without it a premiere can send a crowd to the origin at once: see thundering herd.

More ways to be near

  1. 1

    Long life for segments

    Put a version into the path and let caches keep segments for a year. The playlist of a live stream lives only for about a segment.

  2. 2

    Boxes inside the internet provider

    Netflix's Open Connect gives appliances to internet providers. It says it downloads most content updates to them during off-peak fill windows, because it can predict what members will watch.

  3. 3

    Prefetch

    The player loads ahead. An edge may also fetch segment 77 when 76 is asked for. Useful for a first viewer, wasteful when people leave early.

  4. 4

    Know its limits

    A CDN sees files, not viewers. It cannot tell from its logs that somebody's picture stands still. Players therefore report, and CMCD lets a player add facts such as buffer length to its requests.

Live

Live and on demand

A film in the archive is a finished book. A live stream is a book that is being written while you read, and you want to be close to the pen.

On demandLive
PlaylistComplete, with ENDLISTGrows or slides, must be loaded again and again
Time for encodingCan be slower than real timeMust keep up with real time, always
Two-pass and per-title searchPossibleHardly, or only in small windows
BufferDozens of secondsLimited by how far behind you may be
A failed taskRepeat itThe moment is gone. Run two encoders
CachePopular parts are warmEverybody wants the newest piece at the same second

Where live delay comes from

3×4 s+1 s=13 swith parts of 0.5 s:3×0.5+1=2.5 s3 \times 4\ \text{s} + 1\ \text{s} = 13\ \text{s} \qquad \text{with parts of } 0.5\ \text{s}: \quad 3 \times 0.5 + 1 = 2.5\ \text{s}
RFC 8216 says that a client should not start less than three target durations from the end. The 1 s for encoding and travel is our assumption. The last segment of the list also ages up to 4 s until the next one appears, so the first figure moves between 13 and 17 s.

Low latency does not need tiny segments. A segment is published while it is still being made. In Low-Latency HLS it is listed as small partial segments, the server holds a playlist request until the next part exists, and it hints at the part that comes next. Low-latency DASH sends CMAF chunks of an unfinished segment, typically with HTTP chunked transfer. Keyframes stay far apart, so the compression stays good.

Less delay means less buffer, so every wobble of the network is closer to a stall. RFC 9317 calls under 1 second ultra low latency and under 10 seconds low latency. Chat with a streamer needs it, a lecture does not. A full live service is designed in Twitch.

Access

Signed URLs and DRM

  • Signed URL or cookie

    Proof that this viewer may fetch until a certain time. Amazon's guide suggests signed cookies when many files belong together, as in HLS. The edge checks it. The cache key should not contain it, or every viewer misses.

  • Encryption

    Segments are stored encrypted and the key is fetched separately. Alone, this does not stop a page from reading the key.

  • DRM

    A licence server gives a key with rules to a protected module in the device. In a browser the page talks to it through Encrypted Media Extensions. EME itself does not define any DRM system.

  • Honest limit

    Nothing stops a camera in front of a screen. DRM raises the cost of copying. For a school play, signed cookies are enough.

A licence, briefly

The page carries sealed letters between the two. It does not see the key.

Money

Storage, compute, delivery

Baking costs once, the shelf costs rent every month, and the delivery boy costs for every cake. Which one hurts depends on how many cakes you sell.

Our film with invented prices

CostAmountInvented priceResult
Encoding, once2,250 worker seconds = 0.625 hours0.05 coins an hour0.031 coins
Storage, every month400 + 660 + 9.6 = 1,069.6 MB0.02 coins per GB0.021 coins
Delivery, 300 views56.7 + 2.88 = 59.58 GB0.05 coins per GB2.979 coins
Delivery, one 720p view0.1896 GB with sound0.05 coins per GB0.009 coins
Coins are not a currency and these are no real prices. The point is the order: for a watched film, delivery is about 95 times the encoding. For a film seen once, a year of storage, 0.257 coins, is about 27 times that one view.

Popular titles

  • Make all rungs, perhaps a second codec
  • Push to the edges before the premiere
  • Every saved bit is saved again at every view

Cold titles

  • Keep the source and a small ladder, make the rest when somebody asks
  • Move to cheaper storage. Some classes charge for reading and have a shortest storage time
  • Edges will have thrown it away: expect misses and a slower start

Just-in-time packaging stores one form, for example CMAF pieces, and writes the HLS or DASH lists, and if needed another encryption, when a request comes. It saves storage for work at request time, and works best behind a shield. Just-in-time encoding goes further and makes a missing rung on demand, so the first viewer needs a worker that is faster than real time. Where the bytes rest: object storage.

Measure

What to watch

MeasureHow to compute itA trap
Start timeFrom the click to the first pictureCount people who leave before it appears as well
Rebuffer ratioStalled time / (stalled + played time)Do not count start, seeking and pause
Stalls per hourNumber of stalls / hours playedMany short stalls can annoy more than one long one
Mean bitrateWeighted by time shownMore is not better on a small screen or for an easy film
SwitchesChanges per minute, and how many rungsA visible jump of two rungs feels worse than two steps
Error ratePlays that ended with an error / playsSplit by device, codec, CDN, region and app version
Cache hit ratioBy requests and by bytes, for each layer97% at the edge can still mean a busy origin
Never improve one number alone. Always showing 270p gives a wonderful rebuffer ratio.

Trouble

Common failures

You seeOften the reasonLook at
Stall at every change of rungKeyframes are not aligned, or timestamps differKeyframe times of all rungs
Black picture, sound playsThe codec is not supported, or the init segment of the new rung is missingCODECS, decoding info, the init request
Voice and lips drift apartVariable frame rate, rounding of times, pieces with different lengthsSum of segment lengths against the source
404 in the middleManifest published before its segments, or an old list with deleted filesPublish order, versions in paths
Picture jumps up and downNo hysteresis, noisy speedBuffer and choice per segment
Start is slow for everyoneFirst rung too high, too many requests one after another, cold cacheA waterfall of the first 10 requests
Only live viewers stallEncoder slower than real time, or stale playlists in the cacheAge of the newest segment, cache time of the playlist
Everything fails after an hourSigned addresses ran out during the filmRenewal of the token
Seek lands earlyKeyframes too far apartDistance of keyframes

All together

The play, from stage to screens

StepNumbers
Film10 min, 1080p, 30 frames a second: 18,000 frames, 300 groups
Plain pictures112 GB, or 56 GB as 4:2:0
Upload400 MB
Encode600 tasks, 2,250 worker seconds, first version after 24 s, all after 60 s
Store660 MB picture, 9.6 MB sound, 762 files
Deliver45,000 video requests, 56.7 GB, 450 requests at the origin
Watch270p first, then what speed, buffer and screen allow

Whole products around this core: Design YouTube for uploads by everybody, Design Netflix for a catalogue that is known in advance, and Twitch for live.

Summary

The whole topic in one minute.

Video is a row of pictures. A codec predicts every block from its neighbours or from other frames and stores only a rounded difference. Keyframes stand alone, P and B frames lean on others, and a group from one keyframe to the next is a GOP. In streaming the groups are closed and the keyframes of all renditions are at the same times.

A pipeline inspects the upload, cuts it at keyframes, encodes pieces in parallel, checks quality, and packages segments, an init segment per rendition and manifests. One set of CMAF files can serve HLS and DASH. The player appends segments through Media Source Extensions, keeps a buffer, and uses measured speed and buffer together to choose the next rung.

A CDN keeps the segments near the viewers, so 45,000 video requests of our 300 parents become 450 at the origin. Storage is paid for every month, encoding once, and delivery for every view. Watch start time, rebuffer ratio, bitrate and errors together.

  • Plain 1080p at 30 frames is 1,493 Mbit/s. 8-bit 4:2:0 halves it to 12 bits a pixel.
  • A codec predicts blocks, transforms the difference and rounds it. Rounding is where detail is lost.
  • I frames stand alone, P and B frames lean on others. Decode order is not show order.
  • Closed groups and aligned keyframes make cutting, parallel work, seeking and switching safe.
  • MP4 is a box, H.264 is a language.
  • A ladder is several sizes of the same film. Our segments are 4 s, and 150 of them make ten minutes.
  • Encode pieces as a graph of tasks. Repeat one task, publish a small ladder early, the manifest last.
  • The player uses speed and buffer, goes up slowly, and respects the screen.
  • Segments are ordinary files: 45,000 requests become 450 at the origin.
  • Live trades buffer for closeness. Popular films pay for delivery, cold films for storage.

Sources