diff --git a/public/articles/article.css b/public/articles/article.css new file mode 100644 index 0000000..202842b --- /dev/null +++ b/public/articles/article.css @@ -0,0 +1 @@ +:root{color-scheme:dark;--bg:#080b0f;--panel:#11161d;--text:#edf5f3;--muted:#9dacaa;--line:#27323a;--accent:#51e6c4;font-family:Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;background:var(--bg);color:var(--text);line-height:1.78}a{color:inherit}img{max-width:100%;display:block}.site-header{position:sticky;top:0;z-index:20;border-bottom:1px solid #ffffff14;background:#080b0fd9;backdrop-filter:blur(18px)}.nav{max-width:1180px;margin:auto;height:64px;padding:0 24px;display:flex;align-items:center;justify-content:space-between}.brand{display:flex;align-items:center;gap:10px;text-decoration:none;font-weight:750;letter-spacing:-.02em}.brand-mark{width:30px;height:30px;border-radius:9px;display:grid;place-items:center;background:linear-gradient(135deg,var(--accent),#2998ff);color:#07100e;font-size:14px}.nav-links{display:flex;gap:20px;color:var(--muted);font-size:14px}.nav-links a{text-decoration:none}.nav-links a:hover{color:var(--text)}.hero{max-width:1180px;margin:auto;padding:76px 24px 34px}.eyebrow{margin:0 0 18px;color:var(--accent);font-size:13px;font-weight:800;letter-spacing:.12em;text-transform:uppercase}h1{max-width:940px;margin:0;font-size:clamp(42px,6.5vw,78px);line-height:1.03;letter-spacing:-.055em}.deck{max-width:760px;margin:24px 0 0;color:#b8c6c3;font-size:clamp(18px,2vw,23px);line-height:1.65}.meta{display:flex;flex-wrap:wrap;gap:10px 20px;margin-top:30px;color:var(--muted);font-size:14px}.hero-image{max-width:1180px;margin:34px auto 0;padding:0 24px}.hero-image img{width:100%;aspect-ratio:16/9;object-fit:cover;border:1px solid var(--line);border-radius:24px;box-shadow:0 24px 90px #0007}.layout{max-width:1080px;margin:64px auto 120px;padding:0 24px;display:grid;grid-template-columns:minmax(0,740px) 220px;gap:90px}.article{min-width:0}.article h2{margin:64px 0 18px;font-size:clamp(29px,4vw,40px);line-height:1.2;letter-spacing:-.035em}.article p,.article li{color:#c4cfcd;font-size:17px}.article strong{color:var(--text)}.article a{color:var(--accent);text-underline-offset:3px}.lede{padding-left:20px;border-left:3px solid var(--accent);color:#e5eeec!important;font-size:20px!important}.toc{position:sticky;top:96px;align-self:start}.toc-title{margin:0 0 14px;color:var(--text);font-size:13px;font-weight:800;letter-spacing:.1em;text-transform:uppercase}.toc a{display:block;padding:6px 0;color:var(--muted);font-size:13px;line-height:1.45;text-decoration:none}.toc a:hover{color:var(--accent)}.callout{margin:30px 0;padding:22px 24px;border:1px solid #2d4945;border-radius:16px;background:#30968417}.callout p{margin:0}pre{margin:26px 0;overflow:auto;padding:22px;border:1px solid var(--line);border-radius:15px;background:#0b1016;color:#dce8e6;font:14px/1.65 "SFMono-Regular",Consolas,monospace}code{padding:.13em .35em;border-radius:5px;background:#172029;color:#bdeee3;font-family:"SFMono-Regular",Consolas,monospace;font-size:.88em}pre code{padding:0;background:transparent;color:inherit}.diagram{margin:30px 0;padding:24px;border:1px solid var(--line);border-radius:18px;background:var(--panel)}.flow{display:grid;grid-template-columns:repeat(4,1fr);gap:9px}.flow div{min-height:74px;padding:12px;border:1px solid #30404a;border-radius:11px;background:#151c24;display:grid;place-items:center;text-align:center;color:#d9e5e2;font-size:13px}.metrics{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin:28px 0}.metric{padding:20px;border:1px solid var(--line);border-radius:14px;background:var(--panel)}.metric b{display:block;color:var(--accent);font-size:23px;letter-spacing:-.03em}.metric span{color:var(--muted);font-size:13px}.article-footer{margin-top:72px;padding-top:28px;border-top:1px solid var(--line)}.next-card{display:block;padding:24px;border:1px solid var(--line);border-radius:16px;background:var(--panel);text-decoration:none}.next-card small{color:var(--accent)}.next-card strong{display:block;margin-top:7px;font-size:21px}.index-wrap{max-width:1180px;margin:auto;padding:90px 24px 120px}.index-title{max-width:780px}.article-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:24px;margin-top:54px}.article-card{overflow:hidden;border:1px solid var(--line);border-radius:20px;background:var(--panel);text-decoration:none;transition:.2s}.article-card:hover{transform:translateY(-4px);border-color:#47645d}.article-card img{width:100%;aspect-ratio:16/9;object-fit:cover}.article-card-body{padding:26px}.article-card h2{margin:9px 0 12px;font-size:26px;line-height:1.25;letter-spacing:-.03em}.article-card p{margin:0;color:var(--muted)}.tag{color:var(--accent);font-size:12px;font-weight:800;letter-spacing:.08em;text-transform:uppercase}@media(max-width:820px){.layout{grid-template-columns:1fr;margin-top:44px}.toc{display:none}.article-grid{grid-template-columns:1fr}.flow{grid-template-columns:1fr 1fr}.metrics{grid-template-columns:1fr}}@media(max-width:520px){.hero{padding-top:52px}.nav{padding:0 16px}.hero,.hero-image,.layout,.index-wrap{padding-left:18px;padding-right:18px}.hero-image img{border-radius:15px}.flow{grid-template-columns:1fr}.nav-links a:first-child{display:none}} diff --git a/public/articles/assets/liveportrait-webgpu.webp b/public/articles/assets/liveportrait-webgpu.webp new file mode 100644 index 0000000..a280db7 Binary files /dev/null and b/public/articles/assets/liveportrait-webgpu.webp differ diff --git a/public/articles/assets/local-first-architecture.webp b/public/articles/assets/local-first-architecture.webp new file mode 100644 index 0000000..2c9b29f Binary files /dev/null and b/public/articles/assets/local-first-architecture.webp differ diff --git a/public/articles/index.html b/public/articles/index.html new file mode 100644 index 0000000..4a1bf22 --- /dev/null +++ b/public/articles/index.html @@ -0,0 +1 @@ +技术文章 | Timeline Studio

Engineering Notes · 2026

把浏览器推到创作工具的边界

两篇来自 Timeline Studio 真实代码与验证数据的工程手记:一篇谈完整系统,一篇深入神经网络算子。

浏览器端本地优先 AI 视频编辑器架构概念图
系统架构 · 12 分钟

把 AI 视频编辑器装进浏览器:本地优先架构的六个关键决策

从 Worker、模型缓存到多轨时间线与导出,拆解一个真正可用的浏览器 AI 工作流。

LivePortrait 5D 张量到 WebGPU 的转换概念图
WebGPU 深潜 · 15 分钟

5D GridSample 进不了浏览器之后:LivePortrait 的 WebGPU 移植实战

如何改写 ONNX 图、验证数值等价,并让大型数字人管线在浏览器里完成闭环。

diff --git a/public/articles/liveportrait-webgpu-port/index.html b/public/articles/liveportrait-webgpu-port/index.html new file mode 100644 index 0000000..ae52195 --- /dev/null +++ b/public/articles/liveportrait-webgpu-port/index.html @@ -0,0 +1,19 @@ +LivePortrait 的 WebGPU 移植实战 | Timeline Studio

ONNX · WebGPU · Graph Surgery

5D GridSample 进不了浏览器之后:LivePortrait 的 WebGPU 移植实战

当一个神经网络算子没有浏览器实现时,真正的问题不是“换哪个库”,而是能否把计算改写成 WebGPU 支持的图,并证明它在数值上仍然是同一个模型。

Timeline Studio 工程手记2026-07-17约 15 分钟
5D 张量改写为 4D 采样平面并进入 WebGPU 的概念图

Timeline Studio 的数字人链路使用 JoyVASA 从音频生成动作,再由 LivePortrait 把动作施加到源肖像。模型本身可以导出为 ONNX,真正阻塞浏览器的是生成器中的 rank-5 运算和两个 5D GridSample。

+

01. 先把“数字人”拆成可验证的流水线

这条链路不是单模型调用。它至少包含外观特征提取、源图动作提取、音频驱动、嘴型重定向、关键点拼接、3D 特征形变与 SPADE 图像生成。JoyVASA 的 HuBERT 与 diffusion denoiser 负责把语音转成动作序列,LivePortrait 则负责神经渲染。

Audio
JoyVASA
Motion
Keypoints
3D Warp
LivePortrait
SPADE
RGB Frame

先拆管线的价值是可定位:音频驱动的误差、关键点组合的误差、warping 的误差和最终生成器的误差可以分别测量。否则最终人脸“不对”,你几乎无法知道问题来自哪一段。

+

02. 真正的阻塞点:浏览器没有 5D GridSample

基线 combined generator 使用 opset 20,共 277 个节点,其中有 13 个 rank-5 Conv 与两个 rank-5 GridSample。原仓库附带的 Linux .so 插件无法在浏览器加载,而 ONNX Runtime Web 的 WebGPU 执行提供程序也不能直接执行这两个 5D 采样节点。

输入特征可写成 [N, C, D, H, W],采样网格则在三个空间轴上给出目标坐标。Web 端现成的 GridSample 只处理二维平面。直接删除深度维、把它当批次维或者只取最近切片,都会改变模型含义。

工程原则:当目标运行时缺少算子时,图改写必须保持数学语义。视觉上“差不多”不能替代误差统计。

+

03. 等价改写:4D 采样 + 深度线性插值

三线性采样可以拆成两步:先在深度轴上找到目标坐标两侧的切片 d0 与 d1;分别对这两个 2D 平面执行双线性 GridSample;最后按深度小数部分 α 做线性插值。

d0 = floor(z)
+d1 = min(d0 + 1, D - 1)
+alpha = z - d0
+v0 = GridSample4D(feature[d0], gridXY)
+v1 = GridSample4D(feature[d1], gridXY)
+output = (1 - alpha) * v0 + alpha * v1

实现时需要把深度切片组织成批次,使 WebGPU 能并行执行 4D GridSample,再还原为原来的空间布局。稀疏动作网格还存在经过验证的共享 XY 结构,可以去掉重复的深度采样。改写后的图从 277 个节点增加到 316 个节点,但全部落在 Web 端已支持的算子集合里。

+

04. 数值验证:证明改写前后是同一个函数

验证使用固定输入,将原始 512×512 generator 与 WebGPU 改写图的完整输出逐元素比较。除了最大误差,还同时查看均值和高分位误差,以免少量异常点被平均值掩盖。

7.8976e-6最大绝对误差
1.3853e-7平均绝对误差
1.7881e-699.9% 分位误差

JoyVASA 的 HuBERT 与 diffusion denoiser ONNX 导出也分别对齐 PyTorch,最大绝对误差为 7.75e-6 和 6.44e-6。只有每一段都建立基线,端到端结果才具有可解释性。

+

05. 图能跑以后,运行时问题才刚开始

ONNX Runtime Web 的 WebGPU Worker 必须加载匹配的 Asyncify glue 与 WASM 文件。使用普通或 JSEP glue 会触发 webgpuInit is not a function。多个大型执行提供程序会话还需要串行创建,否则 ORT 可能拒绝并发初始化。

模型包约 906 MB,不适合进入 Git 仓库。项目把它拆成 50 MB 分片,发布到 revision-pinned 的 Hugging Face 模型仓库,并由 Service Worker 缓存。版本固定同时保护了两个假设:图结构不变,运行时代码期待的输入输出也不变。

await createJoyVasaSession();
+releaseTransientGpuResources();
+await createLivePortraitSession();
+appearanceFeature = await extractOnce(sourcePortrait);
+for (const motion of sparseMotions)
+  frames.push(await render(appearanceFeature, motion));
+

06. “跑通”不等于“实时”

项目提供 mixed-FP16 256px 快速预览与 mixed-FP16 512px 质量档。外观特征在帧间保持 GPU 驻留,神经关键帧以 1–2 fps 稀疏渲染,再插值到编码帧率,降低总推理次数。

但必须诚实:在验证设备上,512×512 神经帧仍需要约 25–60 秒。界面展示真实阶段、帧数与耗时,不把稀疏关键帧插值包装成“实时神经渲染”。生成帧会检查非有限值与时间异常,问题帧重试一次,仍失败则沿用上一有效帧。

+

07. 端到端验收必须走完媒体闭环

单个 ONNX session 返回 tensor 只代表算子层通过。真正的验收还包括:模型分片下载、WebGPU 初始化、JoyVASA 50 步动作生成、LivePortrait 渲染、WebM 编码、浏览器播放、媒体库插入和视觉轨替换。

最终验收产物是一段可播放的 3.56 秒 WebM。抽帧能看到张嘴、闭嘴以及头眼运动,完成后浏览器控制台错误为 0。这个闭环很重要,因为编码、Blob 生命周期或轨道替换中的任意错误,都能让“模型成功”变成“用户什么也得不到”。

+

结论:算子移植的核心是可证明

将桌面端模型带进浏览器,最有价值的能力不是写一段兼容代码,而是建立完整证据链:审计图、定位不支持算子、构造等价变换、逐层对齐、统计误差、验证真实运行时,最后走完整个媒体产品闭环。

WebGPU 正在快速扩大浏览器的计算边界。但在这个边界上,最可靠的优化不是更响亮的性能口号,而是每一步都有数字、失败路径和可复现产物。

diff --git a/public/articles/local-first-browser-ai-video-editor/index.html b/public/articles/local-first-browser-ai-video-editor/index.html new file mode 100644 index 0000000..a5a15e4 --- /dev/null +++ b/public/articles/local-first-browser-ai-video-editor/index.html @@ -0,0 +1,19 @@ +把 AI 视频编辑器装进浏览器 | Timeline Studio

Local-first Architecture

把 AI 视频编辑器装进浏览器:本地优先架构的六个关键决策

浏览器 AI 的难点从来不只是“把模型加载进来”。真正的挑战,是把推理、时间线、缓存、渲染与失败恢复组合成一个可信的创作工具。

Timeline Studio 工程手记2026-07-17约 12 分钟
浏览器端本地优先 AI 视频编辑器系统概念图

Timeline Studio 是一个 React 19 + Vite 6 构建的本地优先视频编辑器。语音合成、自动字幕、主体识别、数字人与视频导出都尽可能在用户设备内完成。本文不讨论“浏览器能不能跑 AI”,而是讨论如何让它跑得像一个产品。

+

01. 本地优先不是离线口号,而是一组架构约束

把媒体留在浏览器里,首先解决的是隐私和上传等待:用户选择的原始视频不必先经过服务端。但代价也会立刻转移到客户端——数百 MB 的模型下载、不同设备的内存上限、执行后端差异,以及浏览器编码能力的不一致。

因此“本地优先”的准确含义不是所有资源都内嵌在安装包里,而是:媒体与核心计算默认留在本机,模型按需从固定版本地址获取,重复使用时命中浏览器缓存,任何云端依赖都必须显式可见。

关键判断:把服务器成本移走,并不会让成本消失。它只是变成了下载、存储、内存、GPU 兼容性和更复杂的进度反馈。

+

02. 不追求“一个模型解决一切”

不同任务对模型、量化方式和执行后端的要求不同。Timeline Studio 选择多条专用路径:中文与多语种语音走 Piper/VITS ONNX,英文语音走 Kokoro 82M q8,字幕使用 Whisper small q8,视觉理解使用 YOLOS tiny 与 MODNet,而数字人管线由 JoyVASA 和 LivePortrait 组合完成。

输入媒体
File / Blob
专用 Worker
WASM / WebGPU
统一时间线
Clip Model
Canvas + Audio
导出

这里最重要的选择是延迟加载。用户打开编辑器时,不应该同时下载字幕、数字人、视觉分割和所有语音模型。功能面板被真正使用时才创建对应运行时;同一个会话中则复用热会话,避免重复初始化 ONNX 图。

async function getDetector() {
+  detectorPromise ??= pipeline("object-detection",
+    "Xenova/yolos-tiny", { device: "wasm", dtype: "q8" });
+  return detectorPromise;
+}
+

03. Worker 不只是性能优化,而是产品边界

模型推理、音频解码、逐帧分析和编码任何一项都足以阻塞主线程。如果点击“生成字幕”后整个界面失去响应,那么即使模型最终给出正确结果,产品体验仍然是失败的。

项目把 ASR、视觉分析、数字人、画质增强和人声分离分散到独立 Worker。主线程只负责发送任务、接收结构化进度,并把完成结果转换成时间线资产。对大型 WebGPU 会话还需要串行创建,因为执行提供程序可能拒绝并发初始化。

Worker 同样提供了清晰的取消与错误边界:取消完整视频增强时,原片段保持不变;某个数字人关键帧出现非有限值或时间异常时,系统只重试该帧,并在必要时沿用上一张有效帧,而不是输出损坏纹理。

+

04. 时间线必须是 AI 结果的唯一归宿

很多 AI Demo 的终点是一个下载按钮。编辑器不能这样工作:生成的语音要插入播放头位置,字幕需要与语音绑定,重叠片段要自动进入新轨道,移动和删除时还要保持关联。

Timeline Studio 把 AI 输出统一变成 asset + clip。界面、预览与导出都读取同一份时间模型。生成语音时不会替换上一个结果,而是在播放头位置创建新的 voice clip;对应字幕共享关联 ID,并根据解码后的真实音频时长对齐。

voiceClip = {
+  id, assetId, start, duration, volume,
+  fadeIn, fadeOut, linkedCaptionId, captionSync: true
+};

这个决定也解决了 WYSIWYG:字幕大小、智能裁切、贴纸、滤镜与转场不再有两份互相漂移的状态,而是在指定时间点解析同一个 clip 模型。

+

05. 视频 AI 的输出必须是时间数据

对视频第一帧做一次主体检测,然后把结果应用到全片,是最容易实现、也最容易出错的方案。人物一移动,智能裁切、字幕避让和背景移除都会立刻失真。

项目会以自适应间隔预分析视频,保存带时间戳的 YOLOS 几何与 MODNet 蒙版。预览和导出在当前源时间解析最近的分析记录。长视频扩大采样间隔,以可控的精度损失换取有上限的推理时间与内存。

temporalTrack = [
+  { time: 0.0, box: A, matte: A1 },
+  { time: 0.8, box: B, matte: B1 },
+  { time: 1.6, box: C, matte: C1 }
+];
+

06. 缓存要与版本绑定,导出要接受现实

服务工作线程对模型资源使用 cache-first,对应用壳使用 network-first。模型 URL 固定到不可变 revision,避免缓存中的图与运行时代码悄悄漂移。用户也可以主动清理模型缓存,因为“本地”不等于可以无限占用磁盘。

导出侧同样采用分层策略:浏览器原生支持目标格式时走快速路径;需要 MP4 转码时再加载 FFmpeg WASM;如果转码失败,保留已成功渲染的 WebM,不让用户因最后一步兼容性问题失去全部工作。

+

结论:浏览器 AI 是系统工程

模型准确率只是起点。一个可信的浏览器创作工具还需要明确的计算边界、可取消的 Worker、按需模型生命周期、时间化的视觉分析、统一的时间线语义、版本化缓存与保底导出。

这套架构不会让浏览器变成桌面工作站,但它证明了另一件更有价值的事:只要诚实地处理限制,复杂的 AI 媒体流程已经可以在一个链接里完成,并且不必默认交出用户的原始素材。

diff --git a/public/assets/voice-samples/af_heart.mp3 b/public/assets/voice-samples/af_heart.mp3 new file mode 100644 index 0000000..dbd4d76 Binary files /dev/null and b/public/assets/voice-samples/af_heart.mp3 differ diff --git a/public/assets/voice-samples/am_fenrir.mp3 b/public/assets/voice-samples/am_fenrir.mp3 new file mode 100644 index 0000000..a730cdc Binary files /dev/null and b/public/assets/voice-samples/am_fenrir.mp3 differ diff --git a/public/assets/voice-samples/de_DE-thorsten-medium.mp3 b/public/assets/voice-samples/de_DE-thorsten-medium.mp3 new file mode 100644 index 0000000..cd300c7 Binary files /dev/null and b/public/assets/voice-samples/de_DE-thorsten-medium.mp3 differ diff --git a/public/assets/voice-samples/es_ES-davefx-medium.mp3 b/public/assets/voice-samples/es_ES-davefx-medium.mp3 new file mode 100644 index 0000000..eb9039d Binary files /dev/null and b/public/assets/voice-samples/es_ES-davefx-medium.mp3 differ diff --git a/public/assets/voice-samples/fr_FR-siwis-medium.mp3 b/public/assets/voice-samples/fr_FR-siwis-medium.mp3 new file mode 100644 index 0000000..71d91ba Binary files /dev/null and b/public/assets/voice-samples/fr_FR-siwis-medium.mp3 differ diff --git a/public/assets/voice-samples/it_IT-riccardo-x_low.mp3 b/public/assets/voice-samples/it_IT-riccardo-x_low.mp3 new file mode 100644 index 0000000..5ded36d Binary files /dev/null and b/public/assets/voice-samples/it_IT-riccardo-x_low.mp3 differ diff --git a/public/assets/voice-samples/pt_BR-faber-medium.mp3 b/public/assets/voice-samples/pt_BR-faber-medium.mp3 new file mode 100644 index 0000000..420ffc0 Binary files /dev/null and b/public/assets/voice-samples/pt_BR-faber-medium.mp3 differ diff --git a/public/assets/voice-samples/zh_CN-chaowen-medium.mp3 b/public/assets/voice-samples/zh_CN-chaowen-medium.mp3 new file mode 100644 index 0000000..18e7e1c Binary files /dev/null and b/public/assets/voice-samples/zh_CN-chaowen-medium.mp3 differ diff --git a/public/assets/voice-samples/zh_CN-xiao_ya-medium.mp3 b/public/assets/voice-samples/zh_CN-xiao_ya-medium.mp3 new file mode 100644 index 0000000..4843a59 Binary files /dev/null and b/public/assets/voice-samples/zh_CN-xiao_ya-medium.mp3 differ diff --git a/public/sitemap.xml b/public/sitemap.xml index 5dcf745..d3e5076 100644 --- a/public/sitemap.xml +++ b/public/sitemap.xml @@ -6,4 +6,7 @@ https://video-editor.ai-creator.top/faq/2026-07-16monthly0.8 https://video-editor.ai-creator.top/privacy/2026-07-16yearly0.5 https://video-editor.ai-creator.top/about/2026-07-16monthly0.7 + https://video-editor.ai-creator.top/articles/2026-07-17monthly0.8 + https://video-editor.ai-creator.top/articles/local-first-browser-ai-video-editor/2026-07-17monthly0.8 + https://video-editor.ai-creator.top/articles/liveportrait-webgpu-port/2026-07-17monthly0.8 diff --git a/src/App.jsx b/src/App.jsx index 7d6dbec..4555b97 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -1,11 +1,11 @@ -import { useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { LanguageIntro } from "./components/panels.jsx"; import { PreviewStage } from "./components/PreviewStage.jsx"; import { VoicePanel } from "./components/VoicePanel.jsx"; import { Timeline } from "./components/Timeline.jsx"; import { Topbar } from "./components/Topbar.jsx"; -import { AssetDragPreview, ExportProgressOverlay, RemasterProgressOverlay } from "./components/EditorOverlays.jsx"; +import { AssetDragPreview, ExportProgressOverlay } from "./components/EditorOverlays.jsx"; import { EditorSidebar } from "./components/EditorSidebar.jsx"; import { useExportElapsed } from "./hooks/useExportElapsed.js"; import { usePreviewFrameSize } from "./hooks/usePreviewFrameSize.js"; @@ -56,8 +56,7 @@ import { decodeWaveform, downloadBlob } from "./lib/media.js"; import { getImageThumbnailCount, getVisualSegmentsTotal } from "./lib/timeline.js"; import { removeVisualPropertyKeyframe, updateVisualSegmentPlaybackRate, upsertVisualKeyframe, upsertVisualPropertyKeyframe } from "./lib/visualEffects.js"; import { getLinkedSourceAudioEnd, getLinkedSourceAudioSegments } from "./lib/sourceAudioSync.js"; -import { captureRemasterSource, enhanceRemasterFrame } from "./lib/remasterEnhancement.js"; -import { enhanceRemasterClip } from "./lib/remasterClipEnhancement.js"; +import { getTimelineInitialContentZoom } from "./lib/timelineScale.js"; function getExportDimensions(ratio, longEdge) { const sourceLongEdge = Math.max(ratio.width, ratio.height); @@ -76,9 +75,9 @@ export function App() { const [uiLanguage, setUiLanguage] = useState(() => getStoredLanguage()); const [showExportMenu, setShowExportMenu] = useState(false); const [exportSettings, setExportSettings] = useState({ resolution: "1080", frameRate: 30, codec: "h264", quality: "high" }); - const [remasterQuality, setRemasterQuality] = useState("fast"); + const [captionVoiceFocusRequest, setCaptionVoiceFocusRequest] = useState(0); + const timelineImportRestoreRef = useRef(false); const [introClosing, setIntroClosing] = useState(false); - const [remasterJob, setRemasterJob] = useState({ running: false, mode: "", segmentId: "", progress: 0, phase: "", frameIndex: 0, totalFrames: 0, startedAt: 0, backend: "" }); const { captionPlacement, captionPosition, captionSegments, captionSize, captionStyle, captionsEnabled, script, selectedSegmentId, setCaptionPlacement, @@ -145,7 +144,7 @@ export function App() { avatarMotionCacheRef, avatarMotionWorkerRef, avatarRenderWorkerRef, avatarTestAudioImportedRef, avatarTestImportedRef, currentTimeRef, draggedAssetIdRef, exportStartRef, fileInputRef, imageUrlRefs, musicRef, musicUrlRef, pointerAssetDragRef, - previewCanvasRef, previewShellRef, previewVideoRef, projectFileInputRef, remasterAbortControllerRef, sourceAudioRef, + previewCanvasRef, previewShellRef, previewVideoRef, projectFileInputRef, sourceAudioRef, sourceAudioUrlRef, suppressAssetClickRef, suppressTimelineClipClickRef, timelineClipDragRef, timelineDurationRef, trackScrollRef, visionAbortControllerRef, visionJobGenerationRef, visionObjectUrlsRef, visualPlaybackFrameRef, @@ -216,6 +215,26 @@ export function App() { sourceAudioStart, sourceAudioUrl, stickerSegments, timelineDurationRef, timelineHorizon, trackVisibility, visionRecords, visualSegments, visualType, }); + const previousTimelineContentDurationRef = useRef(estimatedDuration); + useEffect(() => { + const previousDuration = previousTimelineContentDurationRef.current; + const becameNonEmpty = previousDuration <= 0 && estimatedDuration > 0; + const becameEmpty = previousDuration > 0 && estimatedDuration <= 0; + + if (becameNonEmpty) { + if (timelineImportRestoreRef.current) timelineImportRestoreRef.current = false; + else setTimelineZoom(getTimelineInitialContentZoom(estimatedDuration)); + if (trackScrollRef.current) trackScrollRef.current.scrollLeft = 0; + } else if (becameEmpty) { + timelineImportRestoreRef.current = false; + setTimelineHorizon(10); + setTimelineZoom(getTimelineInitialContentZoom(0)); + setCurrentTime(0); + if (trackScrollRef.current) trackScrollRef.current.scrollLeft = 0; + } + + previousTimelineContentDurationRef.current = estimatedDuration; + }, [estimatedDuration, setCurrentTime, setTimelineHorizon, setTimelineZoom, trackScrollRef]); const previewFrameSize = usePreviewFrameSize(previewShellRef, ratio, compactRail); const selectedVisualSegment = visualSegments[selectedVisualSegmentIndex] ?? previewVisualSegment ?? null; const selectedVisualRange = visualTimeline[selectedVisualSegmentIndex] ?? previewVisualRange; @@ -272,155 +291,6 @@ export function App() { return nextItems; }); }; - const clearSelectedVisualEnhancement = () => { - if (!selectedVisualSegment?.id) return; - remasterAbortControllerRef.current?.abort(); - setVisualSegments((items) => items.map((item) => { - if (item.id !== selectedVisualSegment.id) return item; - if (item.enhancement?.mode !== "remaster-drunet-full" || !item.enhancement.original?.src) return { ...item, enhancement: null }; - const original = item.enhancement.original; - return { - ...item, - src: original.src, - blob: original.blob, - width: original.width, - height: original.height, - sourceStart: original.sourceStart, - sourceDuration: original.sourceDuration, - trackFrames: original.trackFrames ?? [], - enhancement: null, - }; - })); - setRemasterJob({ running: false, mode: "", segmentId: "", progress: 0, phase: "", frameIndex: 0, totalFrames: 0, startedAt: 0 }); - }; - const enhanceSelectedVisualFrame = async () => { - if (!selectedVisualSegment?.id || !selectedVisualSegment.src) return notify(t("remasterSelectClip")); - if (remasterJob.running) return; - const controller = new AbortController(); - remasterAbortControllerRef.current = controller; - setIsPlaying(false); - previewVideoRef.current?.pause(); - setRemasterJob({ running: true, mode: "frame", segmentId: selectedVisualSegment.id, progress: 1, phaseKey: "remasterPreparing", frameIndex: 0, totalFrames: 1, startedAt: Date.now() }); - try { - const bitmap = await captureRemasterSource({ - type: selectedVisualSegment.type, - src: selectedVisualSegment.src, - video: previewVideoRef.current, - }); - const result = await enhanceRemasterFrame({ - bitmap, - maxLongEdge: remasterQuality === "quality" ? 960 : 640, - signal: controller.signal, - onProgress: ({ progress, phaseKey, phaseParams }) => setRemasterJob((job) => ({ ...job, running: true, progress, phaseKey, phaseParams })), - }); - if (controller.signal.aborted) return; - const previewUrl = URL.createObjectURL(result.blob); - imageUrlRefs.current.add(previewUrl); - setVisualSegments((items) => items.map((item) => { - if (item.id !== selectedVisualSegment.id) return item; - return { ...item, enhancement: { - enabled: true, - mode: "remaster-drunet-frame-preview", - previewUrl, - previewBlob: result.blob, - localTime: visualLocalTime, - sourceTime: previewVisualSourceTime, - width: result.width, - height: result.height, - inferenceMs: result.inferenceMs, - } }; - })); - setRemasterJob({ running: false, mode: "frame", segmentId: selectedVisualSegment.id, progress: 100, phase: t("remasterReady"), frameIndex: 1, totalFrames: 1, startedAt: 0 }); - notify(t("remasterReady")); - } catch (error) { - if (error?.name !== "AbortError") notify(error instanceof Error ? error.message : t("remasterFailed")); - setRemasterJob({ running: false, mode: "frame", segmentId: selectedVisualSegment.id, progress: 0, phase: "", frameIndex: 0, totalFrames: 1, startedAt: 0 }); - } finally { - if (remasterAbortControllerRef.current === controller) remasterAbortControllerRef.current = null; - } - }; - const cancelRemasterEnhancement = () => { - if (!remasterJob.running) return; - setRemasterJob((job) => ({ ...job, phase: "", phaseKey: "remasterCanceling", phaseParams: {} })); - remasterAbortControllerRef.current?.abort(); - }; - const enhanceSelectedVisualClip = async () => { - if (!selectedVisualSegment?.id || !selectedVisualSegment.src) return notify(t("remasterSelectClip")); - if (selectedVisualSegment.type !== "video") return notify(t("remasterClipOnlyVideo")); - if (remasterJob.running) return; - const existingOriginal = selectedVisualSegment.enhancement?.mode === "remaster-drunet-full" - ? selectedVisualSegment.enhancement.original - : null; - const original = existingOriginal ?? { - src: selectedVisualSegment.src, - blob: selectedVisualSegment.blob, - width: selectedVisualSegment.width, - height: selectedVisualSegment.height, - sourceStart: selectedVisualSegment.sourceStart ?? 0, - sourceDuration: selectedVisualSegment.sourceDuration, - trackFrames: selectedVisualSegment.trackFrames ?? [], - }; - const inputSegment = { ...selectedVisualSegment, ...original, type: "video" }; - const controller = new AbortController(); - remasterAbortControllerRef.current = controller; - setIsPlaying(false); - previewVideoRef.current?.pause(); - setRemasterJob({ running: true, mode: "clip", segmentId: selectedVisualSegment.id, progress: 1, phaseKey: "remasterClipPreparing", frameIndex: 0, totalFrames: 0, startedAt: Date.now() }); - try { - const result = await enhanceRemasterClip({ - segment: inputSegment, - videoElement: previewVideoRef.current, - frameRate: exportSettings.frameRate, - maxLongEdge: 960, - signal: controller.signal, - onProgress: ({ progress, phaseKey, phaseParams, frameIndex = 0, totalFrames = 0, backend = "" }) => setRemasterJob((job) => ({ - ...job, - running: true, - progress, - phase: "", - phaseKey, - phaseParams, - frameIndex, - totalFrames, - backend: backend || job.backend, - })), - }); - if (controller.signal.aborted) return; - const processedUrl = URL.createObjectURL(result.blob); - imageUrlRefs.current.add(processedUrl); - const processed = { - src: processedUrl, - blob: result.blob, - width: result.width, - height: result.height, - sourceStart: 0, - sourceDuration: result.sourceDuration, - trackFrames: [], - }; - setVisualSegments((items) => items.map((item) => item.id === selectedVisualSegment.id ? { - ...item, - ...processed, - enhancement: { - enabled: true, - mode: "remaster-drunet-full", - original, - processed, - frameRate: result.frameRate, - totalFrames: result.totalFrames, - backend: result.backend, - quality: remasterQuality, - }, - } : item)); - setRemasterJob({ running: false, mode: "clip", segmentId: selectedVisualSegment.id, progress: 100, phase: t("remasterClipReady"), frameIndex: result.totalFrames, totalFrames: result.totalFrames, startedAt: 0 }); - notify(t("remasterClipReady")); - } catch (error) { - if (error?.name === "AbortError") notify(t("remasterCanceled")); - else notify(error instanceof Error ? error.message : t("remasterFailed")); - setRemasterJob({ running: false, mode: "clip", segmentId: selectedVisualSegment.id, progress: 0, phase: "", frameIndex: 0, totalFrames: 0, startedAt: 0 }); - } finally { - if (remasterAbortControllerRef.current === controller) remasterAbortControllerRef.current = null; - } - }; const exportElapsedSeconds = useExportElapsed(exporting, exportStartRef); const { effectiveCaptionPlacement, previewSmartCropRect, previewVisionAnalysis, @@ -476,15 +346,6 @@ export function App() { setScript, setSelectedSegmentId, setSelectedTrack, setVisionRecords, trackLocks, }); - const createCaptionFromPreview = (text, placement) => { - const start = Math.max(0, currentTime); - const segment = { id: crypto.randomUUID(), text, hidden: false, weight: 1, start, end: start + 2.5 }; - commitCaptionSegments([...captionSegments, segment].sort((a, b) => (a.start ?? 0) - (b.start ?? 0)), "字幕已加入时间线", 0); - setSelectedSegmentId(segment.id); - setCaptionPlacement({ x: placement.x, y: placement.y }); - setCaptionPosition("custom"); - }; - const { clearAudioTrack, clearMusicTrack, clearSourceAudioTrack, commitAudio, replaceAudio, replaceMusic, replaceSourceAudio, @@ -605,7 +466,7 @@ export function App() { selectedStickerSegmentId, selectedTrack, selectedVisualSegmentId, setCurrentVisualAsset, setFitMode, setRatioId, setSelectedSegmentId, setSelectedVisualSegmentId, setUserAssets, sourceAudioBlob, sourceAudioUrlRef, stickerSegments, - remasterAbortControllerRef, visionAbortControllerRef, visionObjectUrlsRef, visualSegments, + visionAbortControllerRef, visionObjectUrlsRef, visualSegments, voiceRecorderStreamRef, voiceRecorderTimerRef, }); @@ -706,7 +567,9 @@ export function App() { setRatioId, setScript, setSelectedFilterId, setSelectedSegmentId, setSelectedStickerId, setSelectedStickerSegmentId, setSelectedTransitionId, setSelectedVoiceId, setShowFileMenu, setSourceAudioAssetId, setSourceAudioLinked, setSourceAudioVolume, setSpeed, setStickerSegments, setTimelineZoom, setTrackVisibility, + setTimelineHorizon, setVisualSegments, setVolume, setCurrentVisualAsset, sourceAudioBlob, sourceAudioDuration, + markTimelineViewRestored: (hasContent) => { timelineImportRestoreRef.current = hasContent; }, sourceAudioAssetId, sourceAudioLinked, sourceAudioName, sourceAudioStart, sourceAudioVolume, speed, stickerSegments, timelineZoom, trackVisibility, visualSegments, volume, }); @@ -877,15 +740,14 @@ export function App() { currentTime={currentTime} seekTo={seekTo} notify={notify} - activeTool={activeTool} getDraggedAsset={getDraggedAsset} applyAssetToTrack={applyAssetToTrack} - onCreateCaptionAt={createCaptionFromPreview} /> setCaptionVoiceFocusRequest((request) => request + 1)} trackVisibility={trackVisibility} toggleTrackVisibility={toggleTrackVisibility} trackLocks={trackLocks} @@ -1060,7 +917,6 @@ export function App() { - {shouldShowLanguageIntro ? ( ) : null} diff --git a/src/components/PreviewStage.jsx b/src/components/PreviewStage.jsx index 1450f13..bc80aff 100644 --- a/src/components/PreviewStage.jsx +++ b/src/components/PreviewStage.jsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from "react"; +import { useEffect } from "react"; import { CaretDown, CloudArrowUp, @@ -58,17 +58,9 @@ export function PreviewStage({ visualLocalTime = 0, visualMaskEditable = false, onUpdateVisualMask, - activeTool, getDraggedAsset, applyAssetToTrack, - onCreateCaptionAt, }) { - const [captionDraft, setCaptionDraft] = useState(null); - const commitCaptionDraft = () => { - const text = captionDraft?.text.trim(); - if (text) onCreateCaptionAt?.(text, captionDraft); - setCaptionDraft(null); - }; const hasStickerOverlay = Boolean(selectedSticker?.src || selectedSticker?.text); const hasPreviewContent = Boolean(previewVisualSrc || hasStickerOverlay); const renderedVisualSrc = previewVisualRenderSrc || previewVisualSrc; @@ -191,11 +183,6 @@ export function PreviewStage({ } ${smartCropActive ? "has-smart-crop" : ""}`} data-hidden-label={t("imageHidden")} style={previewFrameStyle} - onClick={(event) => { - if (activeTool !== "caption" || event.target.closest(".caption-overlay, .visual-mask-editor, .inline-caption-editor")) return; - const rect = event.currentTarget.getBoundingClientRect(); - setCaptionDraft({ x: Math.max(8, Math.min(92, ((event.clientX - rect.left) / rect.width) * 100)), y: Math.max(8, Math.min(92, ((event.clientY - rect.top) / rect.height) * 100)), text: "" }); - }} > {renderedVisualSrc && trackVisibility.image ? (
@@ -276,11 +263,6 @@ export function PreviewStage({ onDoubleClick={() => setActiveTool("caption")} /> ) : null} - {captionDraft ? ( -
{ event.preventDefault(); commitCaptionDraft(); }}> - setCaptionDraft((draft) => ({ ...draft, text: event.target.value }))} onKeyDown={(event) => { if (event.key === "Escape") setCaptionDraft(null); if (event.key === "Enter" && !event.shiftKey) { event.preventDefault(); commitCaptionDraft(); } }} onBlur={() => { if (!captionDraft.text.trim()) setCaptionDraft(null); }} /> -
- ) : null} {selectedSticker.src ? ( ) : selectedSticker.text ? ( diff --git a/src/components/Timeline.jsx b/src/components/Timeline.jsx index 8de71f4..8144e99 100644 --- a/src/components/Timeline.jsx +++ b/src/components/Timeline.jsx @@ -22,24 +22,28 @@ import { Scissors, SlidersHorizontal, Trash, + Waveform, } from "@phosphor-icons/react"; import { IMAGE_SEGMENT_SECONDS } from "../config/editor.js"; -import { formatClock, formatTime, getImageThumbnailCount, getSegmentStartTime, packTimedSegmentsIntoLanes } from "../lib/timeline.js"; +import { formatClock, formatTime, getSegmentStartTime, packTimedSegmentsIntoLanes } from "../lib/timeline.js"; import { sliceSourceAudioPeaks } from "../lib/sourceAudioSync.js"; import { - TIMELINE_MIN_ZOOM, clampTimelineZoom, getTimelineRulerTicks, + getTimelineAutoFitZoom, getTimelineTrackWidthPercent, getTimelineZoomLabel, } from "../lib/timelineScale.js"; import { IconButton, WaveformStrip } from "./ui.jsx"; -const TIMELINE_WHEEL_ZOOM_SENSITIVITY = 0.00034; +const TIMELINE_WHEEL_ZOOM_SENSITIVITY = 0.00056; const TIMELINE_WHEEL_ZOOM_COMMIT_DELAY = 180; const TIMELINE_BUTTON_ZOOM_RATIO = 1.25; +const TIMELINE_TRACK_ROW_HEIGHT = "48px"; const VIDEO_FRAME_MIN_COUNT = 1; +const IMAGE_THUMBNAIL_TARGET_WIDTH = 84; +const IMAGE_THUMBNAIL_MAX_COUNT = 240; const TIMELINE_WHEEL_ZOOM_CONTENT_SELECTOR = [ ".image-clip", ".caption-segment", @@ -103,6 +107,15 @@ function getVideoTimelineFrameCount({ duration, timelineDuration, contentWidth, ); } +function getImageTimelineThumbnailCount({ duration, timelineDuration, contentWidth }) { + if (timelineDuration <= 0 || contentWidth <= 0) { + return 1; + } + + const clipPixelWidth = Math.max(0, (Math.max(0, duration || 0) / timelineDuration) * contentWidth); + return Math.max(1, Math.min(IMAGE_THUMBNAIL_MAX_COUNT, Math.ceil(clipPixelWidth / IMAGE_THUMBNAIL_TARGET_WIDTH))); +} + export function Timeline({ t, undo, @@ -123,6 +136,7 @@ export function Timeline({ selectedTrack, setSelectedTrack, setActiveTool, + requestCaptionVoiceFocus, trackVisibility, toggleTrackVisibility, trackLocks, @@ -204,7 +218,14 @@ export function Timeline({ () => packCaptionSegmentsIntoLanes(displayedCaptionSegments, displayedCaptionTimeline), [displayedCaptionSegments, displayedCaptionTimeline], ); - const contentRows = ["46px", ...(showStickerTrack ? stickerLanes.map(() => "46px") : []), ...captionLanes.map(() => "46px"), "58px", ...audioLanes.map(() => "58px"), "58px"]; + const contentRows = [ + TIMELINE_TRACK_ROW_HEIGHT, + ...(showStickerTrack ? stickerLanes.map(() => TIMELINE_TRACK_ROW_HEIGHT) : []), + ...captionLanes.map(() => TIMELINE_TRACK_ROW_HEIGHT), + TIMELINE_TRACK_ROW_HEIGHT, + ...audioLanes.map(() => TIMELINE_TRACK_ROW_HEIGHT), + TIMELINE_TRACK_ROW_HEIGHT, + ]; const timelineTrackRows = ["28px", ...contentRows].join(" "); const timelineLabelRows = contentRows.join(" "); const timelineTrackLabels = [ @@ -238,10 +259,14 @@ export function Timeline({ const showTrackContextMenu = (event, track, segmentId = "") => { event.preventDefault(); event.stopPropagation(); selectContextTarget(track, segmentId); + const trackRect = trackScrollRef.current?.getBoundingClientRect(); + const targetTime = trackRect && timelineDuration > 0 + ? Math.max(0, Math.min(timelineDuration, ((event.clientX - trackRect.left) / trackRect.width) * timelineDuration)) + : currentTime; setContextMenu({ x: Math.max(10, Math.min(window.innerWidth - 234, event.clientX)), y: Math.max(10, Math.min(window.innerHeight - 258, event.clientY)), - track, segmentId, kind: segmentId ? "clip" : "track", + track, segmentId, targetTime, kind: segmentId ? "clip" : "track", }); }; const runContextAction = (action) => { @@ -251,12 +276,16 @@ export function Timeline({ useEffect(() => { if (!contextMenu) return undefined; const close = () => setContextMenu(null); + const closeOnOutsidePointer = (event) => { + if (event.target?.closest?.(".timeline-context-menu")) return; + close(); + }; const closeOnKey = (event) => event.key === "Escape" && close(); - window.addEventListener("pointerdown", close); + window.addEventListener("pointerdown", closeOnOutsidePointer, true); window.addEventListener("keydown", closeOnKey); window.addEventListener("blur", close); return () => { - window.removeEventListener("pointerdown", close); + window.removeEventListener("pointerdown", closeOnOutsidePointer, true); window.removeEventListener("keydown", closeOnKey); window.removeEventListener("blur", close); }; @@ -337,10 +366,11 @@ export function Timeline({ if (wheelZoomFrameRef.current) { window.cancelAnimationFrame(wheelZoomFrameRef.current); } + trackScrollRef.current?.classList.remove("is-wheel-zooming"); wheelZoomActiveRef.current = false; window.clearTimeout(commitZoomTimerRef.current); }, - [], + [trackScrollRef], ); const secondsPerPixel = timelineDuration > 0 && rulerViewport.contentWidth > 0 @@ -356,6 +386,7 @@ export function Timeline({ [timelineDuration, localTimelineZoom, rulerVisibleEnd, rulerVisibleStart], ); const zoomReadout = getTimelineZoomLabel(localTimelineZoom); + const fitTimelineZoom = getTimelineAutoFitZoom(timelineDuration, 0.9); const localTrackWidth = `${getTimelineTrackWidthPercent(timelineDuration, localTimelineZoom)}%`; const commitTimelineZoom = (nextZoom, delay = 0) => { window.clearTimeout(commitZoomTimerRef.current); @@ -415,6 +446,7 @@ export function Timeline({ wheelZoomActiveRef.current = true; timelineZoomRef.current = nextZoom; + anchor.trackElement.classList.add("is-wheel-zooming"); anchor.trackElement.style.width = `${nextTrackWidthPercent}%`; anchor.trackElement.style.setProperty("--timeline-zoom", String(nextZoom)); anchor.scrollElement.scrollLeft = Math.max(0, nextScrollLeft); @@ -427,7 +459,10 @@ export function Timeline({ wheelZoomActiveRef.current = false; setLocalTimelineZoom(nextZoom); setTimelineZoom(nextZoom); - window.requestAnimationFrame(() => rulerViewportSyncRef.current?.()); + window.requestAnimationFrame(() => { + anchor.trackElement.classList.remove("is-wheel-zooming"); + rulerViewportSyncRef.current?.(); + }); }, TIMELINE_WHEEL_ZOOM_COMMIT_DELAY); }; const handleTimelineWheel = (event) => { @@ -447,7 +482,7 @@ export function Timeline({ return; } - if (Math.abs(event.deltaX) > Math.abs(event.deltaY)) { + if (!hasZoomModifier && Math.abs(event.deltaX) > Math.abs(event.deltaY)) { return; } @@ -660,8 +695,8 @@ export function Timeline({ {zoomReadout} adjustTimelineZoom(TIMELINE_MIN_ZOOM)} + active={Math.abs(localTimelineZoom - fitTimelineZoom) < 0.001} + onClick={() => adjustTimelineZoom(fitTimelineZoom)} > @@ -852,6 +887,7 @@ export function Timeline({ className={`image-thumbnails ${segmentType === "video" ? "is-video" : ""} ${ isPortraitVideo ? "is-portrait-video" : "" }`} + style={{ "--thumbnail-cell-width": `${IMAGE_THUMBNAIL_TARGET_WIDTH}px` }} > {segmentType === "video" ? ( visibleVideoFrames.length ? ( @@ -871,7 +907,11 @@ export function Timeline({ { length: Math.max( 1, - getImageThumbnailCount(segment.duration || IMAGE_SEGMENT_SECONDS), + getImageTimelineThumbnailCount({ + duration: segment.duration || IMAGE_SEGMENT_SECONDS, + timelineDuration, + contentWidth: rulerViewport.contentWidth, + }), ), }, (_, thumbnailIndex) => ( @@ -1110,21 +1150,27 @@ export function Timeline({
) : null} {contextMenu ? ( -
event.stopPropagation()}> -
{contextMenu.kind === "clip" ? "片段操作" : "轨道操作"}{contextMenu.track}
- +
event.stopPropagation()}> +
{contextMenu.kind === "clip" ? t("clipActions") : t("trackActions")}{t({ image: "imageTrack", caption: "caption", sticker: "stickerTrack", source: "sourceTrack", voice: "voiceTrack", music: "musicTrack" }[contextMenu.track], contextMenu.track)}
+ {contextMenu.kind === "clip" ? ( <> - - + {contextMenu.track === "caption" ? ( + + ) : null} + +
- + ) : ( <> - {["image", "caption"].includes(contextMenu.track) ? : null} - - + {["image", "caption"].includes(contextMenu.track) ? : null} + + )}
diff --git a/src/components/VoicePanel.jsx b/src/components/VoicePanel.jsx index 1608562..0c7b959 100644 --- a/src/components/VoicePanel.jsx +++ b/src/components/VoicePanel.jsx @@ -3,16 +3,18 @@ import { ClosedCaptioning, Eye, EyeSlash, + ImageSquare, ListBullets, PersonSimpleRun, Trash, Waveform, } from "@phosphor-icons/react"; -import { useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { formatTime, getSegmentStartTime } from "../lib/timeline.js"; import { LIVE_PORTRAIT_WEB_MODEL } from "../config/livePortrait.js"; import { probeLivePortraitWebEnvironment } from "../lib/livePortraitWeb.js"; +import { getCaptionVoiceSegment } from "../lib/captionVoice.js"; import { normalizeVisualKeyframes } from "../lib/visualEffects.js"; import { HistoryPanel, MyVoicesPanel, VisualEffectsPanel, VoiceSynthesisPanel } from "./panels.jsx"; @@ -65,7 +67,7 @@ function CaptionContextPanel({
{t("noCaptionSegments")} - {t("captionEmptyHint", "选择时间线字幕片段后,这里会同步编辑。")} + {t("captionEmptyHint", "字幕片段可拖动到字幕轨道,并在这里同步编辑。")}
)} @@ -248,6 +250,7 @@ function AvatarContextPanel({ t, hasVisual, visualType, audioBlob, audioDuration export function VoicePanel({ t, activeTool, + captionVoiceFocusRequest = 0, status, statusText, voiceTab, @@ -320,37 +323,47 @@ export function VoicePanel({ visualLocalTime, visualTimelineStart = 0, updateSelectedVisualEffects, - remasterJob, - remasterQuality, - setRemasterQuality, - enhanceSelectedVisualFrame, - enhanceSelectedVisualClip, - clearSelectedVisualEnhancement, selectedFilterId, setSelectedFilterId, trOption, }) { + const [captionPanelTab, setCaptionPanelTab] = useState("caption"); + const panelRef = useRef(null); const isCaptionContext = activeTool === "caption"; const isAvatarContext = activeTool === "smart" && avatarPanelOpen; const isAudioClipContext = selectedTrack === "audio" && Boolean(selectedAudioSegment); - const isVisualContext = selectedTrack === "image" && Boolean(selectedVisualSegment); - const title = isVisualContext ? t("imageTrack") : isAvatarContext ? t("avatarTitle") : isCaptionContext ? t("caption") : isAudioClipContext ? t("audioClipProperties") : t("aiVoice"); + const isVisualContext = selectedTrack === "image"; + const selectedCaptionAudioSegment = getCaptionVoiceSegment(audioSegments, selectedCaptionSegment); + const title = isVisualContext ? t("visualPanelTitle") : isAvatarContext ? t("avatarTitle") : isCaptionContext ? t("caption") : isAudioClipContext ? t("audioClipProperties") : t("aiVoice"); const panelStatusText = isCaptionContext ? captionSegments.length ? `${captionSegments.length} ${t("captionSegmentsUnit", "条字幕")}` : t("noCaptionSegments") : isVisualContext - ? `${visualLocalTime.toFixed(2)}s · ${normalizeVisualKeyframes(selectedVisualSegment.keyframes).length} ${t("visualFrames")}` + ? selectedVisualSegment + ? `${visualLocalTime.toFixed(2)}s · ${normalizeVisualKeyframes(selectedVisualSegment.keyframes).length} ${t("visualFrames")}` + : t("visualSelectClip") : isAvatarContext ? t("avatarPortingStatus") : isAudioClipContext ? `${formatTime(selectedAudioSegment.duration)} · ${selectedAudioSegment.start.toFixed(1)}s` : statusText === "模型待命" ? t("modelReady") - : statusText; + : statusText; + + useEffect(() => { + if (!captionVoiceFocusRequest || !isCaptionContext) return; + setCaptionPanelTab("voice"); + const frame = requestAnimationFrame(() => { + requestAnimationFrame(() => { + panelRef.current?.querySelector(".voice-header")?.scrollIntoView({ block: "start", behavior: "smooth" }); + }); + }); + return () => cancelAnimationFrame(frame); + }, [captionVoiceFocusRequest, isCaptionContext]); return ( -