---
description: Embedding a live HLS stream in your own template with hls.js — bundling the library, CORS and HTTPS, starting playback, the error handler and retry configuration that keep a dead or dying channel reconnecting, the progress watchdog, disposal, audio fallback, scheduled windows, testing, and the complete script.
---

# Embedding an HLS livestream

HLS is the streaming format behind AWS IVS, Wowza, Mux and most other livestream providers: a `.m3u8`
playlist that points at short media segments. This page is for template authors who embed a stream
inside their own layout or add behavior to it, such as a keynote window that opens at a set time. If
all you need is a full-screen stream on a room's sign, the app generates that template for you with no
code; see [Livestream and Web Page Templates](../livestream_and_url_templates.md).

Everything below is the pattern the generated template ships with, worked out against a stream that
was down, a host that refused cross-origin requests, a slow venue link and a channel that went dark
mid-playback. The complete script is at the end of the page; the lifecycle hooks it relies on are
explained on [Template JavaScript best practices](template-js-best-practices.md).

## Before you write any code

- **Bundle the player library in the ZIP.** Put `hls.min.js` under `assets/libraries/` and load it with
  a normal `<script src="assets/libraries/hls.min.js">` tag. The sign platform ships hls.js 1.6.15;
  take that version's `dist/hls.min.js` from the `hls.js` npm package or its GitHub release.
  Do **not** reference the platform copy at `/static/js/hls.min.js`: that URL is deliberately never
  cached by the sign's service worker, so a template depending on it cannot play offline. A copy inside
  your ZIP is a template asset: precached, offline-safe, and pinned to the version you tested.
- **The stream host must allow cross-origin requests.** hls.js fetches playlists and segments with
  `XMLHttpRequest`, which needs an `Access-Control-Allow-Origin` header from the stream host. Every
  mainstream provider sends one. If it is missing, the browser reports the request as **HTTP 0**, and
  the script below surfaces that in the console.
- **Use an HTTPS stream URL.** Signs run over HTTPS, and a plain HTTP stream is blocked as mixed
  content.

## Test `Hls.isSupported()` first

```js
if (typeof Hls !== "undefined" && Hls.isSupported()) {
  // The hls.js path: the one you want.
} else if (video.canPlayType("application/vnd.apple.mpegurl")) {
  // Native fallback: Safari, or a browser without Media Source Extensions.
}
```

The order matters. Current Chrome plays HLS **natively** too, so a template that tests `canPlayType()`
first silently takes the native path on every sign, and the native `<video>` element has no error
events for a dead stream, no reconnect and no retry policy. Keep native playback as the fallback only.

## Call `play()` yourself

Under Media Source Extensions the `autoplay` attribute is not reliable. Leaving playback to it is the
single most common way to end up with a permanently black player. Start playback from the
`MANIFEST_PARSED` event:

```js
hls.on(Hls.Events.MANIFEST_PARSED, () => {
  play();
});
```

## Always handle `Hls.Events.ERROR`

On a fatal error hls.js calls `stopLoad()` and does nothing further. Without a handler the stream is
dead until somebody reloads the sign. Three facts about hls.js decide what the handler has to do, each
learned on a live sign:

1. **hls.js never retries a 4xx.** A livestream channel that is not broadcasting yet typically answers
   **404** (AWS IVS returns `[{"error":"Can not find channel"}]`). The first response is fatal, so the
   retry limits in the configuration never apply to it; they cover timeouts and 5xx, plus status 0
   while the browser reports itself offline.
2. **`startLoad()` cannot recover a stream whose playlist never loaded.** It reloads levels that are
   already parsed; when the manifest never arrived there are none, and the call does nothing at all.
   Only **`loadSource()`** re-requests the manifest.
3. **A retry must be scheduled, never run inline.** A dead channel fails within milliseconds, so an
   inline `loadSource()` raises its next fatal error inside whatever throttle guards the handler, the
   throttle discards it, and nothing re-arms the attempt. Pace retries on a timer, with a single
   pending flag so only one attempt is ever in flight.

So the handler splits by type. A fatal **media** error gets `recoverMediaError()`, throttled and
followed by `play()` because re-attaching the element pauses it. Every other fatal error gets a
scheduled `loadSource()`:

```js
hls.on(Hls.Events.ERROR, (event, data) => {
  if (!data || !data.fatal) return;
  if (data.type === Hls.ErrorTypes.MEDIA_ERROR) {
    const now = Date.now();
    if (now - (ctx.state.recoveredAt || 0) >= RECOVER_THROTTLE_MS) {
      ctx.state.recoveredAt = now;
      hls.recoverMediaError();
      play();
      return;
    }
    // A second media error inside the window: recovery is not taking. Fall through to a reload.
  }
  showMessage("Waiting for the stream...");
  reconnect(describeError(data)); // schedules hls.loadSource(STREAM_URL) a few seconds out
});
```

## Retry configuration

hls.js honors the older `manifestLoadingMaxRetry`, `levelLoadingMaxRetry` and `fragLoadingMaxRetry`
names **only when the page supplies them**, and skips that mapping entirely if the matching
`*LoadPolicy` object is also supplied. Left unset, a fragment gets four timeout retries and six error
retries, the latter with a backoff that caps at eight seconds; a bad stretch of venue network can
exhaust them, and the error is then fatal and playback stops.

```js
const hls = new Hls({
  manifestLoadingMaxRetry: 3,
  levelLoadingMaxRetry: Infinity,
  fragLoadingMaxRetry: Infinity,
});
```

Two deliberate choices in that block:

- **Level and fragment retries are unlimited**, so a bad stretch of network never becomes fatal.
- **The manifest limit stays finite.** hls.js never retries a 4xx, and it retries status 0, which is
  what a host without CORS headers or a DNS failure produces, only while the browser reports itself
  offline; on a connected sign a refused host is fatal at the first attempt whatever the limit. What
  the library does retry is a 5xx, a timeout, and that offline case, and with no limit those loop
  inside the library forever: no fatal error, no handler, no message, a black screen. A few retries
  make a 5xx or an offline sign fatal within seconds, and a host that never answers fatal in about
  eighty seconds (each manifest attempt may wait twenty seconds); then the message shows and the
  scheduled reconnect paces every attempt after that.

hls.js prints a deprecation notice for the three names only when the instance is created with
`debug: true`. Without it the library's own logger is silent, so the library itself prints nothing;
every console line this page mentions comes from the template's own script.

## A channel that dies mid-playback raises no fatal error

When a live channel is switched off while the player is running, hls.js reports only **non-fatal**
errors, `levelLoadError` and `bufferStalledError`, then stops requesting, and the picture freezes on
its last frame. Nothing in the error handler can fire. The only detector is a **progress watchdog**:

- Sample `video.currentTime`. A frozen video still reports `paused === false`, so the element's own
  state proves nothing.
- Require **two consecutive still samples**, seven seconds apart, before reloading. One still sample is
  ordinary rebuffering, and reloading on it throws the buffer away and starts over, which on slow venue
  wifi never converges.
- A still element that is `paused` gets a `play()` nudge instead: browsers do pause long-running video
  on their own.
- **Drop the reload if the picture moved on while it waited.** hls.js retries fragments by itself with
  a backoff of up to eight seconds, so a link that comes back late comes back inside the reload's own
  delay, and `loadSource()` on a playing element swaps the media source and throws that recovery away
  for a second black gap. Only the watchdog's reload is dropped this way. A reload scheduled by a fatal
  error always runs, because hls.js has stopped loading and a buffer still draining is not recovery,
  and it also lifts the check off a watchdog reload that is already waiting.
- The reload is the same scheduled `loadSource()` as above, which also starts playback again at the
  live edge instead of resuming stale buffer.

## Destroy the player in `ctx.onDispose`

Removing the `<script>` element does not stop a running `Hls` instance; its timers and requests
survive. On a Physical Room sign, which rebuilds its template on every gap-to-content switch, that is
one live downloader leaked per switch. Over a six-day event that is on the order of a hundred of them
hitting the same stream from one address.

```js
ctx.onDispose(() => {
  if (hls) {
    hls.destroy();
    hls = null;
  }
  video.pause();
  video.removeAttribute("src");
  video.load();
});
```

## Audio

Unmuted playback needs either a real user gesture on the page or Chrome launched with
`--autoplay-policy=no-user-gesture-required`; see
[Chrome kiosk setup](../../signs/digital_sign_chrome_startup.md). The pattern that degrades gracefully:

1. **Attempt with sound first.** If `play()` is refused, set `muted = true` and play again so the
   picture is never lost, and log why.
2. **Upgrade on the first gesture.** A tap or key press anywhere on the page gives it sticky
   activation for the rest of its life; unmute and play.
3. **Treat `AbortError` as what it is.** A reconnect swaps the media source under the element and
   rejects a pending `play()` with `AbortError`. That is not an autoplay refusal, and falling back to
   muted on it would silence the stream permanently after a single reconnect.
4. **Fall back only on `NotAllowedError`.** That is the one name the autoplay policy produces. When the
   element fails before its first frame, a dark channel on the native path or a media source that
   ended in error, a pending `play()` is rejected with `NotSupportedError` instead. That is a playback
   fault for the error handlers to reconnect from; leave the audio state
   alone, or the stream comes back muted for good, because sound is only restored after a gesture.

Attempting muted first means a correctly configured sign never gets sound.

## Scheduled windows

A keynote-overflow board shows the stream only during known windows and spends most of its life pointed
at a channel that is **down**. Two rules on top of everything above:

- **Do not keep a stream loading permanently** if it is needed for a few minutes a day. Call
  `hls.stopLoad()` when a window closes, so the player is not pulling segments for days to serve a
  few minutes of use.
- **Open every window with `loadSource()`, not `startLoad(-1)`.** `startLoad(-1)` (`-1` is the live
  edge) only resumes a stream whose manifest parsed at some point; if the channel was down when the
  window opened, it does nothing (fact 2 above). Reloading the source at the edge covers that, covers
  the silent mid-run death above, and starts the window at the live edge rather than from stale buffer.

Event Scoped templates are not switched by any schedule; the one on a sign is replaced only when an
admin assigns a different template, so its player normally lives for days, which is why the
scheduled-window rules matter most there. Physical Room templates are rebuilt on every gap-to-content
switch, which is why disposal matters most for them.

## How to test it

Everything about a stream template can look right when the stream is **up**, which is the one state in
which none of these failures exist. Before trusting a template:

- Boot the sign against a channel that is **down**, then bring the channel up, and count manifest
  requests on the server side. The console line `Reconnecting stream: manifestLoadError (HTTP 404)`
  shows the reconnect loop is alive, and the picture must appear within seconds of the channel starting.
- Point it at a host without CORS headers: the waiting message must appear within seconds and the
  console must show `(HTTP 0)`, not a silent black screen.
- Switch the channel off while it is playing and watch the picture freeze, the message appear once the
  buffer has drained and two samples have passed, and playback resume when the channel returns.
- Force a gap-to-content switch on a Physical Room and confirm the stream host stops receiving requests.

## The complete script

This is the script the generated HLS template ships with, unchanged except for the two constants at
the top. It expects this markup and the `.hls-message` styles below it:

```html
<div id="your-content" class="your-content">
  <video id="video" playsinline></video>
  <p id="hls-message" class="hls-message" hidden></p>

  <script src="assets/libraries/hls.min.js"></script>
  <script>
    /* the script below */
  </script>
</div>
```

```css
.hls-message {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 10%;
  color: #fff;
  font: 2rem/1.3 sans-serif;
  text-align: center;
}

/* The rule above sets display, which would override the browser's own [hidden] rule. */
.hls-message[hidden] {
  display: none;
}
```

```js
window.preseriaTemplateInit = function (ctx) {
  const STREAM_URL = "https://example.com/live/stream.m3u8";
  const AUDIO_ENABLED = false; // true: try with sound first, fall back to muted, upgrade on a tap

  // A dead endpoint fails in milliseconds, so every retry is SCHEDULED, never inline: an
  // inline retry raises its next fatal error inside the log throttle, is discarded, and
  // nothing re-arms it. Measured: an inline loadSource() stops after three attempts.
  const RECONNECT_DELAY_MS = 5000;
  // recoverMediaError() detaches and re-attaches the media element. Spaced out it is the
  // right first response to a decode fault; back-to-back it is a spin. A second fatal media
  // error inside this window escalates to a full reload instead.
  const RECOVER_THROTTLE_MS = 4000;
  // Progress is sampled every 7 s, and a reload needs TWO consecutive still samples - about
  // 14 s of frozen picture. One still sample is normal while the stream rebuffers, and
  // reloading on it throws the buffer away and starts over, which on slow venue wifi never
  // converges.
  const STALL_SAMPLE_MS = 7000;
  const STALL_SAMPLES_BEFORE_RELOAD = 2;
  const LOG_THROTTLE_MS = 300000;

  const video = document.getElementById("video");
  const message = document.getElementById("hls-message");
  if (!video) return;

  let hls = null;
  video.muted = !AUDIO_ENABLED;

  function warnOnce(key, text) {
    if (ctx.state[key]) return;
    ctx.state[key] = true;
    console.warn("[Preseria HLS] " + text);
  }

  function warnThrottled(text) {
    const now = Date.now();
    if (now - (ctx.state.loggedAt || 0) < LOG_THROTTLE_MS) return;
    ctx.state.loggedAt = now;
    console.warn("[Preseria HLS] " + text);
  }

  // Scoped to its own element: writing document.body.innerHTML would destroy #your-content
  // and everything built around it.
  function showMessage(text) {
    if (message) {
      message.textContent = text;
      message.hidden = false;
    }
  }
  function hideMessage() {
    if (message) message.hidden = true;
  }

  function play() {
    // A gesture gives the page sticky activation for the rest of its life, so a muted
    // fallback applied after one is stale. Clear it before every attempt.
    if (AUDIO_ENABLED && ctx.state.gestureSeen) video.muted = false;

    video.play().then(hideMessage).catch((err) => {
      const name = err && err.name;
      // AbortError is NOT an autoplay refusal: loadSource() on reconnect swaps the
      // MediaSource and aborts a pending play(). Falling back to muted here would silence
      // the stream permanently after a single reconnect.
      if (name === "AbortError") return;
      // Only NotAllowedError is the autoplay policy. Anything else is a playback fault,
      // typically NotSupportedError when the element fails before its first frame (a dark
      // channel on the native path, a media source that ended in error): the error
      // handlers reconnect from it, and the audio state must survive it, because sound is
      // only restored after a gesture and a muted fallback here would silence the stream
      // for good once the channel comes back.
      if (name !== "NotAllowedError") {
        warnOnce(
          "playFailed",
          "play() failed (" + name + "); waiting for the stream to recover."
        );
        return;
      }

      if (!video.muted) {
        video.muted = true; // Refused with sound. Keep the picture.
        warnOnce(
          "audioBlocked",
          "Autoplay with sound was refused, so the stream is playing muted. Tap the sign " +
            "once to enable sound, or launch Chrome with --autoplay-policy=no-user-gesture-required."
        );
        video.play().catch((e) => {
          if (e && e.name === "AbortError") return;
          warnOnce("mutedBlocked", "Will not play even muted: " + (e && e.name));
        });
        return;
      }
      warnOnce("mutedBlocked", "Video will not play: " + name);
    });
  }

  // Only loadSource() re-requests the master manifest. startLoad() reloads levels that are
  // ALREADY parsed, so against a channel that has never come up there are no levels and the
  // call does nothing - which is exactly the state a sign is in when it boots before the
  // stream starts. No startLoad() call follows: hls.js starts loading by itself once the new
  // manifest parses (autoStartLoad defaults to true).
  //
  // A reconnect the watchdog asks for is dropped if the position moved while it waited:
  // hls.js retries fragments by itself with a backoff of up to 8 s, so a link that comes
  // back late comes back inside this delay, and loadSource() on a playing element swaps
  // the MediaSource and throws that recovery away for a second black gap. A reconnect a
  // fatal error asks for is never dropped - hls.js has stopped loading, and a buffer still
  // draining is not recovery - and it lifts the gate off a watchdog reconnect already
  // pending, which the pending flag would otherwise have absorbed.
  function reconnect(reason, options) {
    const unlessPlaybackMoves = Boolean(options && options.unlessPlaybackMoves);
    if (ctx.state.reconnectPending) {
      if (!unlessPlaybackMoves) {
        ctx.state.reconnectGatePosition = null;
        ctx.state.reconnectReason = reason;
      }
      return;
    }
    ctx.state.reconnectPending = true;
    ctx.state.reconnectGatePosition = unlessPlaybackMoves ? video.currentTime : null;
    ctx.state.reconnectReason = reason;
    ctx.setTimeout(() => {
      ctx.state.reconnectPending = false;
      ctx.state.stallSamples = 0; // The reload gets a full stall budget.
      const gatePosition = ctx.state.reconnectGatePosition;
      ctx.state.reconnectGatePosition = null;
      if (gatePosition !== null && video.currentTime !== gatePosition) {
        hideMessage(); // Playback moved on by itself; a reload would only interrupt it.
        return;
      }
      warnThrottled("Reconnecting stream: " + ctx.state.reconnectReason);
      if (hls) {
        hls.loadSource(STREAM_URL);
      } else {
        video.src = STREAM_URL;
        video.load();
        play();
      }
    }, RECONNECT_DELAY_MS);
  }

  // The HTTP status is the one fact that separates "channel not broadcasting yet" (404)
  // from "host refuses cross-origin requests" (0) in an unattended console.
  function describeError(data) {
    const code = data.response && data.response.code;
    return (data.details || "fatal " + data.type) + (code != null ? " (HTTP " + code + ")" : "");
  }

  if (typeof Hls !== "undefined" && Hls.isSupported()) {
    hls = new Hls({
      // hls.js maps these deprecated names onto the *LoadPolicy objects, but ONLY when the
      // page supplies them. Left unset, a fragment gets 4 timeout retries and 6 error retries
      // (backoff capped at 8 s), which a bad stretch of venue network can exhaust; the error
      // is then fatal and playback stops.
      //
      // The manifest limit stays FINITE on purpose. hls.js never retries a 4xx, and it
      // retries status 0 (a host without CORS headers, DNS failure) only while the browser
      // reports itself offline; what it does retry is a 5xx, a timeout, and that offline
      // case. With no limit those loop inside the library forever: no fatal error, no
      // handler below, no message, black screen. A few retries and it is fatal, the message
      // shows, and reconnect() paces every attempt after that.
      manifestLoadingMaxRetry: 3,
      levelLoadingMaxRetry: Infinity,
      fragLoadingMaxRetry: Infinity,
    });

    // The autoplay attribute is not reliable under MSE. Drive playback from here.
    hls.on(Hls.Events.MANIFEST_PARSED, () => {
      play();
    });

    // On a fatal error hls.js calls stopLoad() and does nothing further. Without this
    // handler the stream is dead until the sign reloads.
    hls.on(Hls.Events.ERROR, (event, data) => {
      if (!data || !data.fatal) return;
      if (data.type === Hls.ErrorTypes.MEDIA_ERROR) {
        const now = Date.now();
        if (now - (ctx.state.recoveredAt || 0) >= RECOVER_THROTTLE_MS) {
          ctx.state.recoveredAt = now;
          warnThrottled("Fatal media error; recovering: " + data.details);
          hls.recoverMediaError();
          // Re-attaching the media element re-runs the browser's load algorithm, which
          // pauses it, and hls.js never calls play(). Resume here rather than waiting for
          // the watchdog's nudge, which is up to two samples away.
          play();
          return;
        }
        // A second fatal media error inside the throttle window: recovery is not taking.
        // Fall through to the full reload rather than spin on it.
      }
      showMessage("Waiting for the stream...");
      reconnect(describeError(data));
    });

    hls.loadSource(STREAM_URL);
    hls.attachMedia(video);
  } else if (video.canPlayType("application/vnd.apple.mpegurl")) {
    // The native path raises no Hls events, so the element's error event is its only
    // recovery hook. Deliberately NOT registered on the hls.js path: there hls.js owns
    // errors, and the watchdog below backstops anything it does not see.
    ctx.addEventListener(video, "error", () => {
      showMessage("Waiting for the stream...");
      reconnect("media element error");
    });
    video.src = STREAM_URL; // Fallback: Safari / no MSE.
    play();
  } else {
    showMessage("This browser cannot play HLS streams.");
    return;
  }

  // A frozen <video> still reports paused === false, so the element's own state proves
  // nothing. Sampling currentTime is the only reliable stall signal - and the only detector
  // at all for a live channel switched off mid-playback, which hls.js reports with NON-fatal
  // errors only before it stops requesting.
  ctx.state.lastTime = video.currentTime; // Seeded, so the first tick is not "progress".
  ctx.state.stallSamples = 0;
  ctx.setInterval(() => {
    const position = video.currentTime;
    if (position !== ctx.state.lastTime) {
      ctx.state.lastTime = position;
      ctx.state.stallSamples = 0;
      // A reload resets the position to 0 before anything plays; that is not progress
      // worth clearing the message for.
      if (position > 0) hideMessage();
      return;
    }
    ctx.state.stallSamples += 1;
    if (ctx.state.stallSamples < STALL_SAMPLES_BEFORE_RELOAD) {
      // Browsers do pause long-running video on their own; a nudge is enough for that. With
      // controls visible this also undoes a manual pause - on a sign, resuming is the right
      // default.
      if (video.paused) play();
      return;
    }
    ctx.state.stallSamples = 0;
    showMessage("Waiting for the stream...");
    reconnect("playback stalled", { unlessPlaybackMoves: true });
  }, STALL_SAMPLE_MS);

  if (AUDIO_ENABLED) {
    ["pointerdown", "keydown"].forEach((type) => {
      ctx.addEventListener(
        document,
        type,
        () => {
          ctx.state.gestureSeen = true;
          video.muted = false;
          video.play().catch(() => {});
        },
        { once: true }
      );
    });
  }

  ctx.onDispose(() => {
    if (hls) {
      hls.destroy();
      hls = null;
    }
    video.pause();
    video.removeAttribute("src");
    video.load();
  });
};
```

For a scheduled window, wrap the last two sections of the script: call `hls.stopLoad()` and pause the
element when the window closes, and on the window-open edge clear any muted fallback, call
`hls.loadSource(STREAM_URL)` directly (not through `reconnect()`, so a pending flag can never block a
window) and `play()`. Keep the watchdog running only while a window is open.

## Related

- [Livestream and web page templates](../livestream_and_url_templates.md) — the generated template, no code
- [Embedding video](embedding_video.md) — a video file instead of a stream
- [Template JavaScript best practices](template-js-best-practices.md)
- [Chrome kiosk setup](../../signs/digital_sign_chrome_startup.md) — the autoplay flag for sound
