diff --git a/.gitea/workflows/check-js.yaml b/.gitea/workflows/check-js.yaml new file mode 100644 index 00000000..44563f46 --- /dev/null +++ b/.gitea/workflows/check-js.yaml @@ -0,0 +1,38 @@ +name: Check JS + +on: + pull_request: + push: + branches: + - railbird-v6 + +jobs: + typescript: + name: Check TS (tsc) + runs-on: nixos-x86_64-linux + defaults: + run: + shell: nix shell nixpkgs#nodejs_22 nixpkgs#yarn -c bash -e {0} + steps: + - uses: actions/checkout@v4 + - name: Install node_modules and build package + run: yarn install --immutable + - name: Check TypeScript + run: yarn tsc + - name: Test web HLS + run: yarn test:web + + lint: + name: Lint JS (eslint, prettier) + runs-on: nixos-x86_64-linux + defaults: + run: + shell: nix shell nixpkgs#nodejs_22 nixpkgs#yarn -c bash -e {0} + steps: + - uses: actions/checkout@v4 + - name: Install node_modules and build package + run: yarn install --immutable + - name: Run ESLint + run: yarn lint + - name: Verify auto-fix produces no changes + run: yarn lint --fix && git diff --exit-code HEAD diff --git a/package.json b/package.json index 9a153f1a..792f4890 100644 --- a/package.json +++ b/package.json @@ -31,11 +31,10 @@ "react": "18.2.0", "react-native": "0.73.2", "react-native-windows": "^0.61.0-0", - "release-it": "^16.2.1", - "patch-package": "^8.0.0" + "release-it": "^16.2.1" }, "dependencies": { - "shaka-player": "^4.11.7", + "hls.js": "^1.6.16", "typescript": "5.6.3" }, "peerDependencies": { @@ -51,6 +50,7 @@ "docs": "yarn --cwd docs build", "release": "release-it", "test": "echo no test available", + "test:web": "yarn tsc -p test/tsconfig.json && node --test test/web-hls.test.js", "check-ios": "scripts/swift-format.sh && scripts/swift-lint.sh && scripts/clang-format.sh", "check-android": "scripts/kotlin-lint.sh", "check-all": "yarn check-android; yarn check-ios; yarn lint", diff --git a/patches/shaka-player+4.11.7.patch b/patches/shaka-player+4.11.7.patch deleted file mode 100644 index ee5b340f..00000000 --- a/patches/shaka-player+4.11.7.patch +++ /dev/null @@ -1,39 +0,0 @@ -diff --git a/node_modules/shaka-player/dist/shaka-player.compiled.d.ts b/node_modules/shaka-player/dist/shaka-player.compiled.d.ts -index 19c0930..cc0a3fd 100644 ---- a/node_modules/shaka-player/dist/shaka-player.compiled.d.ts -+++ b/node_modules/shaka-player/dist/shaka-player.compiled.d.ts -@@ -5117,3 +5117,5 @@ declare namespace shaka.extern { - declare namespace shaka.extern { - type TransmuxerPlugin = ( ) => shaka.extern.Transmuxer ; - } -+ -+export default shaka; -diff --git a/node_modules/shaka-player/dist/shaka-player.ui.d.ts b/node_modules/shaka-player/dist/shaka-player.ui.d.ts -index 1618ca0..a6076c6 100644 ---- a/node_modules/shaka-player/dist/shaka-player.ui.d.ts -+++ b/node_modules/shaka-player/dist/shaka-player.ui.d.ts -@@ -5830,3 +5830,5 @@ declare namespace shaka.extern { - declare namespace shaka.extern { - type UIVolumeBarColors = { base : string , level : string } ; - } -+ -+export default shaka; -diff --git a/node_modules/shaka-player/index.d.ts b/node_modules/shaka-player/index.d.ts -new file mode 100644 -index 0000000..3ebfd96 ---- /dev/null -+++ b/node_modules/shaka-player/index.d.ts -@@ -0,0 +1,2 @@ -+/// -+/// -\ No newline at end of file -diff --git a/node_modules/shaka-player/ui.d.ts b/node_modules/shaka-player/ui.d.ts -new file mode 100644 -index 0000000..84a3be0 ---- /dev/null -+++ b/node_modules/shaka-player/ui.d.ts -@@ -0,0 +1,3 @@ -+import shaka from 'shaka-player/dist/shaka-player.ui' -+export * from 'shaka-player/dist/shaka-player.ui' -+export default shaka; -\ No newline at end of file diff --git a/src/Video.tsx b/src/Video.tsx index b9eb6102..42df8a36 100644 --- a/src/Video.tsx +++ b/src/Video.tsx @@ -475,7 +475,7 @@ const Video = forwardRef( (e: NativeSyntheticEvent) => { onSeekComplete?.(e.nativeEvent); }, - [onSeekComplete] + [onSeekComplete], ); const onVideoPlaybackStateChanged = useCallback( @@ -733,10 +733,10 @@ const Video = forwardRef( } // poster style - const baseStyle: StyleProp = { - ...StyleSheet.absoluteFill, - resizeMode: _posterResizeMode, - }; + const baseStyle: StyleProp = [ + StyleSheet.absoluteFill, + {resizeMode: _posterResizeMode}, + ]; let posterStyle: StyleProp = baseStyle; @@ -786,10 +786,10 @@ const Video = forwardRef( ]); const _style: StyleProp = useMemo( - () => ({ - ...StyleSheet.absoluteFill, - ...(showPoster ? {display: 'none'} : {}), - }), + () => [ + StyleSheet.absoluteFill, + showPoster ? {display: 'none'} : undefined, + ], [showPoster], ); diff --git a/src/Video.web.tsx b/src/Video.web.tsx index 7bcfcb7b..1fccca7e 100644 --- a/src/Video.web.tsx +++ b/src/Video.web.tsx @@ -4,70 +4,32 @@ import React, { useEffect, useImperativeHandle, useRef, - useState, type RefObject, } from 'react'; -//@ts-ignore -import shaka from 'shaka-player'; +import Hls from 'hls.js'; import type {VideoRef, ReactVideoProps, VideoMetadata} from './types'; +import { + createWebPlaybackErrorReporter, + describeHlsError, + describeMediaError, + isAppleWebKit, + selectWebHlsPlaybackMode, + type WebHlsPlaybackMode, +} from './webHls'; -// Action Queue Class -class ActionQueue { - private queue: { action: () => Promise; name: string }[] = []; - private isRunning = false; +const HLS_MIME = 'application/vnd.apple.mpegurl'; - enqueue(action: () => Promise, name: string) { - this.queue.push({ action, name }); - this.runNext(); +// `poster` is either a (deprecated) plain URI string or a poster object whose +// `source` follows the RN image-source shape. The DOM only takes a URL string. +const resolvePosterUri = ( + poster: ReactVideoProps['poster'], +): string | undefined => { + if (typeof poster === 'string') { + return poster; } - - private async runNext() { - if (this.isRunning || this.queue.length === 0) { - console.log("Refusing to run in runNext", this.queue.length, this.isRunning); - return; - } - this.isRunning = true; - const { action, name } = this.queue.shift()!; - console.log(`Running action: ${name}`); - - const actionPromise = action(); - const timeoutPromise = new Promise((_, reject) => - setTimeout(() => reject(new Error(`Action ${name} timed out`)), 2000) - ); - - try { - await Promise.race([actionPromise, timeoutPromise]); - } catch (e) { - console.error('Error in queued action:', e); - } finally { - this.isRunning = false; - this.runNext(); - } - } -} - -function shallowEqual(obj1: any, obj2: any) { - // If both are strictly equal (covers primitive types and identical object references) - if (obj1 === obj2) return true; - - // If one is not an object (meaning it's a primitive), they must be strictly equal - if (typeof obj1 !== 'object' || typeof obj2 !== 'object' || obj1 === null || obj2 === null) { - return false; - } - - // Get the keys of both objects - const keys1 = Object.keys(obj1); - const keys2 = Object.keys(obj2); - - // If the number of keys is different, the objects are not equal - if (keys1.length !== keys2.length) return false; - - // Check that all keys and their corresponding values are the same - return keys1.every(key => { - // If the value is an object, we fall back to reference equality (shallow comparison) - return obj1[key] === obj2[key]; - }); -} + const source = poster?.source; + return typeof source === 'object' && source !== null ? source.uri : undefined; +}; const Video = forwardRef( ( @@ -99,62 +61,46 @@ const Video = forwardRef( ref, ) => { const nativeRef = useRef(null); - const shakaPlayerRef = useRef(null); - const [currentSource, setCurrentSource] = useState(null); - const actionQueue = useRef(new ActionQueue()); const isSeeking = useRef(false); - const seek = useCallback( - (time: number, _tolerance?: number) => { - actionQueue.current.enqueue(async () => { - 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, - }); - }, 'seek'); + 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(() => { - actionQueue.current.enqueue(async () => { - if (!nativeRef.current) { - return; - } - await nativeRef.current.pause(); - }, 'pause'); + if (!nativeRef.current) { + return; + } + nativeRef.current.pause(); }, []); const resume = useCallback(() => { - actionQueue.current.enqueue(async () => { - if (!nativeRef.current) { - return; - } - try { - await nativeRef.current.play(); - } catch (e) { - console.error('Error playing video:', e); - } - }, 'resume'); + if (!nativeRef.current) { + return; + } + // play() rejects if it is called before the stream has data (common while + // hls.js is still parsing the manifest) or if autoplay is denied. Neither + // is fatal, so swallow it rather than surfacing an unhandled rejection. + nativeRef.current.play()?.catch(() => {}); }, []); const setVolume = useCallback((vol: number) => { - actionQueue.current.enqueue(async () => { - if (!nativeRef.current) { - return; - } - nativeRef.current.volume = Math.max(0, Math.min(vol, 100)) / 100; - }, 'setVolume'); + if (!nativeRef.current) { + return; + } + nativeRef.current.volume = Math.max(0, Math.min(vol, 100)) / 100; }, []); const getCurrentPosition = useCallback(async () => { @@ -187,21 +133,31 @@ const Video = forwardRef( autorotate ??= fsPrefs.current.fullscreenAutorotate; const run = async () => { + const browserOrientation = screen.orientation as + | { + lock?: (orientation: 'landscape' | 'portrait') => Promise; + unlock?: () => void; + } + | undefined; try { if (newVal) { await nativeRef.current?.requestFullscreen({ navigationUI: 'hide', }); if (orientation === 'all' || !orientation || autorotate) { - screen.orientation.unlock(); - } else { - await screen.orientation.lock(orientation); + if (typeof browserOrientation?.unlock === 'function') { + browserOrientation.unlock(); + } + } else if (typeof browserOrientation?.lock === 'function') { + await browserOrientation.lock(orientation); } } else { if (document.fullscreenElement) { await document.exitFullscreen(); } - screen.orientation.unlock(); + if (typeof browserOrientation?.unlock === 'function') { + browserOrientation.unlock(); + } } } catch (e) { // Changing fullscreen status without a button click is not allowed so it throws. @@ -209,7 +165,7 @@ const Video = forwardRef( console.error('Could not toggle fullscreen/screen lock status', e); } }; - actionQueue.current.enqueue(run, 'setFullScreen'); + run(); }, [], ); @@ -272,7 +228,6 @@ const Video = forwardRef( resume(); } }, [paused, pause, resume]); - useEffect(() => { if (volume === undefined) { return; @@ -307,107 +262,77 @@ const Video = forwardRef( nativeRef.current.playbackRate = rate; }, [rate]); - const makeNewShaka = useCallback(() => { - console.log("makeNewShaka"); - actionQueue.current.enqueue(async () => { - console.log("makeNewShaka actionQueue"); - if (!nativeRef.current) { - console.warn('No video element to attach Shaka Player'); - return; - } + // `onError` is typically a fresh closure on every render. Keep it in a ref so + // the source effect below can depend on the URI alone -- callers pass + // `source={{uri}}` as a new object literal each render, so keying the effect + // on anything object-shaped would tear down and reload the stream constantly. + const onErrorRef = useRef(onError); + onErrorRef.current = onError; + const playbackErrorReporterRef = + useRef>(); + if (!playbackErrorReporterRef.current) { + playbackErrorReporterRef.current = createWebPlaybackErrorReporter( + (error) => onErrorRef.current?.({error}), + ); + } + const playbackDiagnosticsRef = useRef<{ + mode: WebHlsPlaybackMode; + nativeHlsSupport: string; + }>(); - // Pause the video before changing the source - nativeRef.current.pause(); - - // Unload the previous Shaka player if it exists - if (shakaPlayerRef.current) { - await shakaPlayerRef.current.unload(); - shakaPlayerRef.current = null; - } - - // Create a new Shaka player and attach it to the video element - shakaPlayerRef.current = new shaka.Player(); - - shakaPlayerRef.current.attach(nativeRef.current); - - if (source?.cropStart) { - shakaPlayerRef.current.configure({ - playRangeStart: source?.cropStart / 1000, - }); - } - if (source?.cropEnd) { - shakaPlayerRef.current.configure({ - playRangeEnd: source?.cropEnd / 1000, - }); - } - - //@ts-ignore - 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'); - - // Load the new source - try { - //@ts-ignore - await shakaPlayerRef.current.load(source?.uri); - console.log(`${source?.uri} finished loading`); - - // Optionally resume playback if not paused - if (!paused) { - try { - await nativeRef.current.play(); - } catch (e) { - console.error('Error playing video:', e); - } - } - } catch (e) { - console.error('Error loading video with Shaka Player', e); - onError?.({ - error: { - //@ts-ignore - errorString: e.message, - //@ts-ignore - code: e.code, - }, - }); - } - }, 'makeNewShaka'); - }, [source, paused, onError]); - - const nativeRefDefined = !!nativeRef.current; + const uri = source?.uri as string | undefined; + const sourceType = source?.type; useEffect(() => { - if (!nativeRef.current) { - console.log('Not starting shaka yet because video element is undefined'); + const video = nativeRef.current; + if (!video || !uri) { return; } - if (!shallowEqual(source, currentSource)) { - console.log( - 'Making new shaka, Old source: ', - currentSource, - 'New source', - source, - ); - //@ts-ignore - setCurrentSource(source); - makeNewShaka(); + + playbackErrorReporterRef.current?.reset(); + const nativeHlsSupport = video.canPlayType(HLS_MIME); + const mode = selectWebHlsPlaybackMode(uri, sourceType, { + hlsJsSupported: Hls.isSupported(), + nativeHlsSupport, + preferNativeHls: isAppleWebKit(navigator.userAgent, navigator.vendor), + }); + playbackDiagnosticsRef.current = {mode, nativeHlsSupport}; + + if (mode === 'native') { + video.src = uri; + return () => { + playbackErrorReporterRef.current?.reset(); + video.removeAttribute('src'); + video.load(); + }; } - }, [source, nativeRefDefined, currentSource, makeNewShaka]); + + const hls = new Hls(); + hls.on(Hls.Events.ERROR, (_event, data) => { + // hls.js surfaces plenty of recoverable warnings; only fatal errors are + // worth propagating as a video error. + if (!data.fatal) { + return; + } + const errorString = `${describeHlsError( + data, + )}; mode=hls.js; nativeHlsSupport=${nativeHlsSupport || 'none'}`; + playbackErrorReporterRef.current?.addHls( + errorString, + `hls.js/${data.type}`, + ); + }); + hls.loadSource(uri); + hls.attachMedia(video); + + return () => { + playbackErrorReporterRef.current?.reset(); + hls.destroy(); + }; + }, [sourceType, uri]); useMediaSession(source?.metadata, nativeRef, showNotificationControls); - const cropStartSeconds = (source?.cropStart || 0) / 1000; - return (