From b99b3e57180d29815d3d1b97e3da0829d74c10c8 Mon Sep 17 00:00:00 2001 From: Your Name Date: Sat, 31 Jan 2026 20:54:25 +0800 Subject: [PATCH] perf: optimize video playback and encoding for better web streaming experience Co-authored-by: Cursor --- app/api/video/upload/route.ts | 29 +++++++++++++++++++--- components/top-navbar.tsx | 46 +++++++++++++++++++++++++++++------ 2 files changed, 65 insertions(+), 10 deletions(-) diff --git a/app/api/video/upload/route.ts b/app/api/video/upload/route.ts index 1099a32..c751a6a 100644 --- a/app/api/video/upload/route.ts +++ b/app/api/video/upload/route.ts @@ -78,21 +78,44 @@ async function compressVideo( const videoInfo = await getVideoInfo(inputPath); const originalSize = (await readFile(inputPath)).length; - // 构建 FFmpeg 命令 + // 构建 FFmpeg 命令 - 针对 Web 流式播放深度优化 // 使用 H.264 (libx264) 编码器 + AAC 音频 - // -movflags +faststart 让视频可以边下载边播放 + // + // 关键优化参数说明: + // -movflags +faststart: 将 moov atom 移到文件开头,支持边下载边播放 + // -profile:v high: 使用 High Profile,更好的压缩率和兼容性 + // -level 4.1: 兼容大多数设备的 Level + // -pix_fmt yuv420p: 确保最广泛的浏览器兼容性 + // -tune film/animation: 根据内容优化(这里用 film 作为通用选择) + // -g 48: 关键帧间隔,约每2秒一个关键帧,优化 seek 体验 + // -keyint_min 24: 最小关键帧间隔 + // -sc_threshold 0: 禁用场景切换检测,保持稳定的关键帧间隔 + // -bf 2: B帧数量,提高压缩率 + // -b_strategy 2: B帧策略,动态选择 + let scaleFilter = ""; if (videoInfo.width > targetWidth) { - scaleFilter = `-vf "scale=${targetWidth}:-2"`; + // 使用 lanczos 缩放算法,质量最好 + scaleFilter = `-vf "scale=${targetWidth}:-2:flags=lanczos"`; } const ffmpegCmd = `ffmpeg -i "${inputPath}" \ -c:v libx264 \ -preset ${preset} \ -crf ${crf} \ + -profile:v high \ + -level 4.1 \ + -pix_fmt yuv420p \ + -g 48 \ + -keyint_min 24 \ + -sc_threshold 0 \ + -bf 2 \ + -b_strategy 2 \ ${scaleFilter} \ -c:a aac \ -b:a ${audioBitrate} \ + -ar 44100 \ + -ac 2 \ -movflags +faststart \ -y \ "${outputPath}"`; diff --git a/components/top-navbar.tsx b/components/top-navbar.tsx index 0e95217..ecbe41f 100644 --- a/components/top-navbar.tsx +++ b/components/top-navbar.tsx @@ -480,28 +480,60 @@ export function TopNavbar({ {/* 视频播放器 */}
{currentTutorialVideo.videoUrl.includes('youtube.com') || currentTutorialVideo.videoUrl.includes('youtu.be') ? ( - // YouTube 嵌入 + // YouTube 嵌入 - 启用自动播放和性能优化