hookehuyr

fix(video-player): 修复视频播放器条件渲染和清晰度插件问题

修复 v-show 改为 v-if 避免视频播放器隐藏时继续消耗资源
改进视频类型推断逻辑,支持从 videoId 扩展名识别类型
优化清晰度插件初始化逻辑,确保在 m3u8 源下正确工作
增强原生 HLS 播放能力检测,避免不必要的 VHS 覆盖
......@@ -40,6 +40,7 @@ const createPlayerStub = ({ bandwidthBitsPerSecond, bandwidthOn = 'vhs' } = {})
},
tech: () => techObject,
hlsQualitySelector: vi.fn(),
qualityLevels: vi.fn(() => ({ on: vi.fn() })),
error: () => null,
load: vi.fn(),
pause: vi.fn(),
......@@ -158,3 +159,111 @@ describe('useVideoPlayer HLS 下载速度调试', () => {
expect(hlsSpeedDebugText.value).toContain('tech:')
})
})
describe('useVideoPlayer 清晰度插件兼容', () => {
let console_warn_spy
beforeEach(() => {
console_warn_spy = vi.spyOn(console, 'warn').mockImplementation(() => {})
})
afterEach(() => {
console_warn_spy?.mockRestore?.()
})
it('非 m3u8 源不会初始化清晰度插件', () => {
const props = {
options: {},
videoUrl: 'https://example.com/test.mp4',
videoId: 'v1',
autoplay: false,
debug: false,
useNativeOnIos: true
}
const emit = vi.fn()
const videoRef = ref(null)
const nativeVideoRef = ref(null)
const { handleVideoJsMounted } = useVideoPlayer(
props,
emit,
videoRef,
nativeVideoRef
)
const { player } = createPlayerStub({ bandwidthBitsPerSecond: 8 * 1024 * 1024, bandwidthOn: 'vhs' })
handleVideoJsMounted({ state: {}, player })
expect(player.hlsQualitySelector).not.toHaveBeenCalled()
})
it('m3u8 + vhs tech 下会别名 hls 并初始化清晰度插件', () => {
const props = {
options: {},
videoUrl: 'https://example.com/test.m3u8',
videoId: 'v1',
autoplay: false,
debug: false,
useNativeOnIos: true
}
const emit = vi.fn()
const videoRef = ref(null)
const nativeVideoRef = ref(null)
const { handleVideoJsMounted } = useVideoPlayer(
props,
emit,
videoRef,
nativeVideoRef
)
const { player } = createPlayerStub({ bandwidthBitsPerSecond: 8 * 1024 * 1024, bandwidthOn: 'vhs' })
expect(player.tech().hls).toBeUndefined()
expect(player.tech().vhs).toBeTruthy()
handleVideoJsMounted({ state: {}, player })
expect(player.tech().hls).toBe(player.tech().vhs)
expect(player.hlsQualitySelector).toHaveBeenCalledTimes(1)
})
})
describe('useVideoPlayer blob URL 兜底类型识别', () => {
let console_warn_spy
beforeEach(() => {
console_warn_spy = vi.spyOn(console, 'warn').mockImplementation(() => {})
})
afterEach(() => {
console_warn_spy?.mockRestore?.()
})
it('blob: URL 时可从 videoId 的扩展名推断 type', () => {
const props = {
options: {},
videoUrl: 'blob:http://localhost:8206/41e9655f-37ee-4e48-bfd2-29104d64d7b3',
videoId: '368_1726304830.mp4',
autoplay: false,
debug: false,
useNativeOnIos: true
}
const emit = vi.fn()
const videoRef = ref(null)
const nativeVideoRef = ref(null)
const { videoOptions } = useVideoPlayer(
props,
emit,
videoRef,
nativeVideoRef
)
expect(videoOptions.value.sources[0].type).toBe('video/mp4')
})
})
......
......@@ -100,17 +100,45 @@ export function useVideoPlayer(props, emit, videoRef, nativeVideoRef) {
});
// 4. 视频类型判断
const getUrlPathExtension = (url) => {
const urlText = (url || "").trim();
if (!urlText) return "";
try {
const u = typeof window !== "undefined" ? new URL(urlText, window.location?.href) : null;
const pathname = u ? u.pathname : urlText;
const lastDot = pathname.lastIndexOf(".");
if (lastDot < 0) return "";
return pathname.slice(lastDot + 1).toLowerCase();
} catch (e) {
const withoutQuery = urlText.split("?")[0].split("#")[0];
const lastDot = withoutQuery.lastIndexOf(".");
if (lastDot < 0) return "";
return withoutQuery.slice(lastDot + 1).toLowerCase();
}
};
const getVideoMimeType = (url) => {
const urlText = (url || "").toLowerCase();
if (urlText.includes(".m3u8")) return "application/x-mpegURL";
if (urlText.includes(".mp4")) return "video/mp4";
if (urlText.includes(".mov")) return "video/quicktime";
const ext = getUrlPathExtension(urlText) || getUrlPathExtension(props?.videoId);
if (ext === "m3u8") return "application/x-mpegURL";
if (ext === "mp4" || ext === "m4v") return "video/mp4";
if (ext === "mov") return "video/quicktime";
if (ext === "webm") return "video/webm";
if (ext === "ogv" || ext === "ogg") return "video/ogg";
return "";
};
// 5. 视频源配置
const videoSources = computed(() => {
const type = getVideoMimeType(videoUrlValue.value);
const inferredType = getVideoMimeType(videoUrlValue.value);
const probeType = (probeInfo.value.content_type || "").toLowerCase();
const type = inferredType
|| (probeType.includes("application/vnd.apple.mpegurl") || probeType.includes("application/x-mpegurl") ? "application/x-mpegURL" : "")
|| (probeType.includes("video/mp4") ? "video/mp4" : "")
|| (probeType.includes("video/quicktime") ? "video/quicktime" : "")
|| (probeType.includes("video/webm") ? "video/webm" : "")
|| (probeType.includes("video/ogg") ? "video/ogg" : "");
if (type) {
return [{ src: videoUrlValue.value, type }];
}
......@@ -143,69 +171,87 @@ export function useVideoPlayer(props, emit, videoRef, nativeVideoRef) {
return "";
};
const canProbeVideoUrl = (url) => {
const urlText = (url || "").trim();
if (!urlText) return false;
if (typeof window === "undefined" || typeof window.location === "undefined") return false;
if (typeof fetch === "undefined") return false;
if (/^(blob:|data:)/i.test(urlText)) return false;
try {
const u = new URL(urlText, window.location.href);
if (!u.protocol || !u.origin) return false;
if (u.origin !== window.location.origin) return false;
return true;
} catch (e) {
return false;
}
};
// 资源探测
const probeVideo = async () => {
const url = videoUrlValue.value;
if (!url || typeof fetch === "undefined") return;
if (!canProbeVideoUrl(url)) return;
if (probeLoading.value) return;
probeLoading.value = true;
const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
const timeoutId = setTimeout(() => controller?.abort?.(), 8000);
let controller2 = null;
let timeoutId2 = null;
try {
const headRes = await fetch(url, {
method: "HEAD",
mode: "cors",
cache: "no-store",
signal: controller?.signal,
});
try {
const headRes = await fetch(url, {
method: "HEAD",
mode: "cors",
cache: "no-store",
signal: controller?.signal,
});
const contentLength = headRes.headers.get("content-length");
probeInfo.value = {
ok: headRes.ok,
status: headRes.status,
content_type: headRes.headers.get("content-type") || "",
content_length: contentLength ? Number(contentLength) || null : null,
accept_ranges: headRes.headers.get("accept-ranges") || "",
};
const contentLength = headRes.headers.get("content-length");
probeInfo.value = {
ok: headRes.ok,
status: headRes.status,
content_type: headRes.headers.get("content-type") || "",
content_length: contentLength ? Number(contentLength) || null : null,
accept_ranges: headRes.headers.get("accept-ranges") || "",
};
if (headRes.ok && probeInfo.value.content_length) return;
} catch (e) {
// 忽略 HEAD 请求失败
}
if (headRes.ok && probeInfo.value.content_length) return;
} catch (e) {
// 忽略 HEAD 请求失败
controller2 = typeof AbortController !== "undefined" ? new AbortController() : null;
timeoutId2 = setTimeout(() => controller2?.abort?.(), 8000);
try {
const rangeRes = await fetch(url, {
method: "GET",
mode: "cors",
cache: "no-store",
headers: { Range: "bytes=0-1" },
signal: controller2?.signal,
});
const contentRange = rangeRes.headers.get("content-range") || "";
const match = contentRange.match(/\/(\d+)\s*$/);
const total = match ? Number(match[1]) || null : null;
const contentLength = rangeRes.headers.get("content-length");
probeInfo.value = {
ok: rangeRes.ok,
status: rangeRes.status,
content_type: rangeRes.headers.get("content-type") || "",
content_length: total || (contentLength ? Number(contentLength) || null : null),
accept_ranges: rangeRes.headers.get("accept-ranges") || "",
};
} catch (e) {
// 忽略错误
}
} finally {
if (timeoutId2) clearTimeout(timeoutId2);
clearTimeout(timeoutId);
probeLoading.value = false;
}
// 如果 HEAD 失败,尝试 GET Range 0-1
const controller2 = typeof AbortController !== "undefined" ? new AbortController() : null;
const timeoutId2 = setTimeout(() => controller2?.abort?.(), 8000);
try {
const rangeRes = await fetch(url, {
method: "GET",
mode: "cors",
cache: "no-store",
headers: { Range: "bytes=0-1" },
signal: controller2?.signal,
});
const contentRange = rangeRes.headers.get("content-range") || "";
const match = contentRange.match(/\/(\d+)\s*$/);
const total = match ? Number(match[1]) || null : null;
const contentLength = rangeRes.headers.get("content-length");
probeInfo.value = {
ok: rangeRes.ok,
status: rangeRes.status,
content_type: rangeRes.headers.get("content-type") || "",
content_length: total || (contentLength ? Number(contentLength) || null : null),
accept_ranges: rangeRes.headers.get("accept-ranges") || "",
};
} catch (e) {
// 忽略错误
} finally {
clearTimeout(timeoutId2);
}
};
// 7. 错误处理逻辑
......@@ -468,6 +514,21 @@ export function useVideoPlayer(props, emit, videoRef, nativeVideoRef) {
};
// 5. Video.js 播放器逻辑 (PC/Android)
const canPlayHlsNatively = () => {
if (typeof document === "undefined") return false;
const el = document.createElement("video");
if (!el || typeof el.canPlayType !== "function") return false;
const r1 = el.canPlayType("application/vnd.apple.mpegurl");
const r2 = el.canPlayType("application/x-mpegURL");
return r1 === "probably" || r1 === "maybe" || r2 === "probably" || r2 === "maybe";
};
const shouldOverrideNativeHls = computed(() => {
if (!isM3U8.value) return false;
if (videojs.browser.IS_SAFARI) return false;
return !canPlayHlsNatively();
});
const videoOptions = computed(() => ({
controls: true,
preload: "metadata",
......@@ -478,7 +539,7 @@ export function useVideoPlayer(props, emit, videoRef, nativeVideoRef) {
sources: videoSources.value,
html5: {
vhs: {
overrideNative: !videojs.browser.IS_SAFARI, // 非 Safari 下使用 VHS 解析 HLS
overrideNative: shouldOverrideNativeHls.value,
},
nativeVideoTracks: false,
nativeAudioTracks: false,
......@@ -513,12 +574,42 @@ export function useVideoPlayer(props, emit, videoRef, nativeVideoRef) {
if (player.value) {
setHlsDebug('mounted');
// 初始化多码率切换插件 (七牛云多码率支持)
if (player.value.hlsQualitySelector) {
player.value.hlsQualitySelector({
displayCurrentQuality: true,
});
}
const quality_selector_inited = { value: false };
const setupQualitySelector = () => {
if (quality_selector_inited.value) return;
if (!isM3U8.value) return;
const p = player.value;
if (!p || (typeof p.isDisposed === "function" && p.isDisposed())) return;
if (typeof p.hlsQualitySelector !== "function") return;
if (typeof p.qualityLevels !== "function") return;
let tech = null;
try {
tech = typeof p.tech === "function" ? p.tech({ IWillNotUseThisInPlugins: true }) : null;
} catch (e) {
tech = null;
}
if (!tech) return;
if (!tech.hls && tech.vhs) {
try {
tech.hls = tech.vhs;
} catch (e) {
void e;
}
}
if (!tech.hls) return;
try {
p.hlsQualitySelector({
displayCurrentQuality: true,
});
quality_selector_inited.value = true;
} catch (e) {
void e;
}
};
setupQualitySelector();
player.value.on('error', () => {
const err = player.value.error();
......@@ -527,11 +618,13 @@ export function useVideoPlayer(props, emit, videoRef, nativeVideoRef) {
player.value.on('loadstart', () => {
showErrorOverlay.value = false;
setupQualitySelector();
});
player.value.on('canplay', () => {
showErrorOverlay.value = false;
retryCount.value = 0;
setupQualitySelector();
});
player.value.on('play', () => {
......
......@@ -158,7 +158,7 @@
</div>
</div>
<!-- 视频播放器 -->
<VideoPlayer v-show="isVideoPlaying" ref="videoPlayerRef" :video-url="videoUrl"
<VideoPlayer v-if="isVideoPlaying" ref="videoPlayerRef" :video-url="videoUrl"
:video-id="videoTitle" :use-native-on-ios="false" :autoplay="false" class="w-full h-full" @play="handleVideoPlay"
@pause="handleVideoPause" />
</div>
......