feat: add subtitle track support to VideoPlayer and integrate with TvPage

This commit is contained in:
2026-03-11 21:55:20 +01:00
parent f6ff65094b
commit b2f40054fc
2 changed files with 100 additions and 3 deletions

View File

@@ -1,17 +1,37 @@
import { forwardRef, useEffect, useRef } from "react";
import Hls from "hls.js";
export interface SubtitleTrack {
id: number;
name: string;
lang?: string;
}
interface VideoPlayerProps {
src?: string;
poster?: string;
className?: string;
/** Seconds into the current item to seek on load (broadcast sync). */
initialOffset?: number;
/** Active subtitle track index, or -1 to disable. */
subtitleTrack?: number;
onStreamError?: () => void;
onSubtitleTracksChange?: (tracks: SubtitleTrack[]) => void;
}
const VideoPlayer = forwardRef<HTMLVideoElement, VideoPlayerProps>(
({ src, poster, className, initialOffset = 0, onStreamError }, ref) => {
(
{
src,
poster,
className,
initialOffset = 0,
subtitleTrack = -1,
onStreamError,
onSubtitleTracksChange,
},
ref,
) => {
const internalRef = useRef<HTMLVideoElement | null>(null);
const hlsRef = useRef<Hls | null>(null);
@@ -21,12 +41,20 @@ const VideoPlayer = forwardRef<HTMLVideoElement, VideoPlayerProps>(
else if (ref) ref.current = el;
};
// Apply subtitle track changes without tearing down the HLS instance
useEffect(() => {
if (hlsRef.current) {
hlsRef.current.subtitleTrack = subtitleTrack;
}
}, [subtitleTrack]);
useEffect(() => {
const video = internalRef.current;
if (!video || !src) return;
hlsRef.current?.destroy();
hlsRef.current = null;
onSubtitleTracksChange?.([]);
const isHls = src.includes(".m3u8");
@@ -41,6 +69,16 @@ const VideoPlayer = forwardRef<HTMLVideoElement, VideoPlayerProps>(
video.play().catch(() => {});
});
hls.on(Hls.Events.SUBTITLE_TRACKS_UPDATED, (_event, data) => {
onSubtitleTracksChange?.(
data.subtitleTracks.map((t) => ({
id: t.id,
name: t.name,
lang: t.lang,
})),
);
});
hls.on(Hls.Events.ERROR, (_event, data) => {
if (data.fatal) onStreamError?.();
});