qhkr2z22o: Prefer hls.js and fall back to the thumbnail when video cannot play

This commit is contained in:
2026-10-19 17:05:16 -06:00
parent ab78a61851
commit fd760e610a
3 changed files with 44 additions and 28 deletions
+32 -23
View File
@@ -9,9 +9,12 @@ export interface VideoPlayerProps {
label: string;
}
const UNPLAYABLE = "Video can't be played here.";
/**
* Real <video controls>. Native HLS where the browser has it, otherwise hls.js,
* loaded only when a video card mounts. Never autoplays.
* Real <video controls>. hls.js (loaded only when a video card mounts) is
* preferred; native HLS is used only where hls.js is unsupported. Never
* autoplays. Any failure falls back to the thumbnail with a short note.
*/
export function VideoPlayer({ hlsUrl, poster, label }: VideoPlayerProps) {
const ref = useRef<HTMLVideoElement>(null);
@@ -22,28 +25,26 @@ export function VideoPlayer({ hlsUrl, poster, label }: VideoPlayerProps) {
if (!video) return;
let destroy: (() => void) | undefined;
let cancelled = false;
const native = supportsNativeHls(video);
if (native) {
if (choosePlayback(hlsUrl, { nativeHls: true, hlsJsSupported: false }) === "native") {
video.src = hlsUrl;
}
return;
}
import("hls.js")
.then(({ default: Hls }) => {
if (cancelled) return;
const mode = choosePlayback(hlsUrl, { nativeHls: false, hlsJsSupported: Hls.isSupported() });
if (mode !== "hlsjs") {
setFailed(true);
return;
}
const hls = new Hls();
hls.on(Hls.Events.ERROR, (_e, data) => {
if (data.fatal) setFailed(true);
const mode = choosePlayback(hlsUrl, {
nativeHls: supportsNativeHls(video),
hlsJsSupported: Hls.isSupported(),
});
hls.loadSource(hlsUrl);
hls.attachMedia(video);
destroy = () => hls.destroy();
if (mode === "hlsjs") {
const hls = new Hls();
hls.on(Hls.Events.ERROR, (_e, data) => {
if (data.fatal) setFailed(true);
});
hls.loadSource(hlsUrl);
hls.attachMedia(video);
destroy = () => hls.destroy();
} else if (mode === "native") {
video.src = hlsUrl;
} else {
setFailed(true);
}
})
.catch(() => setFailed(true));
return () => {
@@ -52,9 +53,16 @@ export function VideoPlayer({ hlsUrl, poster, label }: VideoPlayerProps) {
};
}, [hlsUrl]);
if (failed && poster) {
// eslint-disable-next-line @next/next/no-img-element
return <img src={poster} alt="Video thumbnail" loading="lazy" />;
if (failed) {
return (
<div>
{poster ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={poster} alt="Video thumbnail" loading="lazy" />
) : null}
<p role="status">{UNPLAYABLE}</p>
</div>
);
}
return (
<video
@@ -64,6 +72,7 @@ export function VideoPlayer({ hlsUrl, poster, label }: VideoPlayerProps) {
preload="none"
poster={poster ?? undefined}
aria-label={label}
onError={() => setFailed(true)}
/>
);
}