frigate/web-new/src/components/player/VideoPlayer.tsx

87 lines
2.2 KiB
TypeScript
Raw Normal View History

import { useEffect, useRef, ReactElement } from "react";
2023-12-15 01:56:46 +03:00
import videojs from "video.js";
import "videojs-playlist";
import "video.js/dist/video-js.css";
import Player from "video.js/dist/types/player";
type VideoPlayerProps = {
2023-12-15 01:56:46 +03:00
children?: ReactElement | ReactElement[];
options?: {
[key: string]: any;
};
seekOptions?: {
forward?: number;
backward?: number;
};
onReady?: (player: Player) => void;
onDispose?: () => void;
};
2023-12-15 01:56:46 +03:00
export default function VideoPlayer({
children,
options,
seekOptions = { forward: 30, backward: 10 },
onReady = (_) => {},
onDispose = () => {},
}: VideoPlayerProps) {
const videoRef = useRef<HTMLDivElement | null>(null);
const playerRef = useRef<Player | null>(null);
2023-12-15 01:56:46 +03:00
useEffect(() => {
const defaultOptions = {
controls: true,
controlBar: {
skipButtons: seekOptions,
},
playbackRates: [0.5, 1, 2, 4, 8],
fluid: true,
};
2023-12-15 01:56:46 +03:00
if (!videojs.browser.IS_FIREFOX) {
defaultOptions.playbackRates.push(16);
}
2023-12-15 01:56:46 +03:00
// Make sure Video.js player is only initialized once
if (!playerRef.current) {
// The Video.js player needs to be _inside_ the component el for React 18 Strict Mode.
const videoElement = document.createElement("video-js");
// @ts-ignore we know this is a video element
videoElement.controls = true;
// @ts-ignore
videoElement.playsInline = true;
videoElement.classList.add("small-player");
videoElement.classList.add("video-js");
videoElement.classList.add("vjs-default-skin");
videoRef.current?.appendChild(videoElement);
2023-12-15 01:56:46 +03:00
const player = (playerRef.current = videojs(
videoElement,
{ ...defaultOptions, ...options },
() => {
onReady && onReady(player);
2023-12-15 01:56:46 +03:00
}
));
}
}, [options, videoRef]);
2023-12-15 01:56:46 +03:00
// Dispose the Video.js player when the functional component unmounts
useEffect(() => {
const player = playerRef.current;
2023-12-15 01:56:46 +03:00
return () => {
if (player && !player.isDisposed()) {
player.dispose();
playerRef.current = null;
onDispose();
}
};
}, [playerRef]);
2023-12-15 01:56:46 +03:00
return (
<div data-vjs-player>
<div ref={videoRef} />
{children}
</div>
);
}