fallback of formats

This commit is contained in:
Simon
2026-06-23 06:59:40 +00:00
parent bec981a262
commit a251b274db
2 changed files with 276 additions and 220 deletions

View File

@@ -46,13 +46,17 @@ App.player = App.player || {};
return; return;
} }
const useMobileFullscreen = isMobilePlayback() || isTvPlayback(); const useMobileFullscreen = isMobilePlayback() || isTvPlayback();
let playbackStarted = false;
if (!state.playerHome) { if (!state.playerHome) {
state.playerHome = video.parentElement; state.playerHome = video.parentElement;
} }
// Normalize stream URL + optional referer forwarding. // Resolve an ordered list of candidate sources (best first). When a
// source's URL fails to load we fall back to the next one.
let sources = [];
if (App.videos && typeof App.videos.resolveStreamSources === 'function') {
sources = App.videos.resolveStreamSources(source);
} else {
let resolved = { url: '', referer: '' }; let resolved = { url: '', referer: '' };
if (App.videos && typeof App.videos.resolveStreamSource === 'function') { if (App.videos && typeof App.videos.resolveStreamSource === 'function') {
resolved = App.videos.resolveStreamSource(source); resolved = App.videos.resolveStreamSource(source);
@@ -61,59 +65,15 @@ App.player = App.player || {};
} else if (source && typeof source === 'object') { } else if (source && typeof source === 'object') {
resolved.url = source.url || ''; resolved.url = source.url || '';
} }
if (!resolved.referer && resolved.url) { if (resolved.url) sources = [resolved];
try {
resolved.referer = `${new URL(resolved.url).origin}/`;
} catch (err) {
resolved.referer = '';
} }
} if (!sources.length) {
if (!resolved.url) {
if (App.ui && App.ui.showError) { if (App.ui && App.ui.showError) {
App.ui.showError('Unable to play this stream.'); App.ui.showError('Unable to play this stream.');
} }
clearLoading(); clearLoading();
return; return;
} }
const refererParam = resolved.referer ? `&referer=${encodeURIComponent(resolved.referer)}` : '';
const userAgentParam = resolved.userAgent ? `&User-Agent=${encodeURIComponent(resolved.userAgent)}` : '';
const liveParam = resolved.isLive ? '&live=1' : '';
const streamUrl = `/api/stream?url=${encodeURIComponent(resolved.url)}${refererParam}${userAgentParam}${liveParam}`;
let isHls = /\.m3u8($|\?)/i.test(resolved.url);
let isDirectMedia = /\.(mp4|m4v|m4s|webm|ts|mov)($|\?)/i.test(resolved.url);
// Live cam streams resolve (server-side) to HLS; treat them as HLS up
// front so we skip the content-type HEAD probe and go straight to it.
if (resolved.isLive) {
isHls = true;
isDirectMedia = false;
}
// Cleanup existing player instance to prevent aborted bindings.
if (state.hlsPlayer) {
state.hlsPlayer.stopLoad();
state.hlsPlayer.detachMedia();
state.hlsPlayer.destroy();
state.hlsPlayer = null;
}
// Reset the video element before re-binding a new source.
video.pause();
video.removeAttribute('src');
video.load();
if (!isHls) {
try {
const headResp = await fetch(streamUrl, { method: 'HEAD' });
const contentType = headResp.headers.get('Content-Type') || '';
if (contentType.includes('application/vnd.apple.mpegurl')) {
isHls = true;
} else if (contentType.startsWith('video/') || contentType.startsWith('audio/')) {
isDirectMedia = true;
}
} catch (err) {
console.warn('Failed to detect stream type', err);
}
}
if (useMobileFullscreen) { if (useMobileFullscreen) {
const host = getMobileVideoHost(); const host = getMobileVideoHost();
@@ -149,6 +109,76 @@ App.player = App.player || {};
} }
}; };
const failPlayback = (message) => {
clearLoading();
if (App.ui && App.ui.showError) {
App.ui.showError(message);
}
App.player.close();
};
// Attempts to play a single source. On a fatal failure it advances to
// the next candidate, or reports an error once the list is exhausted.
const attempt = async (index) => {
const resolved = sources[index];
const hasNext = index + 1 < sources.length;
let playbackStarted = false;
let settled = false;
// Advances to the next source (or fails) exactly once per attempt,
// guarding against overlapping error callbacks.
const advanceOrFail = (message) => {
if (settled) return;
settled = true;
if (hasNext) {
attempt(index + 1);
} else {
failPlayback(message);
}
};
const refererParam = resolved.referer ? `&referer=${encodeURIComponent(resolved.referer)}` : '';
const userAgentParam = resolved.userAgent ? `&User-Agent=${encodeURIComponent(resolved.userAgent)}` : '';
const liveParam = resolved.isLive ? '&live=1' : '';
const streamUrl = `/api/stream?url=${encodeURIComponent(resolved.url)}${refererParam}${userAgentParam}${liveParam}`;
let isHls = /\.m3u8($|\?)/i.test(resolved.url);
let isDirectMedia = /\.(mp4|m4v|m4s|webm|ts|mov)($|\?)/i.test(resolved.url);
// Live cam streams resolve (server-side) to HLS; treat them as HLS up
// front so we skip the content-type HEAD probe and go straight to it.
if (resolved.isLive) {
isHls = true;
isDirectMedia = false;
}
// Drop the previous attempt's error handler and player instance
// before rebinding so stale callbacks don't double-advance.
video.onerror = null;
if (state.hlsPlayer) {
state.hlsPlayer.stopLoad();
state.hlsPlayer.detachMedia();
state.hlsPlayer.destroy();
state.hlsPlayer = null;
}
// Reset the video element before re-binding a new source.
video.pause();
video.removeAttribute('src');
video.load();
if (!isHls) {
try {
const headResp = await fetch(streamUrl, { method: 'HEAD' });
const contentType = headResp.headers.get('Content-Type') || '';
if (contentType.includes('application/vnd.apple.mpegurl')) {
isHls = true;
} else if (contentType.startsWith('video/') || contentType.startsWith('audio/')) {
isDirectMedia = true;
}
} catch (err) {
console.warn('Failed to detect stream type', err);
}
}
const startPlayback = () => { const startPlayback = () => {
if (playbackStarted) return; if (playbackStarted) return;
playbackStarted = true; playbackStarted = true;
@@ -212,11 +242,7 @@ App.player = App.player || {};
startNative(); startNative();
return; return;
} }
clearLoading(); advanceOrFail('Unable to play this stream.');
if (App.ui && App.ui.showError) {
App.ui.showError('Unable to play this stream.');
}
App.player.close();
} }
}); });
return true; return true;
@@ -226,12 +252,12 @@ App.player = App.player || {};
if (!startHls(true)) { if (!startHls(true)) {
if (video.canPlayType('application/vnd.apple.mpegurl')) { if (video.canPlayType('application/vnd.apple.mpegurl')) {
startNative(); startNative();
} else if (hasNext) {
advanceOrFail('HLS is not supported in this browser.');
return;
} else { } else {
console.error("HLS not supported in this browser."); console.error("HLS not supported in this browser.");
if (App.ui && App.ui.showError) { failPlayback('HLS is not supported in this browser.');
App.ui.showError('HLS is not supported in this browser.');
}
clearLoading();
return; return;
} }
} }
@@ -243,12 +269,11 @@ App.player = App.player || {};
if (!usingHls && canUseHls && !hlsTried && !isDirectMedia) { if (!usingHls && canUseHls && !hlsTried && !isDirectMedia) {
if (startHls(true)) return; if (startHls(true)) return;
} }
clearLoading(); advanceOrFail('Video failed to load.');
if (App.ui && App.ui.showError) {
App.ui.showError('Video failed to load.');
}
App.player.close();
}; };
};
attempt(0);
if (state.playerMode === 'modal') { if (state.playerMode === 'modal') {
modal.style.display = 'flex'; modal.style.display = 'flex';

View File

@@ -565,18 +565,40 @@ App.videos = App.videos || {};
return 0; return 0;
}; };
App.videos.pickBestFormat = function(formats, preferredHeight) { const headerValue = function(headers, name) {
if (!Array.isArray(formats) || formats.length === 0) return null; if (!headers) return '';
const candidates = formats.filter((fmt) => fmt && fmt.url); return headers[name] || headers[name.toLowerCase()] || '';
if (!candidates.length) return null; };
const videoCandidates = candidates.filter((fmt) => {
const videoExt = String(fmt.video_ext || '').toLowerCase(); const deriveReferer = function(url) {
const vcodec = String(fmt.vcodec || '').toLowerCase(); if (!url) return '';
try {
return `${new URL(url).origin}/`;
} catch (err) {
return '';
}
};
// Ranks the playable formats best-first so callers can fall back to the
// next candidate when a URL fails. Quality is the primary key; when several
// formats share the same quality the one that appears later in the source
// list is preferred (start with the last one). When a preferred height is
// set, formats at or below it come first (best of those first), followed by
// anything above it ordered closest-to-preferred first as a last resort.
App.videos.rankFormats = function(formats, preferredHeight) {
if (!Array.isArray(formats) || formats.length === 0) return [];
const candidates = formats
.map((fmt, index) => ({ fmt, index }))
.filter((entry) => entry.fmt && entry.fmt.url);
if (!candidates.length) return [];
const videoCandidates = candidates.filter((entry) => {
const videoExt = String(entry.fmt.video_ext || '').toLowerCase();
const vcodec = String(entry.fmt.vcodec || '').toLowerCase();
if (videoExt && videoExt !== 'none') return true; if (videoExt && videoExt !== 'none') return true;
if (vcodec && vcodec !== 'none') return true; if (vcodec && vcodec !== 'none') return true;
return false; return false;
}); });
let pool = videoCandidates.length ? videoCandidates : candidates; const pool = videoCandidates.length ? videoCandidates : candidates;
const score = (fmt) => { const score = (fmt) => {
const height = App.videos.coerceNumber(fmt.height || fmt.quality); const height = App.videos.coerceNumber(fmt.height || fmt.quality);
const width = App.videos.coerceNumber(fmt.width); const width = App.videos.coerceNumber(fmt.width);
@@ -585,89 +607,98 @@ App.videos = App.videos || {};
const fps = App.videos.coerceNumber(fmt.fps); const fps = App.videos.coerceNumber(fmt.fps);
return [size, bitrate, fps]; return [size, bitrate, fps];
}; };
// Tie-break on the original index so equal-quality formats start with
// the last one in the source list.
const compare = (a, b, descending) => {
const sa = score(a.fmt);
const sb = score(b.fmt);
for (let i = 0; i < sa.length; i++) {
if (sa[i] !== sb[i]) return descending ? sb[i] - sa[i] : sa[i] - sb[i];
}
return b.index - a.index;
};
if (preferredHeight) { if (preferredHeight) {
const atOrBelow = pool.filter((fmt) => { const atOrBelow = [];
const size = score(fmt)[0]; const above = [];
return size > 0 && size <= preferredHeight; pool.forEach((entry) => {
}); const size = score(entry.fmt)[0];
if (atOrBelow.length) { if (size > 0 && size <= preferredHeight) {
pool = atOrBelow; atOrBelow.push(entry);
} else { } else {
// Nothing at or below the preferred quality, fall back to the lowest available. above.push(entry);
const lowest = pool.reduce((min, fmt) => {
if (!min) return fmt;
return score(fmt)[0] < score(min)[0] ? fmt : min;
}, null);
return lowest;
} }
});
atOrBelow.sort((a, b) => compare(a, b, true));
above.sort((a, b) => compare(a, b, false));
return atOrBelow.concat(above).map((entry) => entry.fmt);
} }
return pool.reduce((best, fmt) => { return pool.slice().sort((a, b) => compare(a, b, true)).map((entry) => entry.fmt);
if (!best) return fmt;
const bestScore = score(best);
const curScore = score(fmt);
for (let i = 0; i < curScore.length; i++) {
if (curScore[i] > bestScore[i]) return fmt;
if (curScore[i] < bestScore[i]) return best;
}
return best;
}, null);
}; };
App.videos.resolveStreamSource = function(videoOrUrl, options) { App.videos.pickBestFormat = function(formats, preferredHeight) {
const ranked = App.videos.rankFormats(formats, preferredHeight);
return ranked.length ? ranked[0] : null;
};
// Resolves an ordered list of stream source candidates (best first). The
// player walks this list and falls back to the next entry when a URL fails.
App.videos.resolveStreamSources = function(videoOrUrl, options) {
const applyPreferredQuality = !options || options.applyPreferredQuality !== false; const applyPreferredQuality = !options || options.applyPreferredQuality !== false;
let sourceUrl = '';
let referer = '';
let userAgent = '';
const isLive = !!(videoOrUrl && typeof videoOrUrl === 'object' && const isLive = !!(videoOrUrl && typeof videoOrUrl === 'object' &&
(videoOrUrl.isLive || (videoOrUrl.meta && videoOrUrl.meta.isLive))); (videoOrUrl.isLive || (videoOrUrl.meta && videoOrUrl.meta.isLive)));
if (typeof videoOrUrl === 'string') { if (typeof videoOrUrl === 'string') {
sourceUrl = videoOrUrl; return videoOrUrl ? [{ url: videoOrUrl, referer: deriveReferer(videoOrUrl), userAgent: '', isLive }] : [];
} else if (videoOrUrl && typeof videoOrUrl === 'object') { }
if (!videoOrUrl || typeof videoOrUrl !== 'object') return [];
const meta = videoOrUrl.meta || videoOrUrl; const meta = videoOrUrl.meta || videoOrUrl;
sourceUrl = meta.url || videoOrUrl.url || ''; const metaReferer = headerValue(meta.http_headers, 'Referer');
const metaUserAgent = headerValue(meta.http_headers, 'User-Agent');
let preferredHeight = null; let preferredHeight = null;
if (applyPreferredQuality) { if (applyPreferredQuality) {
const preferredQuality = App.storage.getPreferredQuality(); const preferredQuality = App.storage.getPreferredQuality();
preferredHeight = preferredQuality === 'auto' ? null : App.videos.coerceNumber(preferredQuality); preferredHeight = preferredQuality === 'auto' ? null : App.videos.coerceNumber(preferredQuality);
} }
const best = App.videos.pickBestFormat(meta.formats, preferredHeight);
if (best && best.url) { const sources = App.videos.rankFormats(meta.formats, preferredHeight).map((fmt) => {
sourceUrl = best.url; const referer = headerValue(fmt.http_headers, 'Referer') || metaReferer || deriveReferer(fmt.url);
if (best.http_headers && (best.http_headers.Referer || best.http_headers.referer)) { const userAgent = headerValue(fmt.http_headers, 'User-Agent') || metaUserAgent;
referer = best.http_headers.Referer || best.http_headers.referer; return { url: fmt.url, referer, userAgent, isLive };
} });
if (best.http_headers && (best.http_headers['User-Agent'] || best.http_headers['user-agent'])) {
userAgent = best.http_headers['User-Agent'] || best.http_headers['user-agent']; if (!sources.length) {
const fallbackUrl = meta.url || videoOrUrl.url || '';
if (fallbackUrl) {
sources.push({
url: fallbackUrl,
referer: metaReferer || deriveReferer(fallbackUrl),
userAgent: metaUserAgent,
isLive
});
} }
} }
if (!referer && meta.http_headers && (meta.http_headers.Referer || meta.http_headers.referer)) { return sources;
referer = meta.http_headers.Referer || meta.http_headers.referer; };
}
if (!userAgent && meta.http_headers && (meta.http_headers['User-Agent'] || meta.http_headers['user-agent'])) { App.videos.resolveStreamSource = function(videoOrUrl, options) {
userAgent = meta.http_headers['User-Agent'] || meta.http_headers['user-agent']; const sources = App.videos.resolveStreamSources(videoOrUrl, options);
} return sources.length ? sources[0] : { url: '', referer: '', userAgent: '', isLive: false };
}
if (!referer && sourceUrl) {
try {
referer = `${new URL(sourceUrl).origin}/`;
} catch (err) {
referer = '';
}
}
return { url: sourceUrl, referer, userAgent, isLive };
}; };
// Builds a proxied stream URL. Extra params other than `url` are forwarded // Builds a proxied stream URL. Extra params other than `url` are forwarded
// by the backend as request headers, so use real header names here. // by the backend as request headers, so use real header names here.
App.videos.buildStreamUrl = function(videoOrUrl, options) { App.videos.buildStreamUrlFromSource = function(resolved) {
const resolved = App.videos.resolveStreamSource(videoOrUrl, options); if (!resolved || !resolved.url) return '';
if (!resolved.url) return '';
const refererParam = resolved.referer ? `&referer=${encodeURIComponent(resolved.referer)}` : ''; const refererParam = resolved.referer ? `&referer=${encodeURIComponent(resolved.referer)}` : '';
const userAgentParam = resolved.userAgent ? `&User-Agent=${encodeURIComponent(resolved.userAgent)}` : ''; const userAgentParam = resolved.userAgent ? `&User-Agent=${encodeURIComponent(resolved.userAgent)}` : '';
const liveParam = resolved.isLive ? '&live=1' : ''; const liveParam = resolved.isLive ? '&live=1' : '';
return `/api/stream?url=${encodeURIComponent(resolved.url)}${refererParam}${userAgentParam}${liveParam}`; return `/api/stream?url=${encodeURIComponent(resolved.url)}${refererParam}${userAgentParam}${liveParam}`;
}; };
App.videos.buildStreamUrl = function(videoOrUrl, options) {
return App.videos.buildStreamUrlFromSource(App.videos.resolveStreamSource(videoOrUrl, options));
};
App.videos.downloadVideo = function(video) { App.videos.downloadVideo = function(video) {
if (!video) return; if (!video) return;
const streamUrl = App.videos.buildStreamUrl(video, { applyPreferredQuality: false }); const streamUrl = App.videos.buildStreamUrl(video, { applyPreferredQuality: false });