Files
tv/web/js/ui/player.js
T
2026-10-27 05:49:38 -05:00

765 lines
23 KiB
JavaScript

/*
PLAYER ENGINE — plays one Stream (docs/api.md "Stream") in a <video>.
createPlayer(video, { onState, onError, onLevels, onAudioTracks, onTorrent, onTime })
load(stream, { startAt, autoplay }) start a source (tears down the previous one)
play() / pause() / toggle()
seek(t) absolute seconds (offset-aware for remux)
currentTime() / duration() / buffered() → [[start,end]…] in absolute seconds
levels() / setLevel(i) hls.js quality, -1 = auto
audioTracks() / setAudioTrack(i)
subtitles() / setSubtitle(i) stream.subtitles, -1 = off (fetched → blob VTT)
destroy()
playback.kind:
hls hls.js (or native HLS on Safari)
file <video src>, native range seeking
remux <video src=url?start=t>, clock = offset + video.currentTime,
seeking outside the buffer reloads with a new start, duration
from `${path}/probe`
torrent poll playback.status every 1s until ready, then remux-style
(status.file.remux) or file-style playback of playback.url
Direct → fallback: when playback.fallback exists and the direct url fails
(fatal hls network error, <video> error, or no metadata within 8s) the
engine silently reloads the fallback at the same position. Anything that
fails after that is reported to onError({ fatal: true }) so the caller can
move on to the next source.
*/
import { resolveUrl } from '../config.js';
const DIRECT_TIMEOUT_MS = 8000;
const STARTUP_TIMEOUT_MS = 12000;
const TORRENT_TIMEOUT_MS = 90000;
let hlsPromise = null;
export function loadHls() {
if (window.Hls) return Promise.resolve(window.Hls);
if (hlsPromise) return hlsPromise;
hlsPromise = new Promise((resolve) => {
const s = document.createElement('script');
s.src = new URL('../../vendor/hls.min.js', import.meta.url).href;
s.async = true;
s.onload = () => resolve(window.Hls || null);
s.onerror = () => {
hlsPromise = null;
resolve(null);
};
document.head.appendChild(s);
});
return hlsPromise;
}
function abs(url) {
if (!url) return '';
if (/^(https?:|blob:|data:)/i.test(url)) return url;
try {
return resolveUrl(url);
} catch (e) {
return url;
}
}
function splitUrl(url) {
const i = url.indexOf('?');
return i < 0 ? [url, ''] : [url.slice(0, i), url.slice(i + 1)];
}
/** url with ?start=<t> set (keeps other params). */
export function withStart(url, t) {
const [path, qs] = splitUrl(url);
const q = new URLSearchParams(qs);
if (t > 0) q.set('start', String(Math.floor(t)));
else q.delete('start');
const s = q.toString();
return s ? `${path}?${s}` : path;
}
/** `/v1/remux/<token>?x` → `/v1/remux/<token>/probe?x` */
export function probeUrl(url) {
const [path, qs] = splitUrl(url);
const q = new URLSearchParams(qs);
q.delete('start');
const s = q.toString();
return `${path.replace(/\/+$/, '')}/probe${s ? `?${s}` : ''}`;
}
export function createPlayer(video, handlers = {}) {
const h = {
onState() {},
onError() {},
onLevels() {},
onAudioTracks() {},
onTorrent() {},
...handlers,
};
let token = 0;
let stream = null;
let hls = null;
let mode = ''; // hls | native-hls | file | remux
let offset = 0;
let knownDuration = 0;
let mediaUrl = '';
let usingFallback = false;
let started = false;
let wantPlay = true;
let pendingTime = null;
let timers = [];
let subIndex = -1;
let subTrackEl = null;
const subCache = new Map();
let lastTorrent = null;
let probeInfo = null; // remux/torrent ffprobe summary
let remuxAudio = null; // absolute ffprobe audio index (?audio=)
let mediaRetries = 0;
let netRetries = 0;
const emit = (phase, extra) => h.onState({ phase, ...extra });
const later = (fn, ms, my) => {
const id = setTimeout(() => {
if (my === token) fn();
}, ms);
timers.push(id);
return id;
};
const clearTimers = () => {
for (const id of timers) {
clearTimeout(id);
clearInterval(id);
}
timers = [];
};
/* ---- teardown -------------------------------------------------------- */
function teardownMedia() {
if (hls) {
try {
hls.destroy();
} catch (e) {
/* already gone */
}
hls = null;
}
video.removeAttribute('src');
try {
video.load();
} catch (e) {
/* ignore */
}
}
function removeSubTrack() {
if (subTrackEl) subTrackEl.remove();
subTrackEl = null;
}
function reset() {
token++;
clearTimers();
teardownMedia();
removeSubTrack();
mode = '';
offset = 0;
knownDuration = 0;
started = false;
pendingTime = null;
usingFallback = false;
mediaRetries = 0;
netRetries = 0;
lastTorrent = null;
probeInfo = null;
remuxAudio = null;
}
/* ---- errors ---------------------------------------------------------- */
function fail(my, message, code) {
if (my !== token) return;
// direct url failed before playing → try the server fallback once
if (!usingFallback && stream && stream.playback && stream.playback.fallback && (mode === 'hls' || mode === 'file' || mode === 'native-hls')) {
const at = pendingTime != null ? pendingTime : currentTime();
usingFallback = true;
emit('fallback', { message: 'Switching to relay…' });
startMedia(stream.playback.fallback, at, /* keepFallbackFlag */ true);
return;
}
clearTimers();
h.onError({ fatal: true, message: message || 'Playback failed', code: code || 'error', stream });
}
/* ---- media start ----------------------------------------------------- */
function armWatchdogs(my) {
// a direct url that hasn't produced metadata quickly is treated as failed
if (!usingFallback && stream.playback && stream.playback.fallback) {
later(() => {
if (video.readyState < 1) fail(my, 'Direct source timed out', 'direct-timeout');
}, DIRECT_TIMEOUT_MS, my);
}
later(() => {
if (!started && video.readyState < 3 && !(video.paused && video.readyState >= 2)) {
fail(my, 'Source stalled while starting', 'stall');
}
}, STARTUP_TIMEOUT_MS, my);
}
async function startHls(url, startAt, my) {
const Hls = await loadHls();
if (my !== token) return;
const nativeOk = video.canPlayType('application/vnd.apple.mpegurl');
if (!Hls || !Hls.isSupported()) {
if (nativeOk) {
mode = 'native-hls';
startFile(url, startAt, my);
return;
}
fail(my, 'HLS is not supported in this browser', 'unsupported');
return;
}
mode = 'hls';
const inst = new Hls({
enableWorker: true,
lowLatencyMode: false,
startLevel: -1,
capLevelToPlayerSize: true,
maxBufferLength: 30,
maxMaxBufferLength: 120,
backBufferLength: 60,
progressive: true,
startPosition: startAt > 0 ? startAt : -1,
testBandwidth: true,
fragLoadPolicy: {
default: {
maxTimeToFirstByteMs: 10000,
maxLoadTimeMs: 120000,
timeoutRetry: { maxNumRetry: 2, retryDelayMs: 0, maxRetryDelayMs: 0 },
errorRetry: { maxNumRetry: 3, retryDelayMs: 1000, maxRetryDelayMs: 8000 },
},
},
});
hls = inst;
const E = Hls.Events;
inst.on(E.MANIFEST_PARSED, () => {
if (my !== token) return;
h.onLevels(levels(), inst.currentLevel);
if (wantPlay) tryPlay(my);
});
inst.on(E.LEVEL_SWITCHED, () => my === token && h.onLevels(levels(), inst.currentLevel));
inst.on(E.AUDIO_TRACKS_UPDATED, () => my === token && h.onAudioTracks(audioTracks(), inst.audioTrack));
inst.on(E.AUDIO_TRACK_SWITCHED, () => my === token && h.onAudioTracks(audioTracks(), inst.audioTrack));
inst.on(E.ERROR, (evt, data) => {
if (my !== token || !data.fatal) return;
if (data.type === Hls.ErrorTypes.MEDIA_ERROR) {
mediaRetries++;
if (mediaRetries === 1) inst.recoverMediaError();
else if (mediaRetries === 2) {
inst.swapAudioCodec();
inst.recoverMediaError();
} else fail(my, `Media error: ${data.details}`, 'media');
return;
}
if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
// before playback started, a network error on the direct url means CORS/blocked
if (!started && !usingFallback && stream.playback.fallback) return fail(my, data.details, 'network');
const manifestish = /manifest|level/i.test(data.details || '');
if (started && !manifestish && netRetries < 3) {
netRetries++;
later(() => inst.startLoad(), 1500 * netRetries, my);
return;
}
fail(my, `Network error: ${data.details}`, 'network');
return;
}
fail(my, `Stream error: ${data.details}`, 'other');
});
inst.loadSource(url);
inst.attachMedia(video);
}
function startFile(url, startAt, my) {
if (!mode) mode = 'file';
video.src = url;
if (startAt > 0) {
pendingTime = startAt;
const seekTo = () => {
if (my !== token) return;
const d = video.duration;
let t = startAt;
if (isFinite(d) && d > 0) t = Math.min(t, Math.max(0, d - 5));
try {
video.currentTime = t;
} catch (e) {
/* ignore */
}
pendingTime = null;
};
video.addEventListener('loadedmetadata', seekTo, { once: true });
}
if (wantPlay) tryPlay(my);
}
function startRemux(url, startAt, my) {
mode = 'remux';
offset = Math.max(0, Math.floor(startAt || 0));
if (!knownDuration) {
// torrent: /v1/torrent/<token>/probe (sibling of /status); remux: <token>/probe
const pb = stream && stream.playback;
const probe = pb && pb.kind === 'torrent' && pb.status ? abs(pb.status).replace(/\/status(\?|$)/, '/probe$1') : probeUrl(url);
fetch(probe)
.then((r) => (r.ok ? r.json() : null))
.then((p) => {
if (my !== token || !p) return;
if (p.duration > 0) knownDuration = p.duration;
probeInfo = p;
emit('probe', { probe: p });
h.onAudioTracks(audioTracks(), currentAudioTrack());
})
.catch(() => {});
}
video.src = remuxSrc(offset);
syncOffset(offset, my);
if (wantPlay) tryPlay(my);
}
function startMedia(url, startAt, keepFallback) {
const prevSub = subIndex;
const keepFlag = keepFallback ? usingFallback : false;
const keptDuration = knownDuration;
const prevTorrentMode = mode === 'remux' ? 'remux' : null;
clearTimers();
teardownMedia();
token++;
const my = token;
usingFallback = keepFlag;
started = false;
pendingTime = startAt > 0 ? startAt : null;
mediaUrl = abs(url);
emit('loading', { message: usingFallback ? 'Connecting through relay…' : 'Loading…', fallback: usingFallback });
armWatchdogs(my);
const kind = stream.playback ? stream.playback.kind : 'file';
if (kind === 'hls') startHls(mediaUrl, startAt, my);
else if (kind === 'remux' || prevTorrentMode === 'remux' || (kind === 'torrent' && lastTorrent && lastTorrent.file && lastTorrent.file.remux)) {
knownDuration = keptDuration;
startRemux(mediaUrl, startAt, my);
} else {
mode = 'file';
startFile(mediaUrl, startAt, my);
}
if (prevSub >= 0) setSubtitle(prevSub);
}
function startTorrent(startAt, my) {
const statusUrl = abs(stream.playback.status);
const began = Date.now();
emit('torrent', { message: 'Connecting to peers…', torrent: null });
let polling = false;
const poll = async () => {
if (my !== token || polling) return;
polling = true;
let st = null;
try {
const r = await fetch(statusUrl);
if (r.ok) st = await r.json();
} catch (e) {
/* retry next tick */
}
polling = false;
if (my !== token) return;
if (st) {
lastTorrent = st;
h.onTorrent(st);
}
if (!mode) {
if (st && st.ready) {
if (st.file && st.file.duration > 0) knownDuration = st.file.duration;
else if (st.duration > 0) knownDuration = st.duration;
const url = abs(stream.playback.url);
mediaUrl = url;
emit('loading', { message: 'Buffering…' });
armWatchdogs(my);
if (st.file && st.file.remux) startRemux(url, startAt, my);
else {
mode = 'file';
startFile(withStart(url, 0), startAt, my);
}
if (subIndex >= 0) setSubtitle(subIndex);
} else {
emit('torrent', { message: st && st.peers ? 'Downloading…' : 'Connecting to peers…', torrent: st });
if (Date.now() - began > TORRENT_TIMEOUT_MS && !(st && st.peers > 0)) {
fail(my, 'No peers for this torrent', 'torrent-timeout');
}
}
}
};
poll();
let tick = 0;
const id = setInterval(() => {
// 1s while waiting for the torrent, every 3s once playing (stats only)
tick++;
if (!mode || tick % 3 === 0) poll();
}, 1000);
timers.push(id);
}
function tryPlay(my) {
const p = video.play();
if (p && p.catch) {
p.catch((e) => {
if (my !== token) return;
if (e && e.name === 'NotAllowedError') emit('blocked', { message: 'Press play to start' });
});
}
}
/* ---- video events ---------------------------------------------------- */
const on = (name, fn) => video.addEventListener(name, fn);
const listeners = [];
const bind = (name, fn) => {
on(name, fn);
listeners.push([name, fn]);
};
bind('loadedmetadata', () => {
if (!stream) return;
emit('metadata', { duration: duration() });
});
bind('playing', () => {
if (!stream) return;
started = true;
emit('playing');
});
bind('canplay', () => {
if (!stream) return;
if (video.paused) emit('ready');
});
bind('waiting', () => stream && emit('buffering', { message: 'Buffering…' }));
bind('pause', () => stream && emit('paused'));
bind('ended', () => stream && emit('ended'));
bind('error', () => {
if (!stream || !mode || mode === 'hls') return;
const err = video.error;
// remux: retry once from the current position before giving up
fail(token, err ? `Video error ${err.code}${err.message ? `: ${err.message}` : ''}` : 'Video error', 'video');
});
/* ---- public: load ---------------------------------------------------- */
function load(s, opts = {}) {
reset();
stream = s;
wantPlay = opts.autoplay !== false;
const startAt = Math.max(0, Number(opts.startAt) || 0);
const pb = s.playback || { kind: 'file', url: s.url };
if (pb.kind === 'torrent') {
const my = token;
pendingTime = startAt || null;
startTorrent(startAt, my);
return;
}
startMedia(pb.url, startAt, false);
}
/* ---- public: transport ----------------------------------------------- */
function currentTime() {
if (pendingTime != null && video.readyState < 1) return pendingTime;
const t = video.currentTime || 0;
return mode === 'remux' ? offset + t : t;
}
function duration() {
if (mode === 'remux') {
if (knownDuration > 0) return knownDuration;
const d = video.duration;
return isFinite(d) && d > 0 ? offset + d : 0;
}
const d = video.duration;
if (isFinite(d) && d > 0) return d;
return knownDuration || 0;
}
function buffered() {
const out = [];
const b = video.buffered;
const add = mode === 'remux' ? offset : 0;
for (let i = 0; i < b.length; i++) out.push([b.start(i) + add, b.end(i) + add]);
return out;
}
function seek(t) {
if (!stream || !mode) return;
const d = duration();
if (d > 0) t = Math.min(t, Math.max(0, d - 1));
t = Math.max(0, t);
if (mode !== 'remux') {
try {
video.currentTime = t;
} catch (e) {
/* not seekable yet */
}
return;
}
const rel = t - offset;
const b = video.buffered;
for (let i = 0; i < b.length; i++) {
if (rel >= b.start(i) && rel <= b.end(i) - 0.5) {
video.currentTime = rel;
return;
}
}
reloadRemux(t);
}
// the remux begins at the keyframe at/before t, not t itself: ask the server which one
function syncOffset(t, my) {
if (!(t > 0)) return;
const pb = stream && stream.playback;
const base = pb && pb.kind === 'torrent' && pb.status ? abs(pb.status).replace(/\/status(\?|$)/, '/probe$1') : probeUrl(mediaUrl);
fetch(`${base}${base.includes('?') ? '&' : '?'}start=${t}`)
.then((r) => (r.ok ? r.json() : null))
.then((p) => {
if (my === token && p && Number.isFinite(p.keyframe) && p.keyframe <= t) offset = p.keyframe;
})
.catch(() => {});
}
function remuxSrc(t) {
let u = withStart(mediaUrl, t);
if (remuxAudio != null) u += `${u.includes('?') ? '&' : '?'}audio=${remuxAudio}`;
return u;
}
// restart the remux at t (seek outside the buffer, or audio track change)
function reloadRemux(t) {
const my = ++token;
clearTimers();
const wasPlaying = !video.paused || wantPlay;
wantPlay = wasPlaying;
offset = Math.floor(t);
pendingTime = offset;
started = false;
emit('seeking', { message: 'Seeking…' });
video.src = remuxSrc(offset);
syncOffset(offset, my);
armWatchdogs(my);
if (lastTorrent || (stream.playback && stream.playback.kind === 'torrent')) {
// keep torrent stats ticking after a remux seek
const statusUrl = abs(stream.playback.status);
const id = setInterval(() => {
fetch(statusUrl)
.then((r) => (r.ok ? r.json() : null))
.then((st) => {
if (st && my === token) {
lastTorrent = st;
h.onTorrent(st);
}
})
.catch(() => {});
}, 3000);
timers.push(id);
}
video.addEventListener('loadedmetadata', () => my === token && (pendingTime = null), { once: true });
if (wasPlaying) tryPlay(my);
}
function play() {
wantPlay = true;
tryPlay(token);
}
function pause() {
wantPlay = false;
video.pause();
}
function toggle() {
if (video.paused || video.ended) play();
else pause();
}
/* ---- public: tracks -------------------------------------------------- */
function levels() {
if (!hls || !hls.levels) return [];
return hls.levels.map((l, i) => ({
index: i,
height: l.height || 0,
width: l.width || 0,
bitrate: l.bitrate || 0,
label: l.height ? `${l.height}p` : l.bitrate ? `${Math.round(l.bitrate / 1000)} kbps` : `Level ${i + 1}`,
}));
}
function setLevel(i) {
if (!hls) return;
hls.currentLevel = i;
hls.loadLevel = i;
h.onLevels(levels(), i);
}
function currentLevel() {
if (!hls) return -1;
return hls.autoLevelEnabled ? -1 : hls.currentLevel;
}
function playingLevel() {
if (!hls || hls.currentLevel < 0 || !hls.levels) return null;
return levels()[hls.currentLevel] || null;
}
function probeAudio() {
return mode === 'remux' && probeInfo && Array.isArray(probeInfo.audio) ? probeInfo.audio : [];
}
function audioTracks() {
if (hls && hls.audioTracks) {
return hls.audioTracks.map((t, i) => ({ index: i, lang: t.lang || '', label: t.name || t.lang || `Track ${i + 1}` }));
}
return probeAudio().map((a, i) => ({
index: i,
lang: a.lang || '',
label: a.title || [a.lang ? a.lang.toUpperCase() : `Track ${i + 1}`, a.codec, a.channels ? `${a.channels}ch` : ''].filter(Boolean).join(' · '),
}));
}
function setAudioTrack(i) {
if (hls) {
hls.audioTrack = i;
return;
}
const list = probeAudio();
if (!list[i] || list[i].index === remuxAudio) return;
remuxAudio = list[i].index;
reloadRemux(currentTime());
h.onAudioTracks(audioTracks(), i);
}
function currentAudioTrack() {
if (hls) return hls.audioTrack;
const list = probeAudio();
if (!list.length) return -1;
if (remuxAudio != null) return list.findIndex((a) => a.index === remuxAudio);
const def = list.findIndex((a) => a.default);
return def >= 0 ? def : 0;
}
function subtitles() {
return ((stream && stream.subtitles) || []).map((s, i) => ({
index: i,
lang: s.lang || s.language || '',
label: s.label || s.name || s.lang || `Subtitles ${i + 1}`,
url: s.url,
}));
}
async function vttBlob(url) {
if (subCache.has(url)) return subCache.get(url);
const p = fetch(abs(url))
.then((r) => {
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.text();
})
.then((text) => {
if (!/^\uFEFF?WEBVTT/.test(text)) text = `WEBVTT\n\n${text.replace(/(\d\d:\d\d:\d\d),(\d\d\d)/g, '$1.$2')}`;
return URL.createObjectURL(new Blob([text], { type: 'text/vtt' }));
});
subCache.set(url, p);
p.catch(() => subCache.delete(url));
return p;
}
/** Remux restarts the clock at `offset`; shift cues so they still line up. */
function shiftTrack(track) {
if (mode !== 'remux' || !offset || !track || !track.cues) return;
const my = offset;
for (const cue of Array.from(track.cues)) {
if (cue._orig == null) {
cue._orig = [cue.startTime, cue.endTime];
}
cue.startTime = cue._orig[0] - my;
cue.endTime = cue._orig[1] - my;
}
}
async function setSubtitle(i) {
subIndex = i;
removeSubTrack();
for (const t of Array.from(video.textTracks)) t.mode = 'disabled';
const list = subtitles();
if (i < 0 || !list[i]) return true;
const my = token;
let url;
try {
url = await vttBlob(list[i].url);
} catch (e) {
return false;
}
if (my !== token || subIndex !== i) return true;
const el = document.createElement('track');
el.kind = 'subtitles';
el.label = list[i].label;
if (list[i].lang) el.srclang = list[i].lang;
el.src = url;
el.default = true;
el.addEventListener('load', () => {
el.track.mode = 'showing';
shiftTrack(el.track);
});
video.appendChild(el);
subTrackEl = el;
el.track.mode = 'showing';
return true;
}
// re-align subtitle cues after a remux reload
bind('loadeddata', () => {
if (subTrackEl && subTrackEl.track) shiftTrack(subTrackEl.track);
});
function stop() {
reset();
stream = null;
}
function destroy() {
reset();
stream = null;
for (const [n, fn] of listeners) video.removeEventListener(n, fn);
for (const p of subCache.values()) p.then((u) => URL.revokeObjectURL(u)).catch(() => {});
subCache.clear();
}
return {
load,
stop,
play,
pause,
toggle,
seek,
currentTime,
duration,
buffered,
levels,
setLevel,
currentLevel,
playingLevel,
audioTracks,
setAudioTrack,
currentAudioTrack,
subtitles,
setSubtitle,
destroy,
get stream() {
return stream;
},
get mode() {
return mode;
},
get usingFallback() {
return usingFallback;
},
get torrent() {
return lastTorrent;
},
get started() {
return started;
},
};
}