From 4e9de682bdb5695d0af5b52ef34be284b2fb8575 Mon Sep 17 00:00:00 2001 From: Cody Bennett Date: Fri, 12 Apr 2024 19:02:42 -0500 Subject: [PATCH] fix(useVideoTexture): lazy initialize hls.js when supported --- src/core/useVideoTexture.tsx | 39 +++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/src/core/useVideoTexture.tsx b/src/core/useVideoTexture.tsx index 02a5293cb..7bcab04e1 100644 --- a/src/core/useVideoTexture.tsx +++ b/src/core/useVideoTexture.tsx @@ -2,7 +2,7 @@ import * as THREE from 'three' import { useEffect, useRef } from 'react' import { useThree } from '@react-three/fiber' import { suspend } from 'suspend-react' -import Hls, { HlsConfig } from 'hls.js' +import type { HlsConfig, default as Hls } from 'hls.js' interface VideoTextureProps extends HTMLVideoElement { unsuspend?: 'canplay' | 'canplaythrough' | 'loadstart' | 'loadedmetadata' @@ -14,6 +14,23 @@ interface HLSConfiguration { hls: HlsConfig } +const IS_BROWSER = + typeof window !== 'undefined' && + typeof window.document?.createElement === 'function' && + typeof window.navigator?.userAgent === 'string' + +let _HLSModule: typeof import('hls.js') | null = null +async function getHLS(url: URL, config: Partial): Promise { + if (IS_BROWSER && url.pathname.endsWith('.m3u8')) { + _HLSModule ??= await import('hls.js') + if (_HLSModule.default.isSupported()) { + return new _HLSModule.default({ ...config }) + } + } + + return null +} + export function useVideoTexture(src: string | MediaStream, props?: Partial) { const { unsuspend, start, crossOrigin, muted, loop, hls, ...rest } = { unsuspend: 'loadedmetadata', @@ -27,14 +44,13 @@ export function useVideoTexture(src: string | MediaStream, props?: Partial