9 changed files with 320 additions and 402 deletions
-189
View File
@@ -1,189 +0,0 @@
name: Build iOS IPA
on:
workflow_dispatch:
push:
branches: ["main"]
tags: ["v*"]
jobs:
ios:
name: iOS Build (IPA)
runs-on: macos-latest
permissions:
contents: write
env:
APPLE_DEVELOPMENT_TEAM: "ABCDE12345"
steps:
- uses: actions/checkout@v4
- name: 对齐版本号
id: ver
shell: bash
run: |
if [[ "$GITHUB_REF" == refs/tags/v* ]]; then
V="${GITHUB_REF_NAME#v}"
else
V="$(node -p "require('./src-tauri/tauri.conf.json').version")"
fi
echo "version=$V" >> "$GITHUB_OUTPUT"
node -e "const fs=require('fs');for(const p of ['src-tauri/tauri.conf.json','package.json']){const j=JSON.parse(fs.readFileSync(p));j.version=process.argv[1];fs.writeFileSync(p,JSON.stringify(j,null,2)+'\n')}" "$V"
- uses: pnpm/action-setup@v4
with:
version: 10
- uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
- uses: dtolnay/rust-toolchain@stable
with:
targets: aarch64-apple-ios,aarch64-apple-ios-sim
- uses: swatinem/rust-cache@v2
with:
workspaces: src-tauri -> target
key: ios-build
- name: 安装依赖
run: pnpm install --frozen-lockfile
- name: 初始化 iOS Xcode 工程
run: |
pnpm tauri ios init --ci || pnpm tauri ios init
# 确保 iOS Info.plist(含 ~iphone / ~ipad 变体)支持横竖屏切换及 ATS
for plist in $(find src-tauri/gen/apple -name "Info.plist" 2>/dev/null); do
for key in "UISupportedInterfaceOrientations" "UISupportedInterfaceOrientations~iphone" "UISupportedInterfaceOrientations~ipad"; do
/usr/libexec/PlistBuddy -c "Delete :${key}" "$plist" 2>/dev/null || true
/usr/libexec/PlistBuddy -c "Add :${key} array" "$plist"
/usr/libexec/PlistBuddy -c "Add :${key}:0 string UIInterfaceOrientationPortrait" "$plist"
/usr/libexec/PlistBuddy -c "Add :${key}:1 string UIInterfaceOrientationLandscapeLeft" "$plist"
/usr/libexec/PlistBuddy -c "Add :${key}:2 string UIInterfaceOrientationLandscapeRight" "$plist"
done
/usr/libexec/PlistBuddy -c "Delete :NSAppTransportSecurity" "$plist" 2>/dev/null || true
/usr/libexec/PlistBuddy -c "Add :NSAppTransportSecurity dict" "$plist"
/usr/libexec/PlistBuddy -c "Add :NSAppTransportSecurity:NSAllowsArbitraryLoads bool true" "$plist"
done
env:
APPLE_DEVELOPMENT_TEAM: "ABCDE12345"
- name: 构建 iOS 应用与打包 IPA
shell: bash
env:
APPLE_DEVELOPMENT_TEAM: "ABCDE12345"
run: |
V="${{ steps.ver.outputs.version }}"
mkdir -p artifacts
# 1. 确保前端编译产物就绪
pnpm build
# 2. 执行 Tauri iOS 自动化构建(免证书签名,激活 custom-protocol 确保为生产打包模式)
echo "=== 执行 Tauri iOS 构建 (--no-sign --features custom-protocol) ==="
pnpm tauri ios build --no-sign --ci --features custom-protocol || true
# 3. 检查是否已直接生成 IPA
IPA_PATH=$(find src-tauri/gen/apple -name "*.ipa" 2>/dev/null | head -n 1 || true)
if [ -n "$IPA_PATH" ] && [ -f "$IPA_PATH" ]; then
echo "=== 发现生成的 IPA: $IPA_PATH ==="
cp "$IPA_PATH" "artifacts/HGhub_${V}_ios.ipa"
fi
# 4. 若未直接生成 IPA,寻找 .app 或通过 xcodebuild 归档编译
if [ ! -s "artifacts/HGhub_${V}_ios.ipa" ]; then
APP_PATH=$(find src-tauri/gen/apple -name "*.app" -type d 2>/dev/null | head -n 1 || true)
if [ -z "$APP_PATH" ]; then
echo "=== 未在 gen/apple 找到 .app,调用 xcodebuild 编译 Release ==="
PROJECT_PATH=$(find src-tauri/gen/apple -name "*.xcodeproj" 2>/dev/null | head -n 1 || true)
SCHEME_NAME=$(xcodebuild -list -project "$PROJECT_PATH" 2>/dev/null | awk '/Schemes:/{flag=1;next} flag && NF{print $1;exit}' || true)
if [ -z "$SCHEME_NAME" ]; then
SCHEME_NAME="huangguo-client_iOS"
fi
echo "项目: $PROJECT_PATH, Scheme: $SCHEME_NAME"
xcodebuild build \
-project "$PROJECT_PATH" \
-scheme "$SCHEME_NAME" \
-configuration Release \
-destination "generic/platform=iOS" \
CODE_SIGNING_ALLOWED=NO \
CODE_SIGNING_REQUIRED=NO \
CODE_SIGN_IDENTITY="" \
-derivedDataPath build_output
APP_PATH=$(find build_output -name "*.app" -type d 2>/dev/null | head -n 1 || true)
fi
if [ -n "$APP_PATH" ] && [ -d "$APP_PATH" ]; then
echo "=== 打包 APP 目录: $APP_PATH 为 IPA ==="
rm -rf Payload
mkdir -p Payload
cp -r "$APP_PATH" Payload/
zip -qr "artifacts/HGhub_${V}_ios.ipa" Payload
rm -rf Payload
fi
fi
if [ -s "artifacts/HGhub_${V}_ios.ipa" ]; then
echo "=== IPA 打包成功 ==="
ls -lh artifacts/
# 5. 校验 IPA 是否为真正的生产包(验证不含 localhost:1420 且静态资源嵌入)
echo "=== 校验生产包模式 ==="
mkdir -p /tmp/verify_ipa
unzip -q -o "artifacts/HGhub_${V}_ios.ipa" -d /tmp/verify_ipa
BIN_PATH=$(find /tmp/verify_ipa -type f -name "HGhub" | head -n 1 || true)
if [ -n "$BIN_PATH" ]; then
if strings "$BIN_PATH" | grep -q "localhost:1420"; then
echo "::error::警告:构建产物依然包含 localhost:1420,处于 dev 模式!"
exit 1
fi
echo "=== 生产模式校验通过:未包含 devUrl,静态前端资源已内置 ==="
fi
rm -rf /tmp/verify_ipa
else
echo "::error::未能生成有效的 iOS IPA 文件"
exit 1
fi
- name: 上传 IPA 产物
uses: actions/upload-artifact@v4
with:
name: HGhub-iOS-IPA
path: artifacts/*
if-no-files-found: error
- name: 发布 iOS GitHub Release
shell: bash
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
V="${{ steps.ver.outputs.version }}"
TAG="v${V}-ios"
NOTES="## HGhub iOS 增强版 (v${V})
### ✨ 核心特性
- **沉浸式竖屏刷剧流**:支持首页无限推荐流、题材分类、三大榜单(热门/推荐/潜力)、搜索、吃瓜社区图文与视频帖、选集与历史续播。
- **原生横竖屏智能切换**:横屏视频支持一键「横屏全屏」(调用 iOS 原生屏幕方向旋转),支持手机物理横置自动全屏、竖回自动退出,独立固定舞台层渲染不跑偏、不闪封面。
- **丰富触控手势**:
- **双指自由缩放(1x~4x)与平移**:竖屏观看横屏视频可自由缩放,并提供「放大铺满 / 完整适应 / 还原缩放」胶囊按钮;
- **单击清屏 / 双击暂停**:单击屏幕隐藏所有控件与遮罩纯享画面,双击屏幕暂停/播放;
- **长按 2.0x 倍速 + 上滑锁定**:长按画面开启 2.0x 倍速,上滑即可锁定倍速;
- **左右横滑预览定位**:任意位置横滑精准跳转进度。
- **HLS 播放稳定性加固**:内置 AES Key 与分片内存缓存、拖动进度条防卡死自愈重连、全屏旋转过渡期持续保活与片尾自动连播下一集。
- **多线路与镜像测速**:内置固定主备线路 + 自动抓取最新镜像域名 + 一键延迟测速切换。
### 📲 安装说明(免证书生产包 \`.ipa\`)
1. **TrollStore(巨魔商店)**:下载 \`HGhub_${V}_ios.ipa\` 后直接导入巨魔永久安装。
2. **AltStore / SideStore / Sideloadly**:使用个人 Apple ID 自签安装。
3. **轻松签(ESign)/ 牛蛙助手 / Feather / 全能签**:导入证书签名后直接安装。"
if gh release view "$TAG" >/dev/null 2>&1; then
gh release upload "$TAG" artifacts/*.ipa --clobber
gh release edit "$TAG" --title "HGhub v${V} iOS 正式版" --notes "$NOTES" --prerelease=false --latest
else
gh release create "$TAG" artifacts/*.ipa \
--title "HGhub v${V} iOS 正式版" \
--notes "$NOTES" \
--latest
fi
-147
View File
@@ -1,147 +0,0 @@
name: Build macOS Release
on:
workflow_dispatch:
push:
branches: ["main"]
jobs:
macos:
name: macOS (${{ matrix.name }})
runs-on: macos-latest
strategy:
fail-fast: false
matrix:
include:
- target: aarch64-apple-darwin
name: Apple Silicon (arm64)
arch: arm64
- target: x86_64-apple-darwin
name: Intel (x64)
arch: x64
- target: universal-apple-darwin
name: Universal (通用版)
arch: universal
steps:
- uses: actions/checkout@v4
- name: 对齐版本号
id: ver
shell: bash
run: |
if [[ "$GITHUB_REF" == refs/tags/v* ]]; then
V="${GITHUB_REF_NAME#v}"
else
V="$(node -p "require('./src-tauri/tauri.conf.json').version")"
fi
echo "version=$V" >> "$GITHUB_OUTPUT"
node -e "const fs=require('fs');for(const p of ['src-tauri/tauri.conf.json','package.json']){const j=JSON.parse(fs.readFileSync(p));j.version=process.argv[1];fs.writeFileSync(p,JSON.stringify(j,null,2)+'\n')}" "$V"
- uses: pnpm/action-setup@v4
with:
version: 10
- uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
- uses: dtolnay/rust-toolchain@stable
with:
targets: aarch64-apple-darwin,x86_64-apple-darwin
- uses: swatinem/rust-cache@v2
with:
workspaces: src-tauri -> target
key: macos-${{ matrix.target }}
- name: 安装前端依赖
run: pnpm install --frozen-lockfile
- name: 构建 macOS 应用 (DMG + APP)
run: |
pnpm tauri build --config src-tauri/tauri.macos.conf.json --target ${{ matrix.target }}
- name: 整理构建产物
shell: bash
run: |
V="${{ steps.ver.outputs.version }}"
mkdir -p artifacts
# 收集 dmg 安装包
found_dmg=0
for f in $(find src-tauri/target -name '*.dmg'); do
echo "发现 DMG: $f"
cp "$f" "artifacts/HGhub_${V}_${{ matrix.arch }}.dmg"
found_dmg=1
done
# 打包 .app 绿色压缩包(便于不需要 DMG 安装的用户直接拖拽)
for app in $(find src-tauri/target -name 'HGhub.app' -type d); do
echo "发现 APP: $app"
tar -czf "artifacts/HGhub_${V}_${{ matrix.arch }}.app.tar.gz" -C "$(dirname "$app")" "HGhub.app"
done
ls -lh artifacts/
if [ "$found_dmg" -eq 0 ]; then
echo "::error::未找到 DMG 构建产物"
exit 1
fi
- name: 上传构建产物
uses: actions/upload-artifact@v4
with:
name: HGhub-macOS-${{ matrix.arch }}
path: artifacts/*
if-no-files-found: error
publish-release:
name: 发布 GitHub Release
needs: [macos]
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- name: 下载所有 macOS 产物
uses: actions/download-artifact@v4
with:
path: artifacts
merge-multiple: true
- name: 查看产物列表
run: ls -lh artifacts
- name: 获取版本号
id: ver
run: |
V="$(node -p "require('./src-tauri/tauri.conf.json').version")"
echo "version=$V" >> "$GITHUB_OUTPUT"
- name: 发布 Release
uses: softprops/action-gh-release@v2
with:
tag_name: v${{ steps.ver.outputs.version }}-macos
name: HGhub v${{ steps.ver.outputs.version }} macOS 专属版
body: |
## HGhub macOS 编译发布版 (v${{ steps.ver.outputs.version }})
本项目为 [Minireel/HGhub](https://github.com/Minireel/HGhub) 官方源码针对 macOS 平台的编译产物。
原项目已在 PR #1 完成 macOS 适配支持,但官方尚未在 Release 页面发布 Mac 版产物。
### 下载说明
- **Apple Silicon (M1/M2/M3/M4 系列芯片)**: 推荐下载 `HGhub_${{ steps.ver.outputs.version }}_arm64.dmg`
- **Intel 芯片**: 推荐下载 `HGhub_${{ steps.ver.outputs.version }}_x64.dmg`
- **通用双架构版 (全机型支持)**: 推荐下载 `HGhub_${{ steps.ver.outputs.version }}_universal.dmg`
### macOS 首次打开说明(绕过未签名提示)
由于开源个人构建未购买苹果开发者企业证书签名与公证,首次打开若提示“已损坏”或“无法打开”,请在「终端」中执行以下命令清除隔离属性:
```bash
sudo xattr -rd com.apple.quarantine /Applications/HGhub.app
```
files: artifacts/*
fail_on_unmatched_files: true
draft: false
prerelease: false
-2
View File
@@ -3,8 +3,6 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="theme-color" content="#1a1a1a" />
<title>HGhub · 黄果短剧</title>
<script>
-4
View File
@@ -11,10 +11,6 @@ rust-version = "1.90"
name = "huangguo_client_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[features]
default = ["custom-protocol"]
custom-protocol = ["tauri/custom-protocol"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
-3
View File
@@ -43,9 +43,6 @@
],
"android": {
"minSdkVersion": 24
},
"iOS": {
"developmentTeam": "ABCDE12345"
}
}
}
-3
View File
@@ -1,8 +1,5 @@
{
"$schema": "https://schema.tauri.app/config/2",
"build": {
"devUrl": null
},
"bundle": {
"iOS": {
"minimumSystemVersion": "15.0"
+5 -2
View File
@@ -9,9 +9,12 @@ import type {
export const APP_VERSION = __APP_VERSION__;
const ua = navigator.userAgent;
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 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);
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";
+46 -8
View File
@@ -1,6 +1,6 @@
import React, { useEffect, useRef, useState } from "react";
import Hls from "hls.js";
import { fmtTime, playlist } from "../api";
import { fmtTime, platform, playlist } from "../api";
import { mediaResource, observeHls, usePlayerDiagnostics } from "../playbackDiagnostics";
import { usePlaybackActivity } from "../usePlaybackActivity";
import { useSeekInput } from "../useSeekInput";
@@ -30,6 +30,7 @@ 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);
@@ -46,6 +47,10 @@ 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);
@@ -56,6 +61,8 @@ 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; }
@@ -66,16 +73,22 @@ export default function Player({
interstitialsController: undefined,
contentSteeringController: undefined,
enableInterstitialPlayback: false,
enableWorker: true,
enableWorker: platform !== "ios",
// Keep the same macOS seek workaround as the shared player.
preferManagedMediaSource: false,
autoStartLoad: false,
lowLatencyMode: false,
maxBufferLength: 24,
maxBufferLength: 30,
maxMaxBufferLength: 60,
backBufferLength: 30,
maxBufferHole: 0.5,
nudgeOffset: 0.25,
nudgeMaxRetry: 6,
manifestLoadingTimeOut: 20000,
manifestLoadingMaxRetry: 3,
fragLoadingMaxRetry: 4,
manifestLoadingMaxRetry: 4,
fragLoadingTimeOut: 25000,
fragLoadingMaxRetry: 6,
fragLoadingRetryDelay: 400,
});
hlsRef.current = hls;
observeHls(hls, trace);
@@ -85,12 +98,34 @@ 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) return;
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;
}
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; }
@@ -151,6 +186,8 @@ 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"
@@ -158,7 +195,8 @@ 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); onPlaying?.(); } }}
onPlaying={() => { if (activity.isActive()) { setWaiting(false); setErrMsg(""); onPlaying?.(); } }}
onSeeked={() => setWaiting(false)}
onTimeUpdate={(e) => setTime((e.target as HTMLVideoElement).currentTime)}
onLoadedMetadata={(e) => setDuration((e.target as HTMLVideoElement).duration || 0)}
onEnded={() => { if (activity.isActive()) onEnded?.(); }}
+269 -44
View File
@@ -1,6 +1,6 @@
import { useEffect, useImperativeHandle, useRef, forwardRef, useState } from "react";
import React, { useEffect, useImperativeHandle, useRef, forwardRef, useState } from "react";
import Hls from "hls.js";
import { isLocalMedia, playlist } from "../api";
import { isLocalMedia, platform, playlist } from "../api";
import { mediaResource, observeHls, usePlayerDiagnostics } from "../playbackDiagnostics";
import { usePlaybackActivity } from "../usePlaybackActivity";
@@ -9,11 +9,12 @@ export type VideoHandle = {
play: () => void;
pause: () => void;
toggle: () => void;
seek: (t: number, source?: string) => void;
seek: (t: number, sourceOrAutoResume?: string | boolean) => 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 = {
@@ -25,6 +26,11 @@ type Props = {
muted?: boolean;
loop?: boolean;
fit?: "contain" | "cover";
/** 缩放倍率与平移偏移(用于移动端竖屏下双指缩放横屏视频) */
scale?: number;
panX?: number;
panY?: number;
isGesturing?: boolean;
/** 换源后重新套用,避免切集时音量/倍速被浏览器重置 */
volume?: number;
rate?: number;
@@ -42,16 +48,75 @@ 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", volume = 1, rate = 1,
{ 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,
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"),
@@ -62,29 +127,47 @@ const VideoSurface = forwardRef<VideoHandle, Props>(function VideoSurface(
trace("toggle.request");
if (v.paused) activity.play("toggle"); else activity.pause("toggle");
},
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; }
}
},
seek: (t: number, sourceOrAutoResume: string | boolean = "handle") => safeSeek(t, sourceOrAutoResume),
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 后浏览器会把它们重置成默认值 */
@@ -103,15 +186,27 @@ const VideoSurface = forwardRef<VideoHandle, Props>(function VideoSurface(
interstitialsController: undefined,
contentSteeringController: undefined,
enableInterstitialPlayback: false,
enableWorker: true,
// iOS WKWebView 下 WebWorker 跨自定义协议 hg:// 高频中断易死锁,关闭 Worker 走主线程加载更稳
enableWorker: !isIos,
// 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: 3,
fragLoadingMaxRetry: 4,
manifestLoadingMaxRetry: 4,
levelLoadingTimeOut: 20000,
levelLoadingMaxRetry: 4,
fragLoadingTimeOut: 25000,
fragLoadingMaxRetry: 6,
fragLoadingRetryDelay: 400,
startFragPrefetch: true,
});
hlsRef.current = hls;
observeHls(hls, trace);
@@ -121,13 +216,63 @@ 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) return;
onError?.(`${data.type}/${data.details}`);
// 非致命卡顿错误(常见于拖动进度条后缓冲空洞):主动触发加载与微调跳帧
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 (!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; }
// 致命错误:优先自动重连/恢复解码器,最多静默恢复 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;
}
});
} else {
video.src = url;
@@ -136,6 +281,10 @@ 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
@@ -151,30 +300,106 @@ 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 (
<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?.(); }}
/>
<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>
);
});