react-native-video/src/Video.web.tsx

437 lines
11 KiB
TypeScript
Raw Normal View History

import React, {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useRef,
2024-06-30 07:25:49 -06:00
type RefObject,
} from 'react';
2024-10-13 01:09:57 -06:00
import shaka from 'shaka-player/ui';
2024-10-12 23:48:55 -06:00
import type { VideoRef, ReactVideoProps, VideoMetadata } from './types';
const Video = forwardRef<VideoRef, ReactVideoProps>(
(
{
source,
paused,
muted,
volume,
2024-06-30 05:38:52 -06:00
rate,
repeat,
controls,
2024-06-30 07:25:49 -06:00
showNotificationControls = false,
2024-06-30 05:38:52 -06:00
poster,
2024-07-10 04:18:21 -06:00
fullscreen,
fullscreenAutorotate,
fullscreenOrientation,
onBuffer,
onLoad,
onProgress,
2024-10-13 00:44:54 -06:00
// onPlaybackRateChange,
onError,
2024-06-30 05:25:43 -06:00
onReadyForDisplay,
onSeek,
2024-10-13 00:44:54 -06:00
// onVolumeChange,
onEnd,
},
ref,
) => {
const nativeRef = useRef<HTMLVideoElement>(null);
2024-10-12 23:48:55 -06:00
const shakaPlayerRef = useRef<shaka.Player | null>(null);
2024-06-30 05:25:43 -06:00
const seek = useCallback(
2024-10-12 23:48:55 -06:00
(time: number, _tolerance?: number) => {
2024-06-30 05:25:43 -06:00
if (isNaN(time)) {
throw new Error('Specified time is not a number');
}
2024-10-12 23:48:55 -06:00
if (!shakaPlayerRef.current) {
console.warn('Shaka Player is not initialized');
2024-06-30 05:25:43 -06:00
return;
}
2024-10-12 23:48:55 -06:00
time = Math.max(
0,
Math.min(time, shakaPlayerRef.current.seekRange().end)
);
onSeek?.({
seekTime: time,
currentTime: nativeRef.current?.currentTime || 0,
});
2024-06-30 05:25:43 -06:00
},
[onSeek],
);
const pause = useCallback(() => {
if (!nativeRef.current) {
return;
}
nativeRef.current.pause();
}, []);
const resume = useCallback(() => {
if (!nativeRef.current) {
return;
}
nativeRef.current.play();
}, []);
2024-06-30 05:25:43 -06:00
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');
}, []);
2024-07-10 04:18:21 -06:00
// 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,
2024-06-30 05:25:43 -06:00
setVolume,
getCurrentPosition,
2024-07-10 04:18:21 -06:00
presentFullscreenPlayer,
dismissFullscreenPlayer,
setFullScreen,
save: unsupported,
restoreUserInterfaceForPictureInPictureStopCompleted: unsupported,
nativeHtmlVideoRef: nativeRef,
}),
2024-06-30 07:25:49 -06:00
[
seek,
pause,
resume,
unsupported,
setVolume,
getCurrentPosition,
nativeRef,
2024-07-10 04:18:21 -06:00
presentFullscreenPlayer,
dismissFullscreenPlayer,
setFullScreen,
2024-06-30 07:25:49 -06:00
],
);
useEffect(() => {
if (paused) {
pause();
} else {
resume();
}
}, [paused, pause, resume]);
useEffect(() => {
2024-06-30 05:25:43 -06:00
if (volume === undefined) {
return;
}
2024-06-30 05:25:43 -06:00
setVolume(volume);
}, [volume, setVolume]);
2024-10-12 23:48:55 -06:00
// Handle playback rate changes
2024-06-30 05:38:52 -06:00
useEffect(() => {
if (!nativeRef.current || rate === undefined) {
return;
}
nativeRef.current.playbackRate = rate;
}, [rate]);
2024-10-12 23:48:55 -06:00
// Initialize Shaka Player
useEffect(() => {
if (!nativeRef.current) {
console.warn('Video component is not mounted');
return;
}
// Initialize Shaka Player
const player = new shaka.Player(nativeRef.current);
shakaPlayerRef.current = player;
// Error handling
2024-10-13 01:07:48 -06:00
player.addEventListener('error', (event) => {
//@ts-ignore
2024-10-12 23:48:55 -06:00
const shakaError = event.detail;
console.error('Shaka Player Error', shakaError);
onError?.({
error: {
errorString: shakaError.message,
code: shakaError.code,
},
});
});
// Buffering events
2024-10-13 01:07:48 -06:00
player.addEventListener('buffering', (event) => {
//@ts-ignore
2024-10-12 23:48:55 -06:00
onBuffer?.({ isBuffering: event.buffering });
});
// Load the video source
player
2024-10-13 01:07:48 -06:00
//@ts-ignore
2024-10-12 23:48:55 -06:00
.load(source?.uri)
.then(() => {
// Media loaded successfully
if (!nativeRef.current) return;
const duration = nativeRef.current.duration;
const naturalSize = {
width: nativeRef.current.videoWidth,
height: nativeRef.current.videoHeight,
orientation:
nativeRef.current.videoWidth > nativeRef.current.videoHeight
? 'landscape'
: 'portrait',
};
onLoad?.({
currentTime: nativeRef.current.currentTime,
duration,
2024-10-13 00:44:54 -06:00
//@ts-ignore
2024-10-12 23:48:55 -06:00
naturalSize,
2024-10-13 01:07:48 -06:00
//@ts-ignore
2024-10-12 23:48:55 -06:00
videoTracks: player.getVariantTracks(),
2024-10-13 01:07:48 -06:00
//@ts-ignore
2024-10-12 23:48:55 -06:00
audioTracks: player.getVariantTracks(),
2024-10-13 01:07:48 -06:00
//@ts-ignore
2024-10-12 23:48:55 -06:00
textTracks: player.getTextTracks(),
});
onReadyForDisplay?.();
})
2024-10-13 00:44:54 -06:00
.catch((error: any) => {
2024-10-12 23:48:55 -06:00
console.error('Error loading video', error);
onError?.({ error });
});
return () => {
// Cleanup
if (shakaPlayerRef.current) {
shakaPlayerRef.current.destroy();
shakaPlayerRef.current = null;
}
};
}, [source?.uri]);
// Handle Media Session (if implemented)
useMediaSession(source?.metadata, nativeRef, showNotificationControls);
2024-06-30 07:25:49 -06:00
return (
2024-06-30 07:25:49 -06:00
<video
ref={nativeRef}
muted={muted}
controls={controls}
loop={repeat}
playsInline
//@ts-ignore
2024-06-30 07:25:49 -06:00
poster={poster}
2024-10-12 23:48:55 -06:00
onCanPlay={() => onBuffer?.({ isBuffering: false })}
onWaiting={() => onBuffer?.({ isBuffering: true })}
2024-06-30 07:25:49 -06:00
onTimeUpdate={() => {
if (!nativeRef.current) {
return;
}
onProgress?.({
currentTime: nativeRef.current.currentTime,
playableDuration: nativeRef.current.buffered.length
? nativeRef.current.buffered.end(
2024-10-12 23:48:55 -06:00
nativeRef.current.buffered.length - 1
)
: 0,
seekableDuration: nativeRef.current.seekable.length
? nativeRef.current.seekable.end(
nativeRef.current.seekable.length - 1
2024-06-30 07:25:49 -06:00
)
: 0,
});
}}
2024-10-12 23:48:55 -06:00
onEnded={onEnd}
2024-06-30 07:25:49 -06:00
onError={() => {
if (!nativeRef.current?.error) {
return;
}
onError?.({
error: {
2024-10-12 23:48:55 -06:00
errorString:
nativeRef.current.error.message || 'Unknown error',
2024-06-30 07:25:49 -06:00
code: nativeRef.current.error.code,
},
});
}}
2024-07-08 23:43:10 -06:00
style={videoStyle}
2024-06-30 07:25:49 -06:00
/>
);
2024-10-12 23:48:55 -06:00
}
);
2024-07-08 23:43:10 -06:00
const videoStyle = {
position: 'absolute',
inset: 0,
objectFit: 'contain',
width: '100%',
height: '100%',
} satisfies React.CSSProperties;
2024-06-30 07:25:49 -06:00
const useMediaSession = (
metadata: VideoMetadata | undefined,
nativeRef: RefObject<HTMLVideoElement>,
showNotification: boolean,
) => {
const isPlaying = !nativeRef.current?.paused ?? false;
const progress = nativeRef.current?.currentTime ?? 0;
2024-06-30 21:32:39 -06:00
const duration = Number.isFinite(nativeRef.current?.duration)
? nativeRef.current?.duration
: undefined;
2024-06-30 07:25:49 -06:00
const playbackRate = nativeRef.current?.playbackRate ?? 1;
const enabled = 'mediaSession' in navigator && showNotification;
useEffect(() => {
if (enabled) {
navigator.mediaSession.metadata = new MediaMetadata({
title: metadata?.title,
artist: metadata?.artist,
artwork: metadata?.imageUri ? [{src: metadata.imageUri}] : undefined,
});
}
}, [enabled, metadata]);
useEffect(() => {
if (!enabled) {
return;
}
const seekTo = (time: number) => {
if (nativeRef.current) {
nativeRef.current.currentTime = time;
}
};
2024-06-30 07:25:49 -06:00
const seekRelative = (offset: number) => {
if (nativeRef.current) {
nativeRef.current.currentTime = nativeRef.current.currentTime + offset;
2024-06-30 07:25:49 -06:00
}
};
const mediaActions: [
MediaSessionAction,
MediaSessionActionHandler | null,
][] = [
['play', () => nativeRef.current?.play()],
['pause', () => nativeRef.current?.pause()],
2024-06-30 07:25:49 -06:00
[
'seekbackward',
(evt: MediaSessionActionDetails) =>
seekRelative(evt.seekOffset ? -evt.seekOffset : -10),
],
[
'seekforward',
(evt: MediaSessionActionDetails) =>
seekRelative(evt.seekOffset ? evt.seekOffset : 10),
],
['seekto', (evt: MediaSessionActionDetails) => seekTo(evt.seekTime!)],
2024-06-30 07:25:49 -06:00
];
for (const [action, handler] of mediaActions) {
try {
navigator.mediaSession.setActionHandler(action, handler);
} catch {
// ignored
}
}
}, [enabled, nativeRef]);
2024-06-30 07:25:49 -06:00
useEffect(() => {
if (enabled) {
navigator.mediaSession.playbackState = isPlaying ? 'playing' : 'paused';
}
}, [isPlaying, enabled]);
useEffect(() => {
if (enabled && duration !== undefined) {
navigator.mediaSession.setPositionState({
position: Math.min(progress, duration),
duration,
playbackRate: playbackRate,
});
}
}, [progress, duration, playbackRate, enabled]);
};
Video.displayName = 'Video';
export default Video;