Files
simply-dvb/web/js/20-player.js
T
Mateusz Gruszczyński 9e65aa0103
build / test (push) Waiting to run
0.1.17
2026-11-17 16:50:28 +01:00

246 lines
9.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* simply-dvb – HLS player (hls.js / native HLS in Safari) with automatic profile selection */
(function () {
'use strict';
var CODECS = {
'H.264': 'video/mp4; codecs="avc1.640028"',
'HEVC': ['video/mp4; codecs="hvc1.1.6.L120.90"', 'video/mp4; codecs="hvc1.1.6.L123.B0"', 'video/mp4; codecs="hev1.1.6.L120.90"', 'video/mp4; codecs="hvc1.2.4.L120.90"'],
'MPEG-2': null,
'AAC': 'audio/mp4; codecs="mp4a.40.2"',
// MPEG-1 Layer II (DVB-T radio/TV sound): MSE decoders handle MP3 only, so browsers
// get it converted to AAC (cheap: the video is not touched)
'MP2': null,
'AC-3': 'audio/mp4; codecs="ac-3"',
'E-AC-3': 'audio/mp4; codecs="ec-3"',
'AAC-LATM': null
};
function mse() {
return window.ManagedMediaSource || window.MediaSource;
}
function supported(label) {
if (!label) return true;
var c = CODECS[label];
if (c === undefined) return true;
if (c === null) return false;
var M = mse();
if (!M || !M.isTypeSupported) return false;
var list = Array.isArray(c) ? c : [c];
for (var i = 0; i < list.length; i++) if (M.isTypeSupported(list[i])) return true;
return false;
}
function list(x) { return Array.isArray(x) ? x : (x ? [x] : []); }
/** Codec label without the language suffix, e.g. "MP2 (pol)" -> "MP2". */
function codec(label) { return String(label || '').replace(/ \(.*\)$/, ''); }
/** True when at least one of the audio tracks can be decoded (or there is no audio info). */
function audioOk(audio) {
var a = list(audio).map(codec);
return !a.length || a.some(supported);
}
/**
* Best profile for this browser: pass, then aac, then h264. Without ffmpeg on the server only
* "pass" is possible, so it is always tried first.
*/
function pickProfile(video, audio, transcode) {
if (transcode === false) return 'pass';
if (!supported(codec(video))) return 'h264';
if (!audioOk(audio)) return 'aac';
return 'pass';
}
function tr(x) { return window.I18N ? window.I18N.tr(x) : x; }
/** Human-readable (translated) explanation why the original stream cannot be decoded here. */
function explain(video, audio) {
var parts = [];
var v = codec(video);
if (v && !supported(v)) {
parts.push(tr(v === 'HEVC'
? 'This browser reports no HEVC (H.265) support. Chrome/Edge decode it only with hardware acceleration (on Linux: VA-API); Safari plays it natively.'
: 'This browser reports no support for ' + v + ' video.'));
}
if (!audioOk(audio)) parts.push(tr('This browser reports no support for any audio track (' + list(audio).map(codec).join(', ') + ').'));
return parts.join(' ');
}
function el(tag, cls, text) {
var e = document.createElement(tag);
if (cls) e.className = cls;
if (text != null) e.textContent = text;
return e;
}
/**
* opts: { channelId, share, token, video, audio, profile ('auto'|'pass'|'aac'|'h264'), src (full playlist URL), live, onProfile }
*/
function create(container, opts) {
container.innerHTML = '';
var video = el('video');
video.controls = true;
video.playsInline = true;
video.autoplay = true;
var overlay = el('div', 'overlay');
var badge = el('div', 'badge', opts.live === false ? 'RECORDING' : 'LIVE');
container.appendChild(video);
container.appendChild(overlay);
container.appendChild(badge);
var hls = null;
var destroyed = false;
// full video transcoding (h264) only when the browser cannot decode the video itself
var fallbackOrder = opts.transcode === false ? ['pass'] : (supported(codec(opts.video)) ? ['pass', 'aac'] : ['pass', 'aac', 'h264']);
// viewer id: lets the server stop this viewer's previous session at once when the
// channel or profile changes (frees the tuner and ffmpeg immediately)
var viewer = Math.random().toString(36).slice(2, 10) + Date.now().toString(36);
var profile = opts.profile && opts.profile !== 'auto' ? opts.profile : pickProfile(opts.video, opts.audio, opts.transcode);
var auto = !opts.profile || opts.profile === 'auto';
var retries = 0;
function status(msg, err, hint) {
overlay.innerHTML = '';
if (!msg) { overlay.classList.add('hidden'); return; }
overlay.classList.remove('hidden');
overlay.classList.toggle('err', !!err);
if (!err) overlay.appendChild(el('div', 'spinner'));
overlay.appendChild(el('div', null, msg));
if (hint) overlay.appendChild(el('div', 'hint', hint));
if (err && opts.vlcUrl) {
var a = el('a', 'btn small', 'Open in VLC');
if (window.SDVB_ICON) a.innerHTML = window.SDVB_ICON('vlc') + a.innerHTML;
a.href = opts.vlcUrl;
a.setAttribute('download', '');
overlay.appendChild(a);
}
}
/** Final failure: explain codecs and what can be done. */
function failed(msg) {
var why = explain(opts.video, opts.audio);
var hint = why;
if (opts.transcode === false) hint = (why ? why + ' ' : '') + tr('Install ffmpeg on the server to enable transcoding, or open the channel in VLC.');
status(tr('Could not play: ' + msg), true, hint);
}
function url() {
if (opts.src) return opts.src;
var q = [];
if (profile !== 'pass') q.push('profile=' + profile);
if (opts.share) q.push('share=' + encodeURIComponent(opts.share));
if (opts.token) q.push('token=' + encodeURIComponent(opts.token));
if (opts.live !== false) q.push('v=' + viewer);
return '/hls/' + opts.channelId + '/index.m3u8' + (q.length ? '?' + q.join('&') : '');
}
function nextProfile() {
if (!auto || opts.src) return false;
var i = fallbackOrder.indexOf(profile);
if (i < 0 || i + 1 >= fallbackOrder.length) return false;
profile = fallbackOrder[i + 1];
return true;
}
function leave() {
if (opts.src || opts.live === false) return;
var u = '/hls/leave?v=' + viewer;
try { if (!(navigator.sendBeacon && navigator.sendBeacon(u))) fetch(u, { method: 'POST', keepalive: true }); } catch (e) {}
}
window.addEventListener('pagehide', leave);
function teardown() {
if (hls) { try { hls.destroy(); } catch (e) {} hls = null; }
video.removeAttribute('src');
try { video.load(); } catch (e) {}
}
function start() {
teardown();
if (destroyed) return;
if (opts.onProfile) opts.onProfile(profile);
status(opts.live === false ? 'Loading recording…' : 'Tuning and buffering…');
var src = url();
if (window.Hls && window.Hls.isSupported()) {
hls = new window.Hls({
liveSyncDurationCount: 2,
liveMaxLatencyDurationCount: 6,
manifestLoadingTimeOut: 30000,
manifestLoadingMaxRetry: 3,
levelLoadingTimeOut: 20000,
fragLoadingTimeOut: 30000,
enableWorker: true,
backBufferLength: 30
});
hls.on(window.Hls.Events.MANIFEST_PARSED, function () {
var p = video.play();
if (p && p.catch) p.catch(function () { status('Click Play to start', true); });
});
hls.on(window.Hls.Events.FRAG_BUFFERED, function () { status(null); retries = 0; });
hls.on(window.Hls.Events.ERROR, function (_e, data) {
if (!data.fatal) return;
var codecProblem = data.type === window.Hls.ErrorTypes.MEDIA_ERROR ||
/codec|incompatible|bufferAddCodec|addSourceBuffer/i.test(String(data.details) + ' ' + String(data.reason || ''));
if (codecProblem && nextProfile()) {
status('Browser lacks the codec – switching to the “' + profile + '” profile…');
setTimeout(start, 300);
return;
}
if (data.type === window.Hls.ErrorTypes.MEDIA_ERROR && retries < 2) {
retries++;
hls.recoverMediaError();
return;
}
if (data.type === window.Hls.ErrorTypes.NETWORK_ERROR && retries < 4) {
retries++;
status('Connection problem – retrying (' + retries + ')…');
setTimeout(start, 2000);
return;
}
var msg = (data.response && data.response.data) || data.details || 'playback error';
failed(String(msg));
});
hls.loadSource(src);
hls.attachMedia(video);
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = src;
video.addEventListener('playing', function () { status(null); }, { once: true });
video.addEventListener('error', function () {
if (nextProfile()) { start(); return; }
failed('the stream');
}, { once: true });
var p = video.play();
if (p && p.catch) p.catch(function () {});
} else {
status('This browser does not support HLS', true);
}
}
video.addEventListener('waiting', function () { if (!overlay.classList.contains('err')) status('Buffering…'); });
video.addEventListener('playing', function () { status(null); });
start();
return {
video: video,
get profile() { return profile; },
setProfile: function (p) { auto = p === 'auto'; profile = auto ? pickProfile(opts.video, opts.audio) : p; start(); },
destroy: function () { destroyed = true; teardown(); leave(); window.removeEventListener('pagehide', leave); container.innerHTML = ''; }
};
}
window.SDVB = { createPlayer: create, pickProfile: pickProfile, codecSupported: supported, explain: explain };
// Public page /watch/<token>
document.addEventListener('DOMContentLoaded', function () {
if (!document.body.classList.contains('watch')) return;
var box = document.getElementById('player');
if (!box) return;
create(box, {
channelId: box.getAttribute('data-channel'),
share: box.getAttribute('data-share'),
video: box.getAttribute('data-video'),
audio: (box.getAttribute('data-audio') || '').split('|').filter(Boolean),
transcode: box.getAttribute('data-transcode') !== '0',
profile: 'auto'
});
});
})();