import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, type RefObject, } from 'react'; import shaka from 'shaka-player'; import type {VideoRef, ReactVideoProps, VideoMetadata} from './types'; const Video = forwardRef( ( { source, paused, muted, volume, rate, repeat, controls, showNotificationControls = false, poster, fullscreen, fullscreenAutorotate, fullscreenOrientation, onBuffer, onLoad, onProgress, onPlaybackRateChange, onError, onReadyForDisplay, onSeek, onVolumeChange, onEnd, onPlaybackStateChanged, }, ref, ) => { const nativeRef = useRef(null); const shakaPlayerRef = useRef(null); const isSeeking = useRef(false); const seek = useCallback( async (time: number, _tolerance?: number) => { if (isNaN(time)) { throw new Error('Specified time is not a number'); } if (!nativeRef.current) { console.warn('Video Component is not mounted'); return; } time = Math.max(0, Math.min(time, nativeRef.current.duration)); nativeRef.current.currentTime = time; onSeek?.({seekTime: time, currentTime: nativeRef.current.currentTime}); }, [onSeek], ); const pause = useCallback(() => { if (!nativeRef.current) { return; } nativeRef.current.pause(); }, []); const resume = useCallback(() => { if (!nativeRef.current) { return; } nativeRef.current.play(); }, []); const setVolume = useCallback((vol: number) => { if (!nativeRef.current) { return; } nativeRef.current.volume = Math.max(0, Math.min(vol, 100)) / 100; }, []); const getCurrentPosition = useCallback(async () => { if (!nativeRef.current) { throw new Error('Video Component is not mounted'); } return nativeRef.current.currentTime; }, []); const unsupported = useCallback(() => { throw new Error('This is unsupported on the web'); }, []); // Stock this in a ref to not invalidate memoization when those changes. const fsPrefs = useRef({ fullscreenAutorotate, fullscreenOrientation, }); fsPrefs.current = { fullscreenOrientation, fullscreenAutorotate, }; const setFullScreen = useCallback( ( newVal: boolean, orientation?: ReactVideoProps['fullscreenOrientation'], autorotate?: boolean, ) => { orientation ??= fsPrefs.current.fullscreenOrientation; autorotate ??= fsPrefs.current.fullscreenAutorotate; const run = async () => { try { if (newVal) { await nativeRef.current?.requestFullscreen({ navigationUI: 'hide', }); if (orientation === 'all' || !orientation || autorotate) { screen.orientation.unlock(); } else { await screen.orientation.lock(orientation); } } else { if (document.fullscreenElement) { await document.exitFullscreen(); } screen.orientation.unlock(); } } catch (e) { // Changing fullscreen status without a button click is not allowed so it throws. // Some browsers also used to throw when locking screen orientation was not supported. console.error('Could not toggle fullscreen/screen lock status', e); } }; run(); }, [], ); useEffect(() => { setFullScreen( fullscreen || false, fullscreenOrientation, fullscreenAutorotate, ); }, [ setFullScreen, fullscreen, fullscreenAutorotate, fullscreenOrientation, ]); const presentFullscreenPlayer = useCallback( () => setFullScreen(true), [setFullScreen], ); const dismissFullscreenPlayer = useCallback( () => setFullScreen(false), [setFullScreen], ); useImperativeHandle( ref, () => ({ seek, pause, resume, setVolume, getCurrentPosition, presentFullscreenPlayer, dismissFullscreenPlayer, setFullScreen, save: unsupported, restoreUserInterfaceForPictureInPictureStopCompleted: unsupported, nativeHtmlVideoRef: nativeRef, }), [ seek, pause, resume, unsupported, setVolume, getCurrentPosition, nativeRef, presentFullscreenPlayer, dismissFullscreenPlayer, setFullScreen, ], ); useEffect(() => { if (paused) { pause(); } else { resume(); } }, [paused, pause, resume]); useEffect(() => { if (volume === undefined) { return; } setVolume(volume); }, [volume, setVolume]); // we use a ref to prevent triggerring the useEffect when the component rerender with a non-stable `onPlaybackStateChanged`. const playbackStateRef = useRef(onPlaybackStateChanged); playbackStateRef.current = onPlaybackStateChanged; useEffect(() => { // Not sure about how to do this but we want to wait for nativeRef to be initialized setTimeout(() => { if (!nativeRef.current) { return; } // Set play state to the player's value (if autoplay is denied) // This is useful if our UI is in a play state but autoplay got denied so // the video is actaully in a paused state. playbackStateRef.current?.({ isPlaying: !nativeRef.current.paused, isSeeking: isSeeking.current, }); }, 500); }, []); useEffect(() => { if (!nativeRef.current || rate === undefined) { return; } nativeRef.current.playbackRate = rate; }, [rate]); useEffect(() => { if (!nativeRef.current || rate === undefined) { console.log("Not starting shaka yet bc undefined") return; } if (shakaPlayerRef.current) { shakaPlayerRef.current.unload() } shakaPlayerRef.current = new shaka.Player(); shakaPlayerRef.current.addEventListener("error", (event) => { //@ts-ignore const shakaError = event.detail; console.error('Shaka Player Error', shakaError); onError?.({ error: { errorString: shakaError.message, code: shakaError.code, }, }); }); console.log("Initializing and attaching shaka") shakaPlayerRef.current.attach(nativeRef.current, true); //@ts-ignore shakaPlayerRef.current.load(source?.uri).then( () => console.log(`${source?.uri} finished loading`) ); console.log("Started shaka loading"); }, [source, nativeRef.current]) useMediaSession(source?.metadata, nativeRef, showNotificationControls); return (