lbry-desktop/ui/component/viewers/videoViewer/internal/videojs.jsx

306 lines
8.7 KiB
React
Raw Normal View History

2020-04-16 23:43:09 +02:00
// @flow
import React, { useEffect, useRef, useState } from 'react';
import Button from 'component/button';
import * as ICONS from 'constants/icons';
2020-04-28 21:33:30 +02:00
import classnames from 'classnames';
2021-07-01 04:12:21 +02:00
import videojs from 'video.js';
import 'video.js/dist/alt/video-js-cdn.min.css';
2020-04-16 01:21:17 +02:00
import eventTracking from 'videojs-event-tracking';
import * as OVERLAY from './overlays';
import './plugins/videojs-mobile-ui/plugin';
import hlsQualitySelector from './plugins/videojs-hls-quality-selector/plugin';
import recsys from './plugins/videojs-recsys/plugin';
import qualityLevels from 'videojs-contrib-quality-levels';
import LbryVolumeBarClass from './lbry-volume-bar';
import keyboardShorcuts from './videojs-keyboard-shortcuts';
import events from './videojs-events';
import functions from './videojs-functions';
2020-04-16 01:21:17 +02:00
2020-04-28 21:33:30 +02:00
export type Player = {
on: (string, (any) => void) => void,
one: (string, (any) => void) => void,
2020-04-28 21:33:30 +02:00
isFullscreen: () => boolean,
exitFullscreen: () => boolean,
requestFullscreen: () => boolean,
play: () => Promise<any>,
volume: (?number) => number,
muted: (?boolean) => boolean,
dispose: () => void,
currentTime: (?number) => number,
ended: () => boolean,
2020-05-21 17:38:28 +02:00
error: () => any,
loadingSpinner: any,
getChild: (string) => any,
playbackRate: (?number) => number,
readyState: () => number,
userActive: (?boolean) => boolean,
overlay: (any) => void,
mobileUi: (any) => void,
2021-01-08 16:21:27 +01:00
controlBar: {
addChild: (string, any) => void,
},
autoplay: (any) => boolean,
2020-04-28 21:33:30 +02:00
};
2020-04-16 01:21:17 +02:00
type Props = {
source: string,
sourceType: string,
2020-04-28 21:33:30 +02:00
poster: ?string,
onPlayerReady: (Player, any) => void,
2020-04-16 01:21:17 +02:00
isAudio: boolean,
autoplay: boolean,
autoplaySetting: boolean,
2021-01-20 09:50:16 +01:00
toggleVideoTheaterMode: () => void,
claimId: ?string,
userId: ?number,
2021-08-23 17:05:33 +02:00
// allowPreRoll: ?boolean,
shareTelemetry: boolean,
replay: boolean,
videoTheaterMode: boolean,
playNext: () => void,
playPrevious: () => void,
2020-04-16 01:21:17 +02:00
};
const videoPlaybackRates = [0.25, 0.5, 0.75, 1, 1.1, 1.25, 1.5, 1.75, 2];
2020-05-25 16:36:17 +02:00
const IS_IOS =
(/iPad|iPhone|iPod/.test(navigator.platform) ||
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) &&
!window.MSStream;
2021-07-19 18:54:05 +02:00
const VIDEO_JS_OPTIONS = {
2020-04-16 23:43:09 +02:00
preload: 'auto',
playbackRates: videoPlaybackRates,
2020-04-16 23:43:09 +02:00
responsive: true,
2020-04-28 21:33:30 +02:00
controls: true,
html5: {
vhs: {
overrideNative: !videojs.browser.IS_ANY_SAFARI,
},
},
2020-04-16 23:43:09 +02:00
};
2020-04-16 01:21:17 +02:00
if (!Object.keys(videojs.getPlugins()).includes('eventTracking')) {
videojs.registerPlugin('eventTracking', eventTracking);
}
if (!Object.keys(videojs.getPlugins()).includes('hlsQualitySelector')) {
videojs.registerPlugin('hlsQualitySelector', hlsQualitySelector);
}
if (!Object.keys(videojs.getPlugins()).includes('qualityLevels')) {
videojs.registerPlugin('qualityLevels', qualityLevels);
}
if (!Object.keys(videojs.getPlugins()).includes('recsys')) {
videojs.registerPlugin('recsys', recsys);
}
// ****************************************************************************
// VideoJs
// ****************************************************************************
2020-04-16 01:21:17 +02:00
/*
properties for this component should be kept to ONLY those that if changed should REQUIRE an entirely new videojs element
*/
2020-04-28 21:33:30 +02:00
export default React.memo<Props>(function VideoJs(props: Props) {
2021-04-12 18:43:47 +02:00
const {
autoplay,
autoplaySetting,
2021-04-12 18:43:47 +02:00
source,
sourceType,
poster,
isAudio,
onPlayerReady,
toggleVideoTheaterMode,
claimId,
userId,
shareTelemetry,
replay,
videoTheaterMode,
playNext,
playPrevious,
2021-04-12 18:43:47 +02:00
} = props;
// will later store the videojs player
const playerRef = useRef();
2020-04-16 23:43:09 +02:00
const containerRef = useRef();
const tapToUnmuteRef = useRef();
const tapToRetryRef = useRef();
// initiate keyboard shortcuts
const { curried_function } = keyboardShorcuts({ toggleVideoTheaterMode, playNext, playPrevious });
const [reload, setReload] = useState('initial');
const videoJsOptions = {
2020-04-16 01:21:17 +02:00
...VIDEO_JS_OPTIONS,
autoplay: autoplay,
2020-04-16 01:21:17 +02:00
sources: [
{
src: source,
type: sourceType,
},
],
poster: poster, // thumb looks bad in app, and if autoplay, flashing poster is annoying
plugins: {
eventTracking: true,
overlay: OVERLAY.OVERLAY_DATA,
},
// fixes problem of errant CC button showing up on iOS
2021-06-25 18:26:00 +02:00
// the true fix here is to fix the m3u8 file, see: https://github.com/lbryio/lbry-desktop/pull/6315
controlBar: {
subsCapsButton: false,
},
2020-04-16 01:21:17 +02:00
};
const { detectFileType, createVideoPlayerDOM } = functions({ source, sourceType, videoJsOptions, isAudio });
const { unmuteAndHideHint, retryVideoAfterFailure, initializeEvents } = events({
tapToUnmuteRef,
tapToRetryRef,
setReload,
videoTheaterMode,
playerRef,
autoplaySetting,
replay,
});
// Initialize video.js
function initializeVideoPlayer(el) {
if (!el) return;
const vjs = videojs(el, videoJsOptions, () => {
const player = playerRef.current;
// this seems like a weird thing to have to check for here
if (!player) return;
2021-01-26 00:50:11 +01:00
initializeEvents();
// Replace volume bar with custom LBRY volume bar
LbryVolumeBarClass.replaceExisting(player);
2021-01-26 00:50:11 +01:00
// Add reloadSourceOnError plugin
player.reloadSourceOnError({ errorInterval: 10 });
// initialize mobile UI
player.mobileUi(); // Inits mobile version. No-op if Desktop.
// Add quality selector to player
player.hlsQualitySelector({
displayCurrentQuality: true,
});
// Add recsys plugin
if (shareTelemetry) {
player.recsys({
videoId: claimId,
userId: userId,
});
}
// set playsinline for mobile
player.children_[0].setAttribute('playsinline', '');
// I think this is a callback function
const videoNode = containerRef.current && containerRef.current.querySelector('video, audio');
onPlayerReady(player, videoNode);
});
// fixes #3498 (https://github.com/lbryio/lbry-desktop/issues/3498)
// summary: on firefox the focus would stick to the fullscreen button which caused buggy behavior with spacebar
vjs.on('fullscreenchange', () => document.activeElement && document.activeElement.blur());
return vjs;
}
/** instantiate videoJS and dispose of it when done with code **/
// This lifecycle hook is only called once (on mount), or when `isAudio` or `source` changes.
2020-04-16 23:43:09 +02:00
useEffect(() => {
const vjsElement = createVideoPlayerDOM(containerRef.current);
2020-04-28 21:33:30 +02:00
// Detect source file type via pre-fetch (async)
detectFileType().then(() => {
// Initialize Video.js
const vjsPlayer = initializeVideoPlayer(vjsElement);
2021-01-26 00:50:11 +01:00
// Add reference to player to global scope
window.player = vjsPlayer;
// Set reference in component state
playerRef.current = vjsPlayer;
window.addEventListener('keydown', curried_function(playerRef, containerRef));
});
2020-04-16 23:43:09 +02:00
// Cleanup
return () => {
window.removeEventListener('keydown', curried_function);
2020-04-16 23:43:09 +02:00
const player = playerRef.current;
if (player) {
player.dispose();
window.player = undefined;
}
2021-01-26 00:50:11 +01:00
};
}, [isAudio, source]);
2021-01-04 16:12:46 +01:00
2021-01-23 21:28:31 +01:00
// Update video player and reload when source URL changes
useEffect(() => {
// For some reason the video player is responsible for detecting content type this way
fetch(source, { method: 'HEAD', cache: 'no-store' }).then((response) => {
let finalType = sourceType;
2021-06-11 19:32:56 +02:00
let finalSource = source;
// override type if we receive an .m3u8 (transcoded mp4)
// do we need to check if explicitly redirected
// or is checking extension only a safer method
if (response && response.redirected && response.url && response.url.endsWith('m3u8')) {
finalType = 'application/x-mpegURL';
2021-06-11 19:32:56 +02:00
finalSource = response.url;
}
2021-01-07 04:58:09 +01:00
// Modify video source in options
videoJsOptions.sources = [
{
src: finalSource,
type: finalType,
},
];
2021-01-07 04:58:09 +01:00
// Update player source
const player = playerRef.current;
if (!player) return;
// PR #5570: Temp workaround to avoid double Play button until the next re-architecture.
if (!player.paused()) {
player.bigPlayButton.hide();
}
});
}, [source, reload]);
2020-04-16 01:21:17 +02:00
return (
// $FlowFixMe
<div className={classnames('video-js-parent', { 'video-js-parent--ios': IS_IOS })} ref={containerRef}>
<Button
label={__('Tap to unmute')}
button="link"
icon={ICONS.VOLUME_MUTED}
className="video-js--tap-to-unmute"
onClick={unmuteAndHideHint}
ref={tapToUnmuteRef}
/>
<Button
label={__('Retry')}
button="link"
icon={ICONS.REFRESH}
className="video-js--tap-to-unmute"
onClick={retryVideoAfterFailure}
ref={tapToRetryRef}
/>
</div>
);
2020-04-16 18:10:47 +02:00
});