When running live campus broadcasts, an upstream encoder dropout or stalled .m3u8 origin leaves viewers stuck on a spinning Video.js player unless the client handles recovery explicitly. In Campus TV, we split playback resilience and live audience tracking into a three-tier client controller and a Socket.IO room counter.

1. Three-Tier Failover Controller

Rather than relying on static #EXT-X-STREAM-INF redundant stream entries baked into a single master playlist, stream URLs are configured dynamically in an admin panel and fetched at runtime from /api/stream-settings. That lets operators swap origins or leave a backup stream optional without regenerating manifests.

The LivePlayer controller orchestrates three fallback stages:

VideoJsPlayer starts an 8-second startup timer (FALLBACK_TIMEOUT_MS = 8000, cleared when playing fires) and listens for Video.js error events. On failure, LivePlayer advances streamPhase and increments liveKey to remount Video.js cleanly—disposing the old player instance so timestamp discontinuities and decoder buffers do not carry across origins.

Here is the core failover state machine from LivePlayer.jsx:

const [mode, setMode] = useState('live');
const [streamPhase, setStreamPhase] = useState('primary');
const [liveKey, setLiveKey] = useState(0);

const handleFallback = useCallback((reason) => {
  if (streamPhase === 'primary' && backupSrc) {
    setStreamPhase('backup');
    setLiveKey((k) => k + 1); // full remount clears stale Video.js state
    return;
  }
  setFallbackReason(reason);
  setMode('archive'); // renders YouTubeArchivePlayer (recorded VOD playlist)
}, [streamPhase, backupSrc]);

const handleTryLiveAgain = useCallback(() => {
  setStreamPhase('primary');
  setLiveKey((k) => k + 1);
  setMode('live');
}, []);

Tier 3 (YouTubeArchivePlayer) is a recorded fallback, not a live feed: it queries /api/youtube/latest for recent uploads and embeds an autoplay YouTube playlist outside Video.js. Recovery back to live is intentionally manual (Try Live Again) so viewers are not yanked out of playback while an origin is flapping.

2. Real-Time Viewer Tracking with Socket.IO

In production (backend/sockets/liveViewers.js), live:join, live:leave, and disconnect all update room membership via io.in('live').allSockets() and emit the count to the room.

When scaling that pattern to traffic spikes or multiple Node instances, unthrottled emits on every join/leave create an $O(N^2)$ broadcast storm, and per-process room maps diverge across workers. A safer pattern throttles room broadcasts and keeps both join and leave paths symmetrical:

const ROOM = 'live_broadcast';
const emitCount = throttle(
  async () => {
    const sockets = await io.in(ROOM).fetchSockets();
    io.to(ROOM).emit('live:viewers', { active: sockets.length });
  },
  1000,
  { leading: true, trailing: true }
);

io.on('connection', (socket) => {
  socket.on('live:join', () => {
    socket.join(ROOM);
    emitCount();
  });

  socket.on('live:leave', () => {
    socket.leave(ROOM);
    emitCount();
  });

  socket.on('disconnect', () => {
    emitCount();
  });
});

Two practical notes:

  • sockets.length (or rooms.get(ROOM)?.size) counts active WebSocket connections, not unique viewers—a user with two open tabs counts twice.
  • Multi-instance deployments require pairing Socket.IO with @socket.io/redis-adapter so io.in(ROOM).fetchSockets() aggregates across nodes instead of reading only local memory.

3. Buffer Delay & Latency

Without glass-to-glass telemetry instrumented in production, claiming a fixed millisecond bound would be guesswork. What we can express accurately is the relationship between segment duration, client buffer depth, and end-to-end delay:

Tbuffer≈Nsegments×Tsegment+Tnetwork+TdecodeT_{\text{buffer}} \approx N_{\text{segments}} \times T_{\text{segment}} + T_{\text{network}} + T_{\text{decode}}
Shortening HLS segments (for example, 2-second segments with 1-second keyframes in OBS/FFmpeg) lowers the playlist buffer floor, at the trade-off of higher request frequency to the origin/CDN and tighter tolerance for mobile packet loss.

4. Trade-offs & Current Limits

  • Remount vs. seamless splice: Remounting VideoJsPlayer on failover avoids HLS discontinuity bugs across unrelated origins, at the cost of re-initializing the player UI and re-buffering from the backup manifest.
  • Manual failback: Once in YouTube archive mode, viewers stay on recorded VOD until they click Try Live Again—preventing oscillation during unstable upstream broadcasts, though automatic health probing could automate recovery later.
  • Next observability step: Instrumenting player startup duration, fallback trigger counts, and live-edge drift would turn the segment budget above into measured p50/p95 latency numbers.