Self-hosted videos with HLS

Vincent Bernat

Host­ing videos on YouTube is con­ve­nient for sev­eral rea­sons: pretty good player, free band­width, mo­bile-friendly, net­work ef­fect and, at your dis­cre­tion, no ads.1 On the other hand, this is one of the least pri­vacy-friendly so­lu­tions. Most other providers share the same char­ac­ter­is­tics—ex­cept the abil­ity to dis­able ads for free.

With the <video> tag, self-host­ing a video is simple:2

<video controls>
  <source src="../videos/big_buck_bunny.webm" type="video/webm">
  <source src="../videos/big_buck_bunny.mp4" type="video/mp4">
</video>

How­ever, while it is pos­si­ble to pro­vide dif­fer­ent videos de­pend­ing on the screen width, adapt­ing the video to the avail­able band­width is trick­ier. There are two so­lutions:

They are both adap­tive bi­trate stream­ing pro­to­cols: the video is sliced into small seg­ments and made avail­able at a va­ri­ety of dif­fer­ent bi­trates. De­pend­ing on cur­rent net­work con­di­tions, the player au­to­mat­i­cally se­lects the ap­pro­pri­ate bi­trate to down­load the next segment.

HLS was ini­tially im­ple­mented by Ap­ple but is now also sup­ported na­tively by Mi­cro­soft Edge and Chrome on An­droid. hls.js is a Java­Script li­brary bring­ing HLS sup­port to other browsers. MPEG-DASH is tech­ni­cally su­pe­rior (codec-ag­nos­tic) but only works through a Java­Script li­brary, like dash.js. In both cases, sup­port of the Me­dia Source Ex­ten­sions is needed when na­tive sup­port is ab­sent. Sa­fari on iOS doesn’t have this fea­ture and can­not use MPEG-DASH. Con­se­quently, the most com­pat­i­ble so­lu­tion is cur­rently HLS.

Encoding#

To serve HLS videos, you need three kinds of files:

  • the me­dia seg­ments (en­coded with dif­fer­ent bitrates/resolutions);
  • a me­dia playlist for each vari­ant, list­ing the me­dia seg­ments; and
  • a mas­ter playlist list­ing the me­dia playlists.

Me­dia seg­ments can come in two formats:

  • MPEG-2 Trans­port Streams (TS); or
  • Frag­mented MP4.

Frag­mented MP4 me­dia seg­ments have been sup­ported since iOS 10. They are a bit more ef­fi­cient and can be reused to serve the same con­tent as MPEG-DASH (only the playlists are dif­fer­ent). Also, they can be served from the same file with range re­quests. How­ever, if you want to tar­get older ver­sions of iOS, you need to stick with MPEG-2 TS.3

Up­date (2026-08)

I have switched to frag­mented MP4. The over­head of MPEG-2 TS is high for low-bi­trate videos, like screen­casts: up to 33% in my case.

FFmpeg is able to con­vert a video to me­dia seg­ments and gen­er­ate the as­so­ci­ated me­dia playlists. Peer5’s doc­u­men­ta­tion ex­plains the suit­able com­mands. I have put to­gether a handy (Python 3.6) script, video2hls, stitch­ing to­gether all the steps. Af­ter ex­e­cut­ing it on your tar­get video, you get a di­rec­tory con­taining:

  • me­dia seg­ments for each res­o­lu­tion (1080p_​1_001.ts, 720p_​2_001.ts, …)
  • me­dia playlists for each res­o­lu­tion (1080p_​1.m3u8, 720p_​2.m3u8, …)
  • mas­ter playlist (index.m3u8)
  • pro­gres­sive (stream­able) MP4 ver­sion of your video (progressive.mp4)
  • poster (poster.jpg)

The script ac­cepts a lot of op­tions for cus­tomiza­tion. Use the --help flag to dis­cover them. Run it with --debug to get the ffmpeg com­mands ex­e­cuted with an ex­pla­na­tion for each flag. For ex­am­ple, the poster is built with this command:

ffmpeg \
  `# seek to the given position (5%)` \
   -ss 4 \
  `# load input file` \
   -i ../2018-self-hosted-videos.mp4 \
  `# take only one frame` \
   -frames:v 1 \
  `# filter to select an I-frame and scale` \
   -vf 'select=eq(pict_type\,I),scale=1280:720' \
  `# request a JPEG quality ~ 10` \
   -qscale:v 28 \
  `# output file` \
   poster.jpg

Serving#

We have a bunch of static files we can up­load any­where. Yet two de­tails are im­portant:

  • When serv­ing from an­other do­main, CORS needs to be con­fig­ured to al­low GET re­quests. Adding Access-Control-Allow-Origin: * to re­sponse head­ers is enough.4
  • Some clients may be picky about the MIME types. En­sure files are served with the ones in the ta­ble below.
Kind Extension MIME type
Playlists .m3u8 application/​vnd.​apple.​mpegurl
MPEG2-TS segments .ts video/​mp2t
fMP4 segments .mp4 video/​mp4
Progressive MP4 .mp4 video/​mp4
Poster .jpg image/​jpeg

Let’s host our files on Ex­oscale’s Ob­ject Stor­age which is com­pat­i­ble with S3 and lo­cated in Switzer­land. As an ex­am­ple, the Cam­i­nan­des 3: Llami­gos video is about 213 MiB (five sizes for HLS and one pro­gres­sive MP4). It would cost us less than €0.01 per month for stor­age and €1.42 for band­width if 1000 peo­ple watch the 1080p ver­sion from be­gin­ning to end—un­likely.5

We use s3cmd to up­load files. First, you need to re­cover your API cre­den­tials from the por­tal and put them in ~/.s3cfg:

[default]
host_base = sos-ch-dk-2.exo.io
host_bucket = %(bucket)s.sos-ch-dk-2.exo.io
access_key = EXO.....
secret_key = ....
use_https = True
bucket_location = ch-dk-2

The sec­ond step is to cre­ate a bucket:

$ s3cmd mb s3://hls-videos
Bucket 's3://hls-videos/' created

You need to con­fig­ure the CORS pol­icy for this bucket. First, de­fine the pol­icy in a cors.​xml file (you may want to re­strict the al­lowed origin):

<CORSConfiguration>
 <CORSRule>
   <AllowedOrigin>*</AllowedOrigin>
   <AllowedMethod>GET</AllowedMethod>
 </CORSRule>
</CORSConfiguration>

Then, ap­ply it to the bucket:

$ s3cmd setcors cors.xml s3://hls-videos

The last step is to copy the static files. Playlists are served com­pressed to save a bit of band­width. For each video, in­side the di­rec­tory con­tain­ing all the gen­er­ated files, use the fol­low­ing command:

while read extension mime gz; do
  [ -z "$gz" ] || {
    # gzip compression (if not already done)
    for f in *.${extension}; do
      ! gunzip -t $f 2> /dev/null || continue
      gzip $f
      mv $f.gz $f
    done
  }
  s3cmd --no-preserve -F -P \
        ${gz:+--add-header=Content-Encoding:gzip} \
        --mime-type=${mime} \
        --encoding=UTF-8 \
        --exclude=* --include=*.${extension} \
        --delete-removed \
    sync . s3://hls-videos/video1/
done <<EOF
m3u8  application/vnd.apple.mpegurl true
jpg   image/jpeg
mp4   video/mp4
ts    video/mp2t
EOF

The files are now avail­able at https://​hls-videos.​sos-ch-dk-2.​exo.​io/​video1/.

HTML#

We can in­sert our video in a doc­u­ment with the fol­low­ing markup:

<video poster="https://hls-videos.sos-ch-dk-2.exo.io/video1/poster.jpg"
       controls preload="none">
  <source src="https://hls-videos.sos-ch-dk-2.exo.io/video1/index.m3u8"
          type="application/vnd.apple.mpegurl">
  <source src="https://hls-videos.sos-ch-dk-2.exo.io/video1/progressive.mp4"
          type='video/mp4; codecs="avc1.4d401f, mp4a.40.2"'>
</video>

Browsers with na­tive sup­port use the HLS ver­sion while oth­ers would fall back to the pro­gres­sive MP4 ver­sion. How­ever, with the help of hls.js, we can en­sure most browsers ben­e­fit from the HLS ver­sion too:

<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<script>
    if(Hls.isSupported()) {
        var selector = "video source[type='application/vnd.apple.mpegurl']",
            videoSources = document.querySelectorAll(selector);
        videoSources.forEach(function(videoSource) {
            var m3u8 = videoSource.src,
                once = false;

            // Clone the video to remove any source
            var oldVideo = videoSource.parentNode,
                newVideo = oldVideo.cloneNode(false);

            // Enable HLS on the video
            const hls = new Hls({
              autoStartLoad: false,
              capLevelToPlayerSize: true,
              maxMaxBufferLength: 90,
            });
            hls.loadSource(m3u8);
            hls.attachMedia(newVideo);
            newVideo.addEventListener("play", () => hls.startLoad(), false);

            // Replace video tag with our clone.
            oldVideo.parentNode.replaceChild(newVideo, oldVideo);
        });
    }
</script>

Up­date (2026-05)

The snip­pet above was sim­plified.

Here is the re­sult, fea­tur­ing Cam­i­nan­des 3: Llami­gos, a video cre­ated by Pablo Vasquez, pro­duced by the Blender Foun­da­tion and re­leased un­der the Cre­ative Com­mons At­tri­bu­tion 3.0 license:

Most Java­Script at­tributes, meth­ods and events work just like with a plain <video> el­e­ment. For ex­am­ple, you can seek to an ar­bi­trary po­si­tion, like 1:00 or 2:00—but you would need to en­able Java­Script to test.

The player is dif­fer­ent from one browser to an­other but pro­vides the ba­sic needs. You can up­grade to a more ad­vanced player, like Video.js or MediaElements.js. They also han­dle HLS videos through hls.js.

Up­date (2019-12)

For sub­ti­tles, have a look at “Self-hosted videos with HLS: sub­titles.”

Up­date (2026-11)

I have switched to Video.js. Na­tive play­ers lag be­hind: most of them do not dis­play chap­ters or let you se­lect an au­dio track. Since ver­sion 10, Video.js is also small: the whole player, in­clud­ing its own HLS en­gine, is less than the size of hls.js alone.

Host­ing your videos on YouTube is not un­avoid­able: serv­ing them your­self while of­fer­ing qual­ity de­liv­ery is tech­ni­cally af­ford­able. If band­width re­quire­ments are mod­est and the net­work ef­fect not im­por­tant, self-host­ing makes it pos­si­ble to re­gain con­trol of the pub­lished con­tent and not to turn over read­ers to Google. In the same spirit, PeerTube of­fers a video shar­ing plat­form. De­cen­tral­ized and fed­er­ated, it re­lies on BitTorrent to re­duce band­width re­quirements.

Addendum#

Preloading#

In the above ex­am­ple, preload="none" was used for two reasons:

  • Most read­ers won’t play the video as it is an add-on to the main con­tent. There­fore, band­width is not wasted by down­load­ing a few seg­ments of video, at the ex­pense of slightly in­creased la­tency on play.
  • We do not want non-na­tive HLS clients to start down­load­ing the non-HLS ver­sion while hls.js is load­ing and tak­ing over the video. This could also be done by declar­ing the pro­gres­sive MP4 fall­back from Java­Script, but this would make the video un­playable for users with­out Java­Script. If preload­ing is im­por­tant, you can re­move the preload at­tribute from Java­Script—and not wait for the play event to ini­tial­ize hls.js.

CSP#

Set­ting up CSP cor­rectly can be quite a pain. For browsers with na­tive HLS sup­port, you need the fol­low­ing pol­icy, in ad­di­tion to your ex­ist­ing policy:

  • image-src https://​hls-videos.​sos-ch-dk-2.​exo.io for the posters; and
  • media-src https://​hls-videos.​sos-ch-dk-2.​exo.io for the playlists and me­dia segments.

With hls.js, things are more com­plex. Ide­ally, the fol­low­ing pol­icy should also be applied:

  • worker-src blob: for the trans­mux­ing web worker;
  • media-src blob: about: for the trans­muxed seg­ments; and
  • connect-src https://​hls-videos.​sos-ch-dk-2.​exo.io to fetch playlists and me­dia seg­ments from JavaScript.

How­ever, worker-src is quite re­cent. The ex­pected fall­backs are child-src (dep­re­cated), script-src (but not ev­ery­where) and then default-src. There­fore, for broader com­pat­i­bil­ity, you also need to ap­pend blob: to default-src as well as to script-src and child-src if you al­ready have them. Here is an ex­am­ple pol­icy—as­sum­ing the orig­i­nal pol­icy was just default-src 'self' and me­dia, XHR and work­ers were not needed:

HTTP/1.0 200 OK
Content-Security-Policy:
  default-src 'self' blob:;
  image-src 'self' https://hls-videos.sos-ch-dk-2.exo.io;
  media-src blob: about: https://hls-videos.sos-ch-dk-2.exo.io;
  connect-src https://hls-videos.sos-ch-dk-2.exo.io;
  worker-src blob:;