6 changed files with 184 additions and 324 deletions
+108
View File
@@ -170,6 +170,114 @@ pub async fn open_url(app: tauri::AppHandle, url: String) -> Result<(), String>
.map_err(|e| e.to_string())
}
/// 切换移动端屏幕方向(iOS 原生旋转屏幕方向:横屏 Landscape / 竖屏 Portrait)。
#[tauri::command]
pub async fn set_orientation(app: tauri::AppHandle, landscape: bool) -> Result<(), String> {
#[cfg(target_os = "ios")]
{
let _ = app.run_on_main_thread(move || {
request_ios_orientation(landscape);
});
}
#[cfg(not(target_os = "ios"))]
{
let _ = (&app, landscape);
}
Ok(())
}
#[cfg(target_os = "ios")]
fn request_ios_orientation(landscape: bool) {
use std::ffi::{c_char, c_void};
extern "C" {
fn objc_getClass(name: *const c_char) -> *mut c_void;
fn sel_registerName(name: *const c_char) -> *mut c_void;
fn objc_msgSend();
}
unsafe {
let msg0: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
std::mem::transmute(objc_msgSend as *const ());
let msg0_usize: unsafe extern "C" fn(*mut c_void, *mut c_void) -> usize =
std::mem::transmute(objc_msgSend as *const ());
let msg1_usize: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
std::mem::transmute(objc_msgSend as *const ());
let msg2_ptr: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void, *mut c_void) =
std::mem::transmute(objc_msgSend as *const ());
let msg1_void: unsafe extern "C" fn(*mut c_void, *mut c_void) =
std::mem::transmute(objc_msgSend as *const ());
// 1. iOS 16+ UIWindowScene.requestGeometryUpdateWithPreferences:errorHandler:
// UIInterfaceOrientationMaskPortrait = 1 << 1 = 2
// UIInterfaceOrientationMaskLandscapeRight = 1 << 3 = 8
let mask: usize = if landscape { 8 } else { 2 };
let prefs_cls = objc_getClass(b"UIWindowSceneGeometryPreferencesIOS\0".as_ptr() as *const c_char);
let app_cls = objc_getClass(b"UIApplication\0".as_ptr() as *const c_char);
if !prefs_cls.is_null() && !app_cls.is_null() {
let sel_alloc = sel_registerName(b"alloc\0".as_ptr() as *const c_char);
let sel_init = sel_registerName(b"initWithInterfaceOrientations:\0".as_ptr() as *const c_char);
let raw_prefs = msg0(prefs_cls, sel_alloc);
let prefs = if !raw_prefs.is_null() {
msg1_usize(raw_prefs, sel_init, mask)
} else {
std::ptr::null_mut()
};
let sel_shared = sel_registerName(b"sharedApplication\0".as_ptr() as *const c_char);
let app = msg0(app_cls, sel_shared);
if !app.is_null() && !prefs.is_null() {
let sel_scenes = sel_registerName(b"connectedScenes\0".as_ptr() as *const c_char);
let scenes_set = msg0(app, sel_scenes);
if !scenes_set.is_null() {
let sel_all = sel_registerName(b"allObjects\0".as_ptr() as *const c_char);
let arr = msg0(scenes_set, sel_all);
if !arr.is_null() {
let sel_count = sel_registerName(b"count\0".as_ptr() as *const c_char);
let sel_at = sel_registerName(b"objectAtIndex:\0".as_ptr() as *const c_char);
let sel_req = sel_registerName(
b"requestGeometryUpdateWithPreferences:errorHandler:\0".as_ptr() as *const c_char,
);
let sel_responds = sel_registerName(b"respondsToSelector:\0".as_ptr() as *const c_char);
let msg_responds: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> bool =
std::mem::transmute(objc_msgSend as *const ());
let count = msg0_usize(arr, sel_count);
for i in 0..count {
let scene = msg1_usize(arr, sel_at, i);
if !scene.is_null() && msg_responds(scene, sel_responds, sel_req) {
msg2_ptr(scene, sel_req, prefs, std::ptr::null_mut());
}
}
}
}
}
}
// 2. Fallback: UIDevice setValue:forKey:@"orientation" + attemptRotationToDeviceOrientation
let dev_cls = objc_getClass(b"UIDevice\0".as_ptr() as *const c_char);
let num_cls = objc_getClass(b"NSNumber\0".as_ptr() as *const c_char);
let str_cls = objc_getClass(b"NSString\0".as_ptr() as *const c_char);
let vc_cls = objc_getClass(b"UIViewController\0".as_ptr() as *const c_char);
if !dev_cls.is_null() && !num_cls.is_null() && !str_cls.is_null() {
let sel_cur = sel_registerName(b"currentDevice\0".as_ptr() as *const c_char);
let dev = msg0(dev_cls, sel_cur);
let sel_num = sel_registerName(b"numberWithInteger:\0".as_ptr() as *const c_char);
let orient_val: usize = if landscape { 3 } else { 1 };
let num = msg1_usize(num_cls, sel_num, orient_val);
let sel_str = sel_registerName(b"stringWithUTF8String:\0".as_ptr() as *const c_char);
let msg_str: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_char) -> *mut c_void =
std::mem::transmute(objc_msgSend as *const ());
let key = msg_str(str_cls, sel_str, b"orientation\0".as_ptr() as *const c_char);
if !dev.is_null() && !num.is_null() && !key.is_null() {
let sel_set_val = sel_registerName(b"setValue:forKey:\0".as_ptr() as *const c_char);
msg2_ptr(dev, sel_set_val, num, key);
}
if !vc_cls.is_null() {
let sel_attempt = sel_registerName(b"attemptRotationToDeviceOrientation\0".as_ptr() as *const c_char);
msg1_void(vc_cls, sel_attempt);
}
}
}
}
/* ───────────────────────── 会话 ───────────────────────── */
#[tauri::command]
+1
View File
@@ -140,6 +140,7 @@ pub fn run() {
api::line_probe,
api::check_update,
api::open_url,
api::set_orientation,
api::api_login,
api::api_register,
api::api_logout,
+2 -5
View File
@@ -9,12 +9,9 @@ import type {
export const APP_VERSION = __APP_VERSION__;
const ua = navigator.userAgent;
/** iPhone 的 UA 也带「like Mac OS X」,必须先于 macOS 判断;iPadOS 默认伪装成 Mac,用触点数区分。 */
export const isIos =
/iPhone|iPad|iPod/i.test(ua) ||
(/Macintosh/i.test(ua) && navigator.maxTouchPoints > 1) ||
(typeof navigator.platform === "string" && navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
export const isAndroid = /Android/i.test(ua);
/** iPhone 的 UA 也带「like Mac OS X」,必须先于 macOS 判断;iPadOS 默认伪装成 Mac,用触点数区分。 */
export const isIos = /iPhone|iPad|iPod/i.test(ua) || (/Macintosh/i.test(ua) && navigator.maxTouchPoints > 1);
export const isMacos = !isIos && /Macintosh|Mac OS X/i.test(ua);
export const platform: "android" | "ios" | "windows" | "macos" =
isAndroid ? "android" : isIos ? "ios" : isMacos ? "macos" : "windows";
+8 -46
View File
@@ -1,6 +1,6 @@
import React, { useEffect, useRef, useState } from "react";
import Hls from "hls.js";
import { fmtTime, platform, playlist } from "../api";
import { fmtTime, playlist } from "../api";
import { mediaResource, observeHls, usePlayerDiagnostics } from "../playbackDiagnostics";
import { usePlaybackActivity } from "../usePlaybackActivity";
import { useSeekInput } from "../useSeekInput";
@@ -30,7 +30,6 @@ export default function Player({
const videoRef = useRef<HTMLVideoElement>(null);
const wrapRef = useRef<HTMLDivElement>(null);
const hlsRef = useRef<Hls | null>(null);
const recoverCountRef = useRef(0);
const { trace, requestSeek } = usePlayerDiagnostics(videoRef, hlsRef, { view: "post_detail", ...diagnosticContext, active, resource: mediaResource(src) });
const activity = usePlaybackActivity(videoRef, hlsRef, { active, autoPlay: !!autoPlay, src, trace });
const [playing, setPlaying] = useState(false);
@@ -47,10 +46,6 @@ export default function Player({
const video = videoRef.current;
if (!video || !activity.isActive()) return;
requestSeek(target, `legacy_${input}`);
setWaiting(true);
if (hlsRef.current) {
try { hlsRef.current.startLoad(target); } catch { /* ignore */ }
}
video.currentTime = target;
trace("seek.assigned", { target });
setTime(video.currentTime);
@@ -61,8 +56,6 @@ export default function Player({
const video = videoRef.current;
if (!video || !src) return;
const url = playlist(src);
recoverCountRef.current = 0;
setErrMsg("");
trace("source.load", { engine: Hls.isSupported() ? "hls.js" : "native", auto_play: autoPlay });
if (hlsRef.current) { hlsRef.current.destroy(); hlsRef.current = null; }
@@ -73,22 +66,16 @@ export default function Player({
interstitialsController: undefined,
contentSteeringController: undefined,
enableInterstitialPlayback: false,
enableWorker: platform !== "ios",
enableWorker: true,
// Keep the same macOS seek workaround as the shared player.
preferManagedMediaSource: false,
autoStartLoad: false,
lowLatencyMode: false,
maxBufferLength: 30,
maxMaxBufferLength: 60,
maxBufferLength: 24,
backBufferLength: 30,
maxBufferHole: 0.5,
nudgeOffset: 0.25,
nudgeMaxRetry: 6,
manifestLoadingTimeOut: 20000,
manifestLoadingMaxRetry: 4,
fragLoadingTimeOut: 25000,
fragLoadingMaxRetry: 6,
fragLoadingRetryDelay: 400,
manifestLoadingMaxRetry: 3,
fragLoadingMaxRetry: 4,
});
hlsRef.current = hls;
observeHls(hls, trace);
@@ -98,34 +85,12 @@ export default function Player({
if (activity.isActive()) hls.startLoad();
if (autoPlay) activity.play("manifest_autoplay", true);
});
hls.on(Hls.Events.FRAG_BUFFERED, () => {
recoverCountRef.current = 0;
setErrMsg("");
});
hls.on(Hls.Events.ERROR, (_e, data) => {
if (!data.fatal) {
if (
data.details === Hls.ErrorDetails.BUFFER_STALLED_ERROR ||
data.details === Hls.ErrorDetails.FRAG_LOAD_ERROR
) {
try { hls.startLoad(video.currentTime || -1); } catch { /* ignore */ }
}
return;
}
if (!activity.isActive()) return;
if (data.type === Hls.ErrorTypes.NETWORK_ERROR && recoverCountRef.current < 4) {
recoverCountRef.current += 1;
try { hls.startLoad(video.currentTime || -1); } catch { /* ignore */ }
return;
}
if (data.type === Hls.ErrorTypes.MEDIA_ERROR && recoverCountRef.current < 4) {
recoverCountRef.current += 1;
try { hls.recoverMediaError(); video.play().catch(() => {}); } catch { /* ignore */ }
return;
}
if (!data.fatal) return;
const detail = `${data.type}/${data.details}/${data.response?.code ?? ""}/${String(data.reason ?? "").slice(0, 80)}`;
(window as unknown as { __hlsErr?: string }).__hlsErr = detail;
setErrMsg(detail);
if (!activity.isActive()) return;
if (data.type === Hls.ErrorTypes.NETWORK_ERROR) hls.startLoad();
else if (data.type === Hls.ErrorTypes.MEDIA_ERROR) hls.recoverMediaError();
else { hls.destroy(); hlsRef.current = null; }
@@ -186,8 +151,6 @@ export default function Player({
ref={videoRef}
poster={poster}
playsInline
webkit-playsinline="true"
preload="auto"
muted={muted}
loop={loop}
className="w-full h-full object-contain bg-black"
@@ -195,8 +158,7 @@ export default function Player({
onPlay={() => { if (activity.isActive()) { setPlaying(true); onTogglePlay?.(true); } }}
onPause={() => { setPlaying(false); onTogglePlay?.(false); }}
onWaiting={() => setWaiting(true)}
onPlaying={() => { if (activity.isActive()) { setWaiting(false); setErrMsg(""); onPlaying?.(); } }}
onSeeked={() => setWaiting(false)}
onPlaying={() => { if (activity.isActive()) { setWaiting(false); onPlaying?.(); } }}
onTimeUpdate={(e) => setTime((e.target as HTMLVideoElement).currentTime)}
onLoadedMetadata={(e) => setDuration((e.target as HTMLVideoElement).duration || 0)}
onEnded={() => { if (activity.isActive()) onEnded?.(); }}
+44 -269
View File
@@ -1,6 +1,6 @@
import React, { useEffect, useImperativeHandle, useRef, forwardRef, useState } from "react";
import { useEffect, useImperativeHandle, useRef, forwardRef, useState } from "react";
import Hls from "hls.js";
import { isLocalMedia, platform, playlist } from "../api";
import { isLocalMedia, playlist } from "../api";
import { mediaResource, observeHls, usePlayerDiagnostics } from "../playbackDiagnostics";
import { usePlaybackActivity } from "../usePlaybackActivity";
@@ -9,12 +9,11 @@ export type VideoHandle = {
play: () => void;
pause: () => void;
toggle: () => void;
seek: (t: number, sourceOrAutoResume?: string | boolean) => void;
seek: (t: number, source?: string) => void;
trace: (event: string, data?: Record<string, unknown>) => void;
rate: (r: number) => void;
mute: (m: boolean) => void;
volume: (v: number) => void;
reload: () => void;
};
type Props = {
@@ -26,11 +25,6 @@ type Props = {
muted?: boolean;
loop?: boolean;
fit?: "contain" | "cover";
/** 缩放倍率与平移偏移(用于移动端竖屏下双指缩放横屏视频) */
scale?: number;
panX?: number;
panY?: number;
isGesturing?: boolean;
/** 换源后重新套用,避免切集时音量/倍速被浏览器重置 */
volume?: number;
rate?: number;
@@ -48,75 +42,16 @@ type Props = {
/** 只负责「播」:hls.js + video 元素,控制条由外层渲染。 */
const VideoSurface = forwardRef<VideoHandle, Props>(function VideoSurface(
{ src, poster, autoPlay = true, active = true, diagnosticContext = {}, muted = false, loop = false, fit = "contain",
scale = 1, panX = 0, panY = 0, isGesturing = false,
volume = 1, rate = 1,
{ src, poster, autoPlay = true, active = true, diagnosticContext = {}, muted = false, loop = false, fit = "contain", volume = 1, rate = 1,
onTime, onDuration, onSize, onPlaying, onPause, onWaiting, onEnded, onError, onClick, className = "" },
ref,
) {
const videoRef = useRef<HTMLVideoElement>(null);
const hlsRef = useRef<Hls | null>(null);
const recoverCountRef = useRef(0);
const recoverTimerRef = useRef<number | null>(null);
const lastSizeRef = useRef({ w: 0, h: 0 });
const [ready, setReady] = useState(false);
const { trace, requestSeek } = usePlayerDiagnostics(videoRef, hlsRef, { ...diagnosticContext, active, resource: mediaResource(src) });
const activity = usePlaybackActivity(videoRef, hlsRef, { active, autoPlay, src, trace });
const reportSizeAndDuration = (v: HTMLVideoElement) => {
if (v.duration && Number.isFinite(v.duration) && v.duration > 0) {
onDuration?.(v.duration);
}
const w = v.videoWidth || 0;
const h = v.videoHeight || 0;
if (w > 0 && h > 0 && (w !== lastSizeRef.current.w || h !== lastSizeRef.current.h)) {
lastSizeRef.current = { w, h };
onSize?.(w, h);
}
};
const safeSeek = (t: number, sourceOrAutoResume: string | boolean = "handle") => {
const v = videoRef.current;
if (!v || !Number.isFinite(t)) return;
const dur = v.duration && Number.isFinite(v.duration) ? v.duration : 0;
const target = dur > 0 ? Math.max(0, Math.min(dur - 0.15, t)) : Math.max(0, t);
const source = typeof sourceOrAutoResume === "string" ? sourceOrAutoResume : "handle";
const autoResume = typeof sourceOrAutoResume === "boolean" ? sourceOrAutoResume : !v.paused;
requestSeek(target, source);
onWaiting?.();
if (hlsRef.current) {
try {
hlsRef.current.startLoad(target);
} catch { /* ignore */ }
}
try {
v.currentTime = target;
trace("seek.assigned", { target, source });
} catch (e) {
trace("seek.rejected", { error_name: (e as Error).name });
}
if (autoResume && activity.isActive()) {
const resumeOnce = () => {
v.removeEventListener("seeked", resumeOnce);
v.removeEventListener("canplay", resumeOnce);
if (activity.isActive()) v.play().catch(() => {});
};
v.addEventListener("seeked", resumeOnce, { once: true });
v.addEventListener("canplay", resumeOnce, { once: true });
// 兜底:若 350ms 内已经就绪则直接播
window.setTimeout(() => {
if (v.readyState >= 2 && v.paused && activity.isActive()) {
v.removeEventListener("seeked", resumeOnce);
v.removeEventListener("canplay", resumeOnce);
v.play().catch(() => {});
}
}, 350);
}
};
useImperativeHandle(ref, () => ({
el: () => videoRef.current,
play: () => activity.play("handle"),
@@ -127,47 +62,29 @@ const VideoSurface = forwardRef<VideoHandle, Props>(function VideoSurface(
trace("toggle.request");
if (v.paused) activity.play("toggle"); else activity.pause("toggle");
},
seek: (t: number, sourceOrAutoResume: string | boolean = "handle") => safeSeek(t, sourceOrAutoResume),
seek: (t: number, source = "handle") => {
const v = videoRef.current;
if (v && Number.isFinite(t)) {
requestSeek(t, source);
try { v.currentTime = t; trace("seek.assigned", { target: t, source }); }
catch (e) { trace("seek.rejected", { error_name: (e as Error).name }); throw e; }
}
},
trace,
rate: (r: number) => { const v = videoRef.current; if (v) v.playbackRate = r; },
mute: (m: boolean) => { const v = videoRef.current; if (v) v.muted = m; },
volume: (vol: number) => { const v = videoRef.current; if (v) v.volume = vol; },
reload: () => {
const v = videoRef.current;
if (!v) return;
recoverCountRef.current = 0;
const cur = v.currentTime || 0;
if (hlsRef.current) {
try {
hlsRef.current.startLoad(cur);
activity.play("reload");
return;
} catch { /* ignore */ }
}
v.load();
if (cur > 0) {
try { v.currentTime = cur; } catch { /* ignore */ }
}
activity.play("reload");
},
}));
}), []);
useEffect(() => {
const video = videoRef.current;
if (!video || !src) return;
setReady(false);
recoverCountRef.current = 0;
lastSizeRef.current = { w: 0, h: 0 };
if (recoverTimerRef.current) {
window.clearTimeout(recoverTimerRef.current);
recoverTimerRef.current = null;
}
if (hlsRef.current) { hlsRef.current.destroy(); hlsRef.current = null; }
const proxied = isLocalMedia(src);
const url = proxied ? src : playlist(src);
const useHls = !url.includes("/seg?u=");
const isIos = platform === "ios";
trace("source.load", { engine: useHls && Hls.isSupported() ? "hls.js" : "native", auto_play: autoPlay, resource: mediaResource(src) });
/* 换源时先把音量/倍速套回去:hls 重新 attach 后浏览器会把它们重置成默认值 */
@@ -186,27 +103,15 @@ const VideoSurface = forwardRef<VideoHandle, Props>(function VideoSurface(
interstitialsController: undefined,
contentSteeringController: undefined,
enableInterstitialPlayback: false,
// iOS WKWebView 下 WebWorker 跨自定义协议 hg:// 高频中断易死锁,关闭 Worker 走主线程加载更稳
enableWorker: !isIos,
enableWorker: true,
// Prefer standard MSE on macOS; hls.js handles MMS-only fallback and seek recovery.
preferManagedMediaSource: false,
autoStartLoad: false,
lowLatencyMode: false,
maxBufferLength: 30,
maxMaxBufferLength: 60,
backBufferLength: 30,
maxBufferHole: 0.5,
highBufferWatchdogPeriod: 2,
nudgeOffset: 0.25,
nudgeMaxRetry: 6,
manifestLoadingTimeOut: 20000,
manifestLoadingMaxRetry: 4,
levelLoadingTimeOut: 20000,
levelLoadingMaxRetry: 4,
fragLoadingTimeOut: 25000,
fragLoadingMaxRetry: 6,
fragLoadingRetryDelay: 400,
startFragPrefetch: true,
manifestLoadingMaxRetry: 3,
fragLoadingMaxRetry: 4,
});
hlsRef.current = hls;
observeHls(hls, trace);
@@ -216,63 +121,13 @@ const VideoSurface = forwardRef<VideoHandle, Props>(function VideoSurface(
if (activity.isActive()) hls.startLoad();
if (autoPlay) activity.play("manifest_autoplay", true);
});
hls.on(Hls.Events.FRAG_BUFFERED, () => {
recoverCountRef.current = 0;
setReady(true);
});
hls.on(Hls.Events.ERROR, (_e, data) => {
// 非致命卡顿错误(常见于拖动进度条后缓冲空洞):主动触发加载与微调跳帧
if (!data.fatal) {
if (
activity.isActive() && (
data.details === Hls.ErrorDetails.BUFFER_STALLED_ERROR ||
data.details === Hls.ErrorDetails.FRAG_LOAD_ERROR ||
data.details === Hls.ErrorDetails.FRAG_LOAD_TIMEOUT
)
) {
try {
hls.startLoad(video.currentTime || -1);
} catch { /* ignore */ }
}
return;
}
if (!data.fatal) return;
onError?.(`${data.type}/${data.details}`);
if (!activity.isActive()) return;
// 致命错误:优先自动重连/恢复解码器,最多静默恢复 4 次,避免拖动进度条直接弹报错层
if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
if (recoverCountRef.current < 4) {
recoverCountRef.current += 1;
const delay = 250 * recoverCountRef.current;
if (recoverTimerRef.current) window.clearTimeout(recoverTimerRef.current);
recoverTimerRef.current = window.setTimeout(() => {
if (!hlsRef.current || !activity.isActive()) return;
try {
hlsRef.current.startLoad(video.currentTime || -1);
if (!video.paused) video.play().catch(() => {});
} catch { /* ignore */ }
}, delay);
return;
}
onError?.(`${data.type}/${data.details}`);
hls.startLoad();
} else if (data.type === Hls.ErrorTypes.MEDIA_ERROR) {
if (recoverCountRef.current < 4) {
recoverCountRef.current += 1;
try {
if (recoverCountRef.current === 2) hls.swapAudioCodec();
hls.recoverMediaError();
video.play().catch(() => {});
} catch { /* ignore */ }
return;
}
onError?.(`${data.type}/${data.details}`);
hls.recoverMediaError();
} else {
onError?.(`${data.type}/${data.details}`);
hls.destroy();
hlsRef.current = null;
}
if (data.type === Hls.ErrorTypes.NETWORK_ERROR) hls.startLoad();
else if (data.type === Hls.ErrorTypes.MEDIA_ERROR) hls.recoverMediaError();
else { hls.destroy(); hlsRef.current = null; }
});
} else {
video.src = url;
@@ -281,10 +136,6 @@ const VideoSurface = forwardRef<VideoHandle, Props>(function VideoSurface(
return () => {
trace("source.cleanup");
if (recoverTimerRef.current) {
window.clearTimeout(recoverTimerRef.current);
recoverTimerRef.current = null;
}
if (hlsRef.current) { hlsRef.current.destroy(); hlsRef.current = null; }
};
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -300,106 +151,30 @@ const VideoSurface = forwardRef<VideoHandle, Props>(function VideoSurface(
v.playbackRate = rate;
};
const nearEndFiredRef = useRef(false);
useEffect(() => {
nearEndFiredRef.current = false;
}, [src]);
// Native Resize Event listener for HTMLVideoElement (React doesn't always bind onResize on <video>)
useEffect(() => {
const v = videoRef.current;
if (!v) return undefined;
const onVideoResize = () => reportSizeAndDuration(v);
v.addEventListener("resize", onVideoResize);
return () => v.removeEventListener("resize", onVideoResize);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [src]);
const hasTransform = scale !== 1 || panX !== 0 || panY !== 0;
return (
<div className={`relative w-full h-full bg-black overflow-hidden ${className}`}>
{!ready && poster && (
<img
src={poster}
alt=""
className={`absolute inset-0 w-full h-full pointer-events-none ${fit === "cover" ? "object-cover" : "object-contain"}`}
/>
)}
<video
ref={videoRef}
playsInline
webkit-playsinline="true"
preload="auto"
muted={muted}
loop={loop}
onClick={onClick}
className={`w-full h-full bg-black ${fit === "cover" ? "object-cover" : "object-contain"}`}
style={{
opacity: ready ? 1 : 0,
transform: hasTransform ? `translate3d(${panX}px, ${panY}px, 0) scale(${scale})` : "translateZ(0)",
transformOrigin: "center center",
transition: isGesturing ? "opacity .25s" : "opacity .25s, transform .2s cubic-bezier(.2,0,0,1)",
}}
onLoadedData={(e) => {
const v = e.target as HTMLVideoElement;
setReady(true);
reapply(v);
reportSizeAndDuration(v);
}}
onCanPlay={(e) => {
const v = e.target as HTMLVideoElement;
setReady(true);
reportSizeAndDuration(v);
}}
onTimeUpdate={(e) => {
const v = e.target as HTMLVideoElement;
onTime?.(v.currentTime);
if (lastSizeRef.current.w === 0 && v.videoWidth > 0) {
reportSizeAndDuration(v);
}
// 借鉴 stclock1988/hghub-ios:部分 HLS 流容器标称时长比最后一个分片略长 0.5~1.2s,
// 接近片尾时提前复位准备,若卡在片尾则自动触发连播
if (!loop && !nearEndFiredRef.current && activity.isActive() && v.duration > 5 && v.currentTime >= v.duration - 0.35) {
nearEndFiredRef.current = true;
onEnded?.();
}
}}
onLoadedMetadata={(e) => {
const v = e.target as HTMLVideoElement;
reapply(v);
reportSizeAndDuration(v);
}}
onPlay={() => { if (activity.isActive()) onPlaying?.(); }}
onPause={() => onPause?.()}
onWaiting={(e) => {
const v = e.target as HTMLVideoElement;
if (!loop && !nearEndFiredRef.current && activity.isActive() && v.duration > 5 && v.currentTime >= v.duration - 1.5) {
nearEndFiredRef.current = true;
onEnded?.();
return;
}
onWaiting?.();
}}
onPlaying={(e) => {
setReady(true);
recoverCountRef.current = 0;
reportSizeAndDuration(e.target as HTMLVideoElement);
if (activity.isActive()) onPlaying?.();
}}
onSeeking={() => onWaiting?.()}
onSeeked={() => {
const v = videoRef.current;
if (v && !v.paused && activity.isActive()) onPlaying?.();
}}
onEnded={() => {
if (!nearEndFiredRef.current && activity.isActive()) {
nearEndFiredRef.current = true;
onEnded?.();
}
}}
/>
</div>
<video
ref={videoRef}
poster={poster}
playsInline
muted={muted}
loop={loop}
onClick={onClick}
className={`w-full h-full bg-black ${fit === "cover" ? "object-cover" : "object-contain"} ${className}`}
style={{ opacity: ready ? 1 : 0, transition: "opacity .35s" }}
onLoadedData={(e) => { setReady(true); reapply(e.target as HTMLVideoElement); }}
onTimeUpdate={(e) => onTime?.((e.target as HTMLVideoElement).currentTime)}
onLoadedMetadata={(e) => {
const v = e.target as HTMLVideoElement;
reapply(v);
onDuration?.(v.duration || 0);
onSize?.(v.videoWidth || 0, v.videoHeight || 0);
}}
onPlay={() => { if (activity.isActive()) onPlaying?.(); }}
onPause={() => onPause?.()}
onWaiting={() => onWaiting?.()}
onPlaying={() => { if (activity.isActive()) onPlaying?.(); }}
onEnded={() => { if (activity.isActive()) onEnded?.(); }}
/>
);
});
+21 -4
View File
@@ -34,6 +34,7 @@
}
.plat-windows { --r-sm: 4px; --r-md: 8px; --r-lg: 8px; --r-ctl: 4px; --nav-h: 0px; }
.plat-macos { --r-sm: 6px; --r-md: 10px; --r-lg: 12px; --r-ctl: 6px; --nav-h: 0px; }
.plat-ios { --r-sm: 10px; --r-md: 14px; --r-lg: 18px; --r-ctl: 999px; -webkit-touch-callout: none; }
html.theme-light {
color-scheme: light;
--p-canvas: #f3f3f3;
@@ -152,7 +153,7 @@ html.theme-light .elev-3 { box-shadow: 0 10px 30px rgba(0,0,0,.1); }
.a-panel-out { animation: kf-panel-out .2s ease-in both; }
@keyframes kf-scale-in { from{opacity:0;transform:scale(.92)} to{opacity:1;transform:scale(1)} }
.a-scale-in { animation: kf-scale-in .22s cubic-bezier(.2,0,0,1) both; }
@keyframes kf-page-in { from{transform:translateX(100%)} to{transform:translateX(0)} }
@keyframes kf-page-in { from{transform:translateX(100%)} to{transform:none} }
.a-page-in { animation: kf-page-in .3s cubic-bezier(.2,0,0,1) both; }
@keyframes kf-page-out { from{transform:translateX(0)} to{transform:translateX(100%)} }
.a-page-out { animation: kf-page-out .22s cubic-bezier(.3,0,.8,.15) both; }
@@ -250,7 +251,8 @@ input[type="range"].hg-range::-webkit-slider-thumb { -webkit-appearance: none; w
原生全屏时红绿灯被系统隐藏(is-native-fs),让位收回,避免留一条空白。 */
.plat-macos .win-titlebar { padding-left: 84px; }
.plat-macos .win-titlebar.is-native-fs { padding-left: 14px; }
.plat-android .win-main { background: var(--p-bg); overflow: hidden; }
.plat-android .win-main,
.plat-ios .win-main { background: var(--p-bg); overflow: hidden; }
.win-page-in { animation: kf-page-in .26s cubic-bezier(.2,0,0,1) both; }
.win-page-out { animation: kf-page-out .2s ease-in both; }
@@ -483,13 +485,28 @@ input[type="range"].hg-range::-webkit-slider-thumb { -webkit-appearance: none; w
.player-surface .player-root,
.player-root { background: #15181d; }
/* —— 安卓沉浸全屏:横屏视频把舞台旋转 90°(不依赖系统旋转) —— */
/* —— 移动端沉浸全屏:固定铺满全屏视口,脱离外层滚动容器 scrollTop 影响 —— */
.fs-immersive {
position: fixed;
inset: 0;
width: 100vw; height: 100vh;
width: 100dvw; height: 100dvh;
z-index: 45;
background: #000;
overflow: hidden;
}
/* —— 移动端沉浸全屏(系统仍处于竖屏时的 CSS 90° 旋转兜底) —— */
.fs-landscape {
position: absolute;
position: fixed;
top: 50%; left: 50%; right: auto; bottom: auto;
width: 100vh; height: 100vw;
width: 100dvh; height: 100dvw;
transform: translate(-50%, -50%) rotate(90deg);
transform-origin: center center;
z-index: 45;
background: #000;
overflow: hidden;
}
.desktop-dock-panel {