BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
144 lines · 8.0 KB · download this file
// Live: the player for live_player blocks. It asks /x/live/status whether
// the stream is on (and how many are watching), shows the player or the
// picture and note, and plays the stream when a visitor presses "watch live":
// with the browser's own HLS (Safari, iPhones, Chrome 142 and later), or else
// by feeding the fMP4 pieces to a MediaSource as they are (Firefox and older
// Chromes). If the browser's own player fails or never starts (12 seconds),
// the pieces are fed to it instead, where the browser can (iPhones since iOS
// 17.1 have ManagedMediaSource). Nothing is fetched until a visitor presses play.
//
// Counting viewers: while a visitor watches, each status check carries w=ID,
// a random number made for this page (not stored anywhere else, and
// forgotten by the server a minute after the last check). Everyone sees the
// count beside the live badge.
(() => {
for (const box of document.querySelectorAll('[data-live]')) {
const base = box.dataset.live, playlist = base + 'files/live.m3u8';
const on = box.querySelector('[data-live-on]'), off = box.querySelector('[data-live-off]');
const video = box.querySelector('video'), watch = box.querySelector('[data-live-watch]'), problem = box.querySelector('[data-live-problem]');
const count = box.querySelector('[data-live-viewers]');
const id = Array.from(crypto.getRandomValues(new Uint8Array(8)), b => b.toString(16).padStart(2, '0')).join('');
let live = false, player = null, timer = null;
const say = text => { problem.textContent = text; problem.hidden = !text; };
function stop() { if (player) player.stop(); player = null; watch.hidden = false; }
function show(isLive) {
if (isLive === live) return;
live = isLive; on.hidden = !live; off.hidden = live;
if (!live) { stop(); say(''); }
}
function viewers(n) {
if (!count) return;
count.hidden = !live || !(n >= 1);
count.textContent = n === 1 ? '1 watching' : `${n} watching`;
}
async function check() {
clearTimeout(timer);
let now = false, n = 0;
try {
const r = await fetch(base + 'status' + (player ? '?w=' + id : ''), {cache: 'no-store'});
const s = r.ok ? await r.json() : {};
now = s.live === true; n = Number(s.viewers) || 0;
} catch { now = live; }
show(now); viewers(n);
timer = setTimeout(check, now ? 10000 : 5000);
}
const failed = () => { stop(); say('The stream stopped. It may be starting again: press watch live in a moment.'); };
const mse = window.MediaSource || window.ManagedMediaSource;
let usePieces = !video.canPlayType('application/vnd.apple.mpegurl');
// Playing needs the visitor's press; if the browser wants another, say so.
const play = () => video.play().catch(error => { if (player && error && error.name === 'NotAllowedError') { stop(); say('Press watch live again to start the stream.'); } });
watch.addEventListener('click', () => {
say(''); watch.hidden = true;
if (usePieces && !mse) { watch.hidden = false; say('This browser can’t play live video. Try a current Firefox, Chrome, Edge or Safari.'); return; }
if (usePieces) player = piecePlayer(video, playlist, failed);
else {
// The browser's own player; the pieces from then on if it can't.
player = nativePlayer(video, playlist, why => {
if (!player) return;
if (!mse) { stop(); say(why); return; }
usePieces = true; player.stop(); player = piecePlayer(video, playlist, failed); play();
});
}
play();
check(); // counted at once, not at the next check
});
check();
}
// The browser's own HLS. It says why it stopped through trouble(): an
// error, or nothing playing 12 seconds after pressing play.
function nativePlayer(video, url, trouble) {
let done = false;
const fail = why => { if (!done) { done = true; trouble(why); } };
const onError = () => fail('The stream couldn’t be played here' + (video.error ? ` (error ${video.error.code})` : '') + '. Try again in a moment.');
const onPlaying = () => { done = true; clearTimeout(slow); };
video.addEventListener('error', onError);
video.addEventListener('playing', onPlaying);
const slow = setTimeout(() => fail('The stream didn’t start. Try again in a moment.'), 12000);
video.src = url;
return {stop() {
done = true; clearTimeout(slow);
video.removeEventListener('error', onError); video.removeEventListener('playing', onPlaying);
video.removeAttribute('src'); video.load();
}};
}
// The playlist names an init piece (#EXT-X-MAP) and the newest pieces; each is
// appended once, in order, starting three from the newest.
function piecePlayer(video, url, failed) {
const MS = window.ManagedMediaSource || window.MediaSource;
const ms = new MS();
let stopped = false, sb = null, next = null, init = null, timer = null;
if (window.ManagedMediaSource) video.disableRemotePlayback = true;
video.src = URL.createObjectURL(ms);
const get = async (u, as) => { const r = await fetch(new URL(u, new URL(url, location.href)), {cache: 'no-store'}); if (!r.ok) throw new Error(r.status); return as === 'text' ? r.text() : new Uint8Array(await r.arrayBuffer()); };
const done = () => new Promise((ok, bad) => { sb.addEventListener('updateend', ok, {once: true}); sb.addEventListener('error', bad, {once: true}); });
const append = async data => { const d = done(); sb.appendBuffer(data); await d; };
function parse(text) {
const p = {seq: 0, dur: 2, map: null, pieces: []};
for (const line of text.split('\n').map(s => s.trim())) {
if (line.startsWith('#EXT-X-MEDIA-SEQUENCE:')) p.seq = Number(line.slice(22)) || 0;
else if (line.startsWith('#EXT-X-TARGETDURATION:')) p.dur = Number(line.slice(22)) || 2;
else if (line.startsWith('#EXT-X-MAP:')) p.map = (line.match(/URI="([^"]+)"/) || [])[1] || null;
else if (line && !line.startsWith('#')) p.pieces.push(line);
}
return p;
}
// The codecs, read from the init piece: H.264's profile and level from its avcC box, and AAC.
function codecs(data) {
const at = name => { for (let i = 4; i + 4 <= data.length; i++) if (String.fromCharCode(data[i], data[i + 1], data[i + 2], data[i + 3]) === name) return i + 4; return -1; };
const list = [], avc = at('avcC'), hex = b => b.toString(16).padStart(2, '0');
if (avc > 0) list.push('avc1.' + hex(data[avc + 1]) + hex(data[avc + 2]) + hex(data[avc + 3]));
if (at('mp4a') > 0) list.push('mp4a.40.2');
return `video/mp4; codecs="${list.join(', ')}"`;
}
async function step() {
if (stopped) return;
try {
const p = parse(await get(url, 'text'));
if (p.map && p.map !== init) {
const data = await get(p.map);
if (!sb) { const type = codecs(data); if (!MS.isTypeSupported(type)) throw new Error('codec'); sb = ms.addSourceBuffer(type); sb.mode = 'sequence'; }
init = p.map; await append(data);
}
const last = p.seq + p.pieces.length;
// First time, or fallen out of the playlist, or a new stream (numbers start again): near the newest.
if (next === null || next < p.seq || next > last) next = Math.max(p.seq, last - 3);
while (!stopped && next < last) { await append(await get(p.pieces[next - p.seq])); next++; }
const b = video.buffered;
if (b.length) {
const end = b.end(b.length - 1);
if (end - video.currentTime > p.dur * 4) video.currentTime = end - p.dur;
if (video.currentTime - b.start(0) > 60) { const d = done(); sb.remove(b.start(0), video.currentTime - 30); await d; }
}
timer = setTimeout(step, Math.max(1000, p.dur * 500));
} catch { if (!stopped) failed(); }
}
ms.addEventListener('sourceopen', step, {once: true});
return {stop() {
stopped = true; clearTimeout(timer);
try { if (ms.readyState === 'open') ms.endOfStream(); } catch { /* already ended */ }
video.removeAttribute('src'); video.load();
}};
}
})();