Compare commits
28 Commits
volodymyr/
...
loewy/fix-
| Author | SHA1 | Date | |
|---|---|---|---|
| 7c0669190f | |||
| 452a9748d5 | |||
| b81dae8878 | |||
| ba3dea885d | |||
| a1579eebad | |||
| 42608bd8d1 | |||
| 04682d02c7 | |||
| ec3cb15984 | |||
| ff6c4316cf | |||
| dfe2957087 | |||
| d7563cfd93 | |||
| 69a9159a43 | |||
| c6bd3e3ee4 | |||
| 2d953c4c46 | |||
| 7a6afd52a3 | |||
| d7977241c9 | |||
| 921ead0f05 | |||
| 20397d32e6 | |||
| e3900e794d | |||
| 4dc7bf465f | |||
| e5f182cda9 | |||
| 9138c3249d | |||
| 7a1d0e8b10 | |||
| 9cbba8f95e | |||
| 2cfb26d51f | |||
| 4f18e9b238 | |||
| bd64379837 | |||
| a16275b003 |
38
.gitea/workflows/check-js.yaml
Normal file
38
.gitea/workflows/check-js.yaml
Normal file
@@ -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
|
||||
@@ -24,7 +24,7 @@ class SideLoadedTextTrackList {
|
||||
}
|
||||
val sideLoadedTextTrackList = SideLoadedTextTrackList()
|
||||
for (i in 0 until src.size()) {
|
||||
val textTrack: ReadableMap = src.getMap(i)
|
||||
val textTrack: ReadableMap = src.getMap(i) ?: continue
|
||||
sideLoadedTextTrackList.tracks.add(SideLoadedTextTrack.parse(textTrack))
|
||||
}
|
||||
return sideLoadedTextTrackList
|
||||
|
||||
@@ -228,7 +228,7 @@ class Source {
|
||||
if (propSrcHeadersArray != null) {
|
||||
if (propSrcHeadersArray.size() > 0) {
|
||||
for (i in 0 until propSrcHeadersArray.size()) {
|
||||
val current = propSrcHeadersArray.getMap(i)
|
||||
val current = propSrcHeadersArray.getMap(i) ?: continue
|
||||
val key = if (current.hasKey("key")) current.getString("key") else null
|
||||
val value = if (current.hasKey("value")) current.getString("value") else null
|
||||
if (key != null && value != null) {
|
||||
|
||||
@@ -288,12 +288,22 @@ class VideoEventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
private class VideoEvent(
|
||||
surfaceId: Int,
|
||||
viewId: Int,
|
||||
private val name: String,
|
||||
private val data: WritableMap?
|
||||
) : Event<VideoEvent>(surfaceId, viewId) {
|
||||
override fun getEventName() = name
|
||||
override fun getEventData() = data
|
||||
}
|
||||
|
||||
private class EventBuilder(private val surfaceId: Int, private val viewId: Int, private val dispatcher: EventDispatcher) {
|
||||
fun dispatch(event: EventTypes, paramsSetter: (WritableMap.() -> Unit)? = null) =
|
||||
dispatcher.dispatchEvent(object : Event<Event<*>>(surfaceId, viewId) {
|
||||
override fun getEventName() = "top${event.eventName.removePrefix("on")}"
|
||||
override fun getEventData() = Arguments.createMap().apply(paramsSetter ?: {})
|
||||
})
|
||||
fun dispatch(event: EventTypes, paramsSetter: (WritableMap.() -> Unit)? = null) {
|
||||
val eventName = "top${event.eventName.removePrefix("on")}"
|
||||
val eventData = Arguments.createMap().apply(paramsSetter ?: {})
|
||||
dispatcher.dispatchEvent(VideoEvent(surfaceId, viewId, eventName, eventData))
|
||||
}
|
||||
}
|
||||
|
||||
private fun audioTracksToArray(audioTracks: java.util.ArrayList<Track>?): WritableArray =
|
||||
|
||||
@@ -34,6 +34,22 @@ enum RCTVideoAssetsUtils {
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
static func getDuration(asset: AVAsset) async -> CMTime? {
|
||||
if #available(iOS 15, tvOS 15, visionOS 1.0, *) {
|
||||
return try? await asset.load(.duration)
|
||||
} else {
|
||||
#if !os(visionOS)
|
||||
return await withCheckedContinuation { continuation in
|
||||
asset.loadValuesAsynchronously(forKeys: ["duration"]) {
|
||||
var error: NSError?
|
||||
let status = asset.statusOfValue(forKey: "duration", error: &error)
|
||||
continuation.resume(returning: status == .loaded ? asset.duration : nil)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - RCTVideoUtils
|
||||
|
||||
@@ -1420,7 +1420,10 @@ class RCTVideo: UIView, RCTVideoPlayerViewControllerDelegate, RCTPlayerObserverH
|
||||
}
|
||||
|
||||
if onVideoLoad != nil, self._videoLoadStarted {
|
||||
var duration = Float(CMTimeGetSeconds(_playerItem.asset.duration))
|
||||
let assetDuration = await RCTVideoAssetsUtils.getDuration(asset: _playerItem.asset)
|
||||
guard self._playerItem === _playerItem,
|
||||
self._source?.json === source.json else { return }
|
||||
var duration = Float(CMTimeGetSeconds(assetDuration ?? .invalid))
|
||||
|
||||
if duration.isNaN || duration == 0 {
|
||||
// This is a safety check for live video.
|
||||
@@ -1449,6 +1452,8 @@ class RCTVideo: UIView, RCTVideoPlayerViewControllerDelegate, RCTPlayerObserverH
|
||||
|
||||
let audioTracks = await RCTVideoUtils.getAudioTrackInfo(self._player)
|
||||
let textTracks = await RCTVideoUtils.getTextTrackInfo(self._player)
|
||||
guard self._playerItem === _playerItem,
|
||||
self._source?.json === source.json else { return }
|
||||
self.onVideoLoad?(["duration": NSNumber(value: duration),
|
||||
"currentTime": NSNumber(value: Float(CMTimeGetSeconds(_playerItem.currentTime()))),
|
||||
"canPlayReverse": NSNumber(value: _playerItem.canPlayReverse),
|
||||
@@ -1699,4 +1704,3 @@ class RCTVideo: UIView, RCTVideoPlayerViewControllerDelegate, RCTPlayerObserverH
|
||||
@objc
|
||||
func setOnClick(_: Any) {}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,13 @@ import React
|
||||
@objc(RCTVideoManager)
|
||||
class RCTVideoManager: RCTViewManager {
|
||||
override func view() -> UIView {
|
||||
return RCTVideo(eventDispatcher: (RCTBridge.current().eventDispatcher() as! RCTEventDispatcher))
|
||||
// `RCTBridge.current()` returns nil under bridgeless (New Architecture), and it
|
||||
// is nonnull-annotated, so Swift emits an unconditional nil-check trap around
|
||||
// the call -- optional chaining does not avoid it. Every <Video> mount killed
|
||||
// the app. RCTVideo only stores this dispatcher and never reads it (events go
|
||||
// out through the RCT_EXPORT_VIEW_PROPERTY direct event blocks), so skip the
|
||||
// lookup entirely.
|
||||
return RCTVideo(eventDispatcher: nil)
|
||||
}
|
||||
|
||||
func methodQueue() -> DispatchQueue {
|
||||
|
||||
11
package.json
11
package.json
@@ -31,18 +31,18 @@
|
||||
"react": "18.2.0",
|
||||
"react-native": "0.73.2",
|
||||
"react-native-windows": "^0.61.0-0",
|
||||
"release-it": "^16.2.1",
|
||||
"typescript": "5.1.6",
|
||||
"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": {
|
||||
"react": "*",
|
||||
"react-native": "*"
|
||||
},
|
||||
"scripts": {
|
||||
"install": "tsc --noCheck",
|
||||
"lint": "yarn eslint .",
|
||||
"build": "yarn tsc",
|
||||
"prepare": "yarn build",
|
||||
@@ -50,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",
|
||||
@@ -61,6 +62,8 @@
|
||||
"windows",
|
||||
"src",
|
||||
"lib",
|
||||
"tsconfig.json",
|
||||
"tsconfig.build.json",
|
||||
"react-native-video.podspec",
|
||||
"app.plugin.js",
|
||||
"!android/build",
|
||||
|
||||
@@ -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 @@
|
||||
+/// <reference path="./dist/shaka-player.compiled.d.ts" />
|
||||
+/// <reference path="./dist/shaka-player.ui.d.ts" />
|
||||
\ 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
|
||||
@@ -475,7 +475,7 @@ const Video = forwardRef<VideoRef, ReactVideoProps>(
|
||||
(e: NativeSyntheticEvent<OnSeekCompleteData>) => {
|
||||
onSeekComplete?.(e.nativeEvent);
|
||||
},
|
||||
[onSeekComplete]
|
||||
[onSeekComplete],
|
||||
);
|
||||
|
||||
const onVideoPlaybackStateChanged = useCallback(
|
||||
@@ -733,10 +733,10 @@ const Video = forwardRef<VideoRef, ReactVideoProps>(
|
||||
}
|
||||
|
||||
// poster style
|
||||
const baseStyle: StyleProp<ImageStyle> = {
|
||||
...StyleSheet.absoluteFillObject,
|
||||
resizeMode: _posterResizeMode,
|
||||
};
|
||||
const baseStyle: StyleProp<ImageStyle> = [
|
||||
StyleSheet.absoluteFill,
|
||||
{resizeMode: _posterResizeMode},
|
||||
];
|
||||
|
||||
let posterStyle: StyleProp<ImageStyle> = baseStyle;
|
||||
|
||||
@@ -786,10 +786,10 @@ const Video = forwardRef<VideoRef, ReactVideoProps>(
|
||||
]);
|
||||
|
||||
const _style: StyleProp<ViewStyle> = useMemo(
|
||||
() => ({
|
||||
...StyleSheet.absoluteFillObject,
|
||||
...(showPoster ? {display: 'none'} : {}),
|
||||
}),
|
||||
() => [
|
||||
StyleSheet.absoluteFill,
|
||||
showPoster ? {display: 'none'} : undefined,
|
||||
],
|
||||
[showPoster],
|
||||
);
|
||||
|
||||
|
||||
@@ -6,9 +6,30 @@ import React, {
|
||||
useRef,
|
||||
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';
|
||||
|
||||
const HLS_MIME = 'application/vnd.apple.mpegurl';
|
||||
|
||||
// `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;
|
||||
}
|
||||
const source = poster?.source;
|
||||
return typeof source === 'object' && source !== null ? source.uri : undefined;
|
||||
};
|
||||
|
||||
const Video = forwardRef<VideoRef, ReactVideoProps>(
|
||||
(
|
||||
@@ -32,6 +53,7 @@ const Video = forwardRef<VideoRef, ReactVideoProps>(
|
||||
onError,
|
||||
onReadyForDisplay,
|
||||
onSeek,
|
||||
onSeekComplete,
|
||||
onVolumeChange,
|
||||
onEnd,
|
||||
onPlaybackStateChanged,
|
||||
@@ -39,7 +61,6 @@ const Video = forwardRef<VideoRef, ReactVideoProps>(
|
||||
ref,
|
||||
) => {
|
||||
const nativeRef = useRef<HTMLVideoElement>(null);
|
||||
const shakaPlayerRef = useRef<shaka.Player | null>(null);
|
||||
|
||||
const isSeeking = useRef(false);
|
||||
const seek = useCallback(
|
||||
@@ -69,7 +90,10 @@ const Video = forwardRef<VideoRef, ReactVideoProps>(
|
||||
if (!nativeRef.current) {
|
||||
return;
|
||||
}
|
||||
nativeRef.current.play();
|
||||
// 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) => {
|
||||
@@ -109,21 +133,31 @@ const Video = forwardRef<VideoRef, ReactVideoProps>(
|
||||
autorotate ??= fsPrefs.current.fullscreenAutorotate;
|
||||
|
||||
const run = async () => {
|
||||
const browserOrientation = screen.orientation as
|
||||
| {
|
||||
lock?: (orientation: 'landscape' | 'portrait') => Promise<void>;
|
||||
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.
|
||||
@@ -228,36 +262,74 @@ const Video = forwardRef<VideoRef, ReactVideoProps>(
|
||||
nativeRef.current.playbackRate = rate;
|
||||
}, [rate]);
|
||||
|
||||
// `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<ReturnType<typeof createWebPlaybackErrorReporter>>();
|
||||
if (!playbackErrorReporterRef.current) {
|
||||
playbackErrorReporterRef.current = createWebPlaybackErrorReporter(
|
||||
(error) => onErrorRef.current?.({error}),
|
||||
);
|
||||
}
|
||||
const playbackDiagnosticsRef = useRef<{
|
||||
mode: WebHlsPlaybackMode;
|
||||
nativeHlsSupport: string;
|
||||
}>();
|
||||
|
||||
const uri = source?.uri as string | undefined;
|
||||
const sourceType = source?.type;
|
||||
|
||||
useEffect(() => {
|
||||
if (!nativeRef.current) {
|
||||
console.log("Not starting shaka yet bc undefined")
|
||||
const video = nativeRef.current;
|
||||
if (!video || !uri) {
|
||||
return;
|
||||
}
|
||||
if (shakaPlayerRef.current) {
|
||||
shakaPlayerRef.current.unload()
|
||||
}
|
||||
shakaPlayerRef.current = new shaka.Player();
|
||||
//@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")
|
||||
shakaPlayerRef.current.attach(nativeRef.current, true);
|
||||
|
||||
//@ts-ignore
|
||||
shakaPlayerRef.current.load(source?.uri).then(
|
||||
() => console.log(`${source?.uri} finished loading`)
|
||||
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();
|
||||
};
|
||||
}
|
||||
|
||||
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}`,
|
||||
);
|
||||
console.log("Started shaka loading");
|
||||
}, [source, nativeRef.current])
|
||||
});
|
||||
hls.loadSource(uri);
|
||||
hls.attachMedia(video);
|
||||
|
||||
return () => {
|
||||
playbackErrorReporterRef.current?.reset();
|
||||
hls.destroy();
|
||||
};
|
||||
}, [sourceType, uri]);
|
||||
|
||||
useMediaSession(source?.metadata, nativeRef, showNotificationControls);
|
||||
|
||||
@@ -269,8 +341,7 @@ const Video = forwardRef<VideoRef, ReactVideoProps>(
|
||||
controls={controls}
|
||||
loop={repeat}
|
||||
playsInline
|
||||
//@ts-ignore
|
||||
poster={poster}
|
||||
poster={resolvePosterUri(poster)}
|
||||
onCanPlay={() => onBuffer?.({isBuffering: false})}
|
||||
onWaiting={() => onBuffer?.({isBuffering: true})}
|
||||
onRateChange={() => {
|
||||
@@ -314,15 +385,23 @@ const Video = forwardRef<VideoRef, ReactVideoProps>(
|
||||
}}
|
||||
onLoadedData={() => onReadyForDisplay?.()}
|
||||
onError={() => {
|
||||
if (!nativeRef.current?.error) {
|
||||
const video = nativeRef.current;
|
||||
if (!video?.error) {
|
||||
return;
|
||||
}
|
||||
onError?.({
|
||||
error: {
|
||||
errorString: nativeRef.current.error.message ?? 'Unknown error',
|
||||
code: nativeRef.current.error.code,
|
||||
},
|
||||
const diagnostics = playbackDiagnosticsRef.current;
|
||||
const mediaError = describeMediaError({
|
||||
currentSrc: video.currentSrc,
|
||||
networkState: video.networkState,
|
||||
readyState: video.readyState,
|
||||
error: video.error,
|
||||
playbackMode: diagnostics?.mode,
|
||||
nativeHlsSupport: diagnostics?.nativeHlsSupport,
|
||||
});
|
||||
playbackErrorReporterRef.current?.addMedia(
|
||||
mediaError,
|
||||
video.error.code,
|
||||
);
|
||||
}}
|
||||
onLoadedMetadata={() => {
|
||||
if (source?.startPosition) {
|
||||
@@ -342,7 +421,15 @@ const Video = forwardRef<VideoRef, ReactVideoProps>(
|
||||
})
|
||||
}
|
||||
onSeeking={() => (isSeeking.current = true)}
|
||||
onSeeked={() => (isSeeking.current = false)}
|
||||
onSeeked={() => {
|
||||
isSeeking.current = false;
|
||||
const currentTime = nativeRef.current?.currentTime ?? 0;
|
||||
onSeekComplete?.({
|
||||
currentTime,
|
||||
seekTime: currentTime,
|
||||
target: 0,
|
||||
});
|
||||
}}
|
||||
onVolumeChange={() => {
|
||||
if (!nativeRef.current) {
|
||||
return;
|
||||
@@ -359,7 +446,9 @@ const Video = forwardRef<VideoRef, ReactVideoProps>(
|
||||
const videoStyle = {
|
||||
position: 'absolute',
|
||||
inset: 0,
|
||||
objectFit: 'contain',
|
||||
// Use 'fill' instead of 'contain' to force video to match container dimensions.
|
||||
// This works around browsers miscalculating intrinsic dimensions from rotation matrices.
|
||||
objectFit: 'fill',
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
} satisfies React.CSSProperties;
|
||||
@@ -369,7 +458,7 @@ const useMediaSession = (
|
||||
nativeRef: RefObject<HTMLVideoElement>,
|
||||
showNotification: boolean,
|
||||
) => {
|
||||
const isPlaying = !nativeRef.current?.paused ?? false;
|
||||
const isPlaying = nativeRef.current ? !nativeRef.current.paused : false;
|
||||
const progress = nativeRef.current?.currentTime ?? 0;
|
||||
const duration = Number.isFinite(nativeRef.current?.duration)
|
||||
? nativeRef.current?.duration
|
||||
|
||||
248
src/webHls.ts
Normal file
248
src/webHls.ts
Normal file
@@ -0,0 +1,248 @@
|
||||
export type WebHlsPlaybackMode = 'hls.js' | 'native';
|
||||
|
||||
export interface WebHlsPlaybackCapabilities {
|
||||
hlsJsSupported: boolean;
|
||||
nativeHlsSupport: string;
|
||||
preferNativeHls: boolean;
|
||||
}
|
||||
|
||||
export interface HlsErrorDetails {
|
||||
type: string;
|
||||
details: string;
|
||||
reason?: string;
|
||||
error?: {message?: string};
|
||||
response?: {
|
||||
code?: number;
|
||||
text?: string;
|
||||
url?: string;
|
||||
data?: unknown;
|
||||
};
|
||||
url?: string;
|
||||
}
|
||||
|
||||
export interface MediaElementDiagnostics {
|
||||
currentSrc: string;
|
||||
networkState: number;
|
||||
readyState: number;
|
||||
error: {code: number; message?: string} | null;
|
||||
playbackMode?: WebHlsPlaybackMode;
|
||||
nativeHlsSupport?: string;
|
||||
}
|
||||
|
||||
export interface WebVideoError {
|
||||
errorString: string;
|
||||
code?: number;
|
||||
domain: string;
|
||||
}
|
||||
|
||||
const HLS_SOURCE_PATTERN = /\.m3u8(\?|#|$)/i;
|
||||
const HLS_SOURCE_TYPES = new Set([
|
||||
'application/vnd.apple.mpegurl',
|
||||
'application/x-mpegurl',
|
||||
'hls',
|
||||
'm3u8',
|
||||
]);
|
||||
|
||||
const MEDIA_ERROR_NAMES: Record<number, string> = {
|
||||
1: 'MEDIA_ERR_ABORTED',
|
||||
2: 'MEDIA_ERR_NETWORK',
|
||||
3: 'MEDIA_ERR_DECODE',
|
||||
4: 'MEDIA_ERR_SRC_NOT_SUPPORTED',
|
||||
};
|
||||
|
||||
export const isHlsSource = (uri: string, sourceType?: string): boolean => {
|
||||
const normalizedType = sourceType?.split(';', 1)[0]?.trim().toLowerCase();
|
||||
return (
|
||||
HLS_SOURCE_PATTERN.test(uri) ||
|
||||
(normalizedType !== undefined && HLS_SOURCE_TYPES.has(normalizedType))
|
||||
);
|
||||
};
|
||||
|
||||
export const isAppleWebKit = (userAgent: string, vendor: string): boolean =>
|
||||
/AppleWebKit/i.test(userAgent) && /Apple/i.test(vendor);
|
||||
|
||||
export const selectWebHlsPlaybackMode = (
|
||||
uri: string,
|
||||
sourceType: string | undefined,
|
||||
{
|
||||
hlsJsSupported,
|
||||
nativeHlsSupport,
|
||||
preferNativeHls,
|
||||
}: WebHlsPlaybackCapabilities,
|
||||
): WebHlsPlaybackMode => {
|
||||
if (!isHlsSource(uri, sourceType)) {
|
||||
return 'native';
|
||||
}
|
||||
|
||||
if (preferNativeHls && nativeHlsSupport) {
|
||||
return 'native';
|
||||
}
|
||||
|
||||
return hlsJsSupported ? 'hls.js' : 'native';
|
||||
};
|
||||
|
||||
const compactText = (value: string): string =>
|
||||
value.replace(/\s+/g, ' ').trim();
|
||||
|
||||
const limitedText = (value: string, maxLength = 160): string => {
|
||||
const compact = compactText(value);
|
||||
return compact.length > maxLength
|
||||
? `${compact.slice(0, maxLength)}…`
|
||||
: compact;
|
||||
};
|
||||
|
||||
const SAFE_RESPONSE_MESSAGES = new Set([
|
||||
'Playlist does not exist',
|
||||
'Video stream not found',
|
||||
]);
|
||||
|
||||
export const sanitizeDiagnosticUrl = (value: string): string => {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
url.username = '';
|
||||
url.password = '';
|
||||
url.search = url.search ? '?<redacted>' : '';
|
||||
url.hash = url.hash ? '#<redacted>' : '';
|
||||
return url.toString().replaceAll('%3Credacted%3E', '<redacted>');
|
||||
} catch {
|
||||
return value.replace(/[?#].*$/, '?<redacted>');
|
||||
}
|
||||
};
|
||||
|
||||
const sanitizeHlsText = (value: string, data: HlsErrorDetails): string => {
|
||||
let sanitized = value;
|
||||
for (const url of [data.response?.url, data.url]) {
|
||||
if (url) {
|
||||
sanitized = sanitized.replaceAll(url, sanitizeDiagnosticUrl(url));
|
||||
}
|
||||
}
|
||||
return limitedText(sanitized);
|
||||
};
|
||||
|
||||
export const describeHlsError = (data: HlsErrorDetails): string => {
|
||||
const parts = [`hls.js fatal ${data.type}: ${data.details}`];
|
||||
|
||||
if (data.reason && data.reason !== data.details) {
|
||||
parts.push(`reason=${sanitizeHlsText(data.reason, data)}`);
|
||||
}
|
||||
|
||||
if (data.error?.message && data.error.message !== data.reason) {
|
||||
parts.push(`message=${sanitizeHlsText(data.error.message, data)}`);
|
||||
}
|
||||
|
||||
const response = data.response;
|
||||
if (response) {
|
||||
if (response.code !== undefined) {
|
||||
const statusText = response.text ? ` ${limitedText(response.text)}` : '';
|
||||
parts.push(`HTTP ${response.code}${statusText}`);
|
||||
}
|
||||
if (typeof response.data === 'string' && response.data.trim()) {
|
||||
const responseBody = compactText(response.data);
|
||||
if (SAFE_RESPONSE_MESSAGES.has(responseBody)) {
|
||||
parts.push(`response=${responseBody}`);
|
||||
} else {
|
||||
parts.push(`responseBodyLength=${response.data.length}`);
|
||||
}
|
||||
}
|
||||
if (response.url) {
|
||||
parts.push(`url=${sanitizeDiagnosticUrl(response.url)}`);
|
||||
}
|
||||
} else if (data.url) {
|
||||
parts.push(`url=${sanitizeDiagnosticUrl(data.url)}`);
|
||||
}
|
||||
|
||||
return parts.join('; ');
|
||||
};
|
||||
|
||||
export const createWebPlaybackErrorReporter = (
|
||||
report: (error: WebVideoError) => void,
|
||||
debounceMs = 50,
|
||||
) => {
|
||||
let hlsError: string | undefined;
|
||||
let hlsDomain: string | undefined;
|
||||
let mediaError: string | undefined;
|
||||
let mediaCode: number | undefined;
|
||||
let timeout: ReturnType<typeof setTimeout> | undefined;
|
||||
let reported = false;
|
||||
|
||||
const clearTimer = () => {
|
||||
if (timeout !== undefined) {
|
||||
clearTimeout(timeout);
|
||||
timeout = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const schedule = () => {
|
||||
if (reported) {
|
||||
return;
|
||||
}
|
||||
clearTimer();
|
||||
timeout = setTimeout(() => {
|
||||
timeout = undefined;
|
||||
reported = true;
|
||||
const errorString = [hlsError, mediaError].filter(Boolean).join('; ');
|
||||
report({
|
||||
errorString,
|
||||
code: mediaCode,
|
||||
domain: hlsError
|
||||
? mediaError
|
||||
? 'hls.js/HTMLMediaElement'
|
||||
: hlsDomain || 'hls.js'
|
||||
: 'HTMLMediaElement',
|
||||
});
|
||||
}, debounceMs);
|
||||
};
|
||||
|
||||
const reset = () => {
|
||||
clearTimer();
|
||||
hlsError = undefined;
|
||||
hlsDomain = undefined;
|
||||
mediaError = undefined;
|
||||
mediaCode = undefined;
|
||||
reported = false;
|
||||
};
|
||||
|
||||
return {
|
||||
addHls(errorString: string, domain: string) {
|
||||
if (reported) {
|
||||
return;
|
||||
}
|
||||
hlsError = errorString;
|
||||
hlsDomain = domain;
|
||||
schedule();
|
||||
},
|
||||
addMedia(errorString: string, code: number) {
|
||||
if (reported) {
|
||||
return;
|
||||
}
|
||||
mediaError = errorString;
|
||||
mediaCode = code;
|
||||
schedule();
|
||||
},
|
||||
reset,
|
||||
};
|
||||
};
|
||||
|
||||
export const describeMediaError = (media: MediaElementDiagnostics): string => {
|
||||
const code = media.error?.code ?? 0;
|
||||
const errorName = MEDIA_ERROR_NAMES[code] ?? 'MEDIA_ERR_UNKNOWN';
|
||||
const parts = [`HTMLMediaElement ${errorName} (${code})`];
|
||||
const message = media.error?.message?.trim();
|
||||
|
||||
if (message) {
|
||||
parts.push(`message=${limitedText(message)}`);
|
||||
}
|
||||
if (media.playbackMode) {
|
||||
parts.push(`mode=${media.playbackMode}`);
|
||||
}
|
||||
if (media.nativeHlsSupport !== undefined) {
|
||||
parts.push(`nativeHlsSupport=${media.nativeHlsSupport || 'none'}`);
|
||||
}
|
||||
if (media.currentSrc) {
|
||||
parts.push(`src=${sanitizeDiagnosticUrl(media.currentSrc)}`);
|
||||
}
|
||||
parts.push(`networkState=${media.networkState}`);
|
||||
parts.push(`readyState=${media.readyState}`);
|
||||
|
||||
return parts.join('; ');
|
||||
};
|
||||
1
test/.gitignore
vendored
Normal file
1
test/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
lib/
|
||||
9
test/tsconfig.json
Normal file
9
test/tsconfig.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"composite": false,
|
||||
"rootDir": "../src",
|
||||
"outDir": "./lib"
|
||||
},
|
||||
"include": ["../src/webHls.ts"]
|
||||
}
|
||||
228
test/web-hls.test.js
Normal file
228
test/web-hls.test.js
Normal file
@@ -0,0 +1,228 @@
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
const assert = require('node:assert/strict');
|
||||
const test = require('node:test');
|
||||
|
||||
const {
|
||||
createWebPlaybackErrorReporter,
|
||||
describeHlsError,
|
||||
describeMediaError,
|
||||
isAppleWebKit,
|
||||
isHlsSource,
|
||||
sanitizeDiagnosticUrl,
|
||||
selectWebHlsPlaybackMode,
|
||||
} = require('./lib/webHls');
|
||||
|
||||
test('recognizes HLS playlist URLs with query strings', () => {
|
||||
assert.equal(isHlsSource('https://api.example/playlist/42.m3u8?vod=1'), true);
|
||||
assert.equal(isHlsSource('https://cdn.example/video.mp4'), false);
|
||||
assert.equal(
|
||||
isHlsSource('https://api.example/playlist/42', 'application/x-mpegURL'),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test('uses hls.js in Chromium even when native HLS support reports maybe', () => {
|
||||
const userAgent =
|
||||
'Mozilla/5.0 Chrome/146.0.0.0 Safari/537.36 AppleWebKit/537.36';
|
||||
assert.equal(isAppleWebKit(userAgent, 'Google Inc.'), false);
|
||||
assert.equal(
|
||||
selectWebHlsPlaybackMode(
|
||||
'https://api.example/playlist/42.m3u8',
|
||||
undefined,
|
||||
{
|
||||
hlsJsSupported: true,
|
||||
nativeHlsSupport: 'maybe',
|
||||
preferNativeHls: isAppleWebKit(userAgent, 'Google Inc.'),
|
||||
},
|
||||
),
|
||||
'hls.js',
|
||||
);
|
||||
});
|
||||
|
||||
test('uses hls.js for an extensionless HLS source with an explicit type', () => {
|
||||
assert.equal(
|
||||
selectWebHlsPlaybackMode(
|
||||
'https://api.example/playlist/42',
|
||||
'application/vnd.apple.mpegurl; charset=utf-8',
|
||||
{
|
||||
hlsJsSupported: true,
|
||||
nativeHlsSupport: '',
|
||||
preferNativeHls: false,
|
||||
},
|
||||
),
|
||||
'hls.js',
|
||||
);
|
||||
});
|
||||
|
||||
test('preserves native HLS in Apple WebKit browsers', () => {
|
||||
const userAgent =
|
||||
'Mozilla/5.0 Version/18.6 Safari/605.1.15 AppleWebKit/605.1.15';
|
||||
assert.equal(isAppleWebKit(userAgent, 'Apple Computer, Inc.'), true);
|
||||
assert.equal(
|
||||
selectWebHlsPlaybackMode(
|
||||
'https://api.example/playlist/42.m3u8',
|
||||
undefined,
|
||||
{
|
||||
hlsJsSupported: true,
|
||||
nativeHlsSupport: 'maybe',
|
||||
preferNativeHls: isAppleWebKit(userAgent, 'Apple Computer, Inc.'),
|
||||
},
|
||||
),
|
||||
'native',
|
||||
);
|
||||
});
|
||||
|
||||
test('falls back to native playback when hls.js is unavailable', () => {
|
||||
assert.equal(
|
||||
selectWebHlsPlaybackMode(
|
||||
'https://api.example/playlist/42.m3u8',
|
||||
undefined,
|
||||
{
|
||||
hlsJsSupported: false,
|
||||
nativeHlsSupport: 'probably',
|
||||
preferNativeHls: false,
|
||||
},
|
||||
),
|
||||
'native',
|
||||
);
|
||||
assert.equal(
|
||||
selectWebHlsPlaybackMode('https://cdn.example/video.mp4', undefined, {
|
||||
hlsJsSupported: true,
|
||||
nativeHlsSupport: '',
|
||||
preferNativeHls: false,
|
||||
}),
|
||||
'native',
|
||||
);
|
||||
});
|
||||
|
||||
test('includes fatal HLS network and response details', () => {
|
||||
assert.equal(
|
||||
describeHlsError({
|
||||
type: 'networkError',
|
||||
details: 'manifestParsingError',
|
||||
reason: 'no EXTM3U delimiter',
|
||||
error: {message: 'manifest parsing failed'},
|
||||
response: {
|
||||
code: 200,
|
||||
text: 'OK',
|
||||
data: 'Playlist does not exist',
|
||||
url: 'https://api.example/playlist/42.m3u8',
|
||||
},
|
||||
}),
|
||||
'hls.js fatal networkError: manifestParsingError; ' +
|
||||
'reason=no EXTM3U delimiter; message=manifest parsing failed; HTTP 200 OK; ' +
|
||||
'response=Playlist does not exist; ' +
|
||||
'url=https://api.example/playlist/42.m3u8',
|
||||
);
|
||||
});
|
||||
|
||||
test('redacts URL credentials, query values, and unknown response bodies', () => {
|
||||
assert.equal(
|
||||
sanitizeDiagnosticUrl(
|
||||
'https://user:password@cdn.example/42.m3u8?token=secret#private',
|
||||
),
|
||||
'https://cdn.example/42.m3u8?<redacted>#<redacted>',
|
||||
);
|
||||
assert.equal(
|
||||
describeHlsError({
|
||||
type: 'networkError',
|
||||
details: 'manifestLoadError',
|
||||
response: {
|
||||
code: 403,
|
||||
data: 'internal credential: secret',
|
||||
url: 'https://cdn.example/42.m3u8?token=secret',
|
||||
},
|
||||
}),
|
||||
'hls.js fatal networkError: manifestLoadError; HTTP 403; ' +
|
||||
'responseBodyLength=27; url=https://cdn.example/42.m3u8?<redacted>',
|
||||
);
|
||||
assert.equal(
|
||||
describeHlsError({
|
||||
type: 'keySystemError',
|
||||
details: 'licenseRequestFailed',
|
||||
error: {
|
||||
message:
|
||||
'License request failed (https://license.example/key?token=secret)',
|
||||
},
|
||||
url: 'https://license.example/key?token=secret',
|
||||
}),
|
||||
'hls.js fatal keySystemError: licenseRequestFailed; ' +
|
||||
'message=License request failed (https://license.example/key?<redacted>); ' +
|
||||
'url=https://license.example/key?<redacted>',
|
||||
);
|
||||
});
|
||||
|
||||
const wait = (milliseconds) =>
|
||||
new Promise((resolve) => setTimeout(resolve, milliseconds));
|
||||
|
||||
for (const order of ['hls-first', 'media-first']) {
|
||||
test(`combines HLS and media errors once when ${order}`, async () => {
|
||||
const reports = [];
|
||||
const reporter = createWebPlaybackErrorReporter(
|
||||
(error) => reports.push(error),
|
||||
5,
|
||||
);
|
||||
const addHls = () =>
|
||||
reporter.addHls(
|
||||
'hls.js fatal mediaError: bufferAppendError',
|
||||
'hls.js/mediaError',
|
||||
);
|
||||
const addMedia = () =>
|
||||
reporter.addMedia('HTMLMediaElement MEDIA_ERR_DECODE (3)', 3);
|
||||
|
||||
if (order === 'hls-first') {
|
||||
addHls();
|
||||
addMedia();
|
||||
} else {
|
||||
addMedia();
|
||||
addHls();
|
||||
}
|
||||
await wait(15);
|
||||
|
||||
assert.deepEqual(reports, [
|
||||
{
|
||||
errorString:
|
||||
'hls.js fatal mediaError: bufferAppendError; ' +
|
||||
'HTMLMediaElement MEDIA_ERR_DECODE (3)',
|
||||
code: 3,
|
||||
domain: 'hls.js/HTMLMediaElement',
|
||||
},
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
test('reset cancels a pending source error and permits the next source', async () => {
|
||||
const reports = [];
|
||||
const reporter = createWebPlaybackErrorReporter(
|
||||
(error) => reports.push(error),
|
||||
5,
|
||||
);
|
||||
reporter.addHls('stale source failure', 'hls.js/networkError');
|
||||
reporter.reset();
|
||||
reporter.addMedia('current source failure', 4);
|
||||
await wait(15);
|
||||
|
||||
assert.deepEqual(reports, [
|
||||
{
|
||||
errorString: 'current source failure',
|
||||
code: 4,
|
||||
domain: 'HTMLMediaElement',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test('names media error code 4 and records the selected playback path', () => {
|
||||
assert.equal(
|
||||
describeMediaError({
|
||||
currentSrc: 'https://api.example/playlist/42.m3u8',
|
||||
networkState: 3,
|
||||
readyState: 0,
|
||||
error: {code: 4},
|
||||
playbackMode: 'native',
|
||||
nativeHlsSupport: 'maybe',
|
||||
}),
|
||||
'HTMLMediaElement MEDIA_ERR_SRC_NOT_SUPPORTED (4); mode=native; ' +
|
||||
'nativeHlsSupport=maybe; src=https://api.example/playlist/42.m3u8; ' +
|
||||
'networkState=3; readyState=0',
|
||||
);
|
||||
});
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
{
|
||||
"extends": "./tsconfig",
|
||||
"exclude": ["examples", "lib"]
|
||||
|
||||
@@ -14,8 +14,8 @@
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"jsx": "react",
|
||||
"lib": ["esnext"],
|
||||
"module": "CommonJS",
|
||||
"moduleResolution": "node",
|
||||
"module": "Node16",
|
||||
"moduleResolution": "Node16",
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noImplicitReturns": true,
|
||||
"noImplicitUseStrict": false,
|
||||
|
||||
Reference in New Issue
Block a user