Improve editor timeline and caption voice workflows (#13)
* fix editor media caption and audio workflows * improve editor timeline and caption voice workflows --------- Co-authored-by: haixin.yang <haixin.yang@weimob.com>
This commit is contained in:
1 parent
42ea7685e4
commit
a6b7a9e51b
40 files changed
+794
-365
No files matched your search
@@ -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,.lLine truncated
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 148 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 116 KiB |
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>技术文章 | Timeline Studio</title><meta name="description" content="Timeline Studio 的浏览器 AI、WebGPU、ONNX 与本地优先视频编辑工程实践。"><link rel="stylesheet" href="/articles/article.css"></head><body><header class="site-header"><nav class="nav"><a class="brand" href="/"><span class="brand-mark">TS</span>Timeline Studio</a><div class="nav-links"><a href="/">打开编辑器</a><a href="https://github.com/MartinDelophy/ai-video-editor">GitHub ↗</a></div></nav></header><main class="index-wrap"><div class="index-title"><p class="eyebrow">Engineering Notes · 2026</p><h1>把浏览器推到创作工具的边界</h1><p class="deck">两篇来自 Timeline Studio 真实代码与验证数据的工程手记:一篇谈完整系统,一篇深入神经网络算子。</p></div><section class="article-grid"><a class="article-card" href="/articles/local-first-browser-ai-video-editor/"><img src="/articles/assets/local-first-architecture.webp" alt="浏览器端本地优先 AI 视频编辑器架构概念图"><div class="article-card-body"><span class="tag">系统架构 · 12 分钟</span><h2>把 AI 视频编辑器装进浏览器:本地优先架构的六个关键决策</h2><p>从 Worker、模型缓存到多轨时间线与导出,拆解一个真正可用的浏览器 AI 工作流。</p></div></a><a class="article-card" href="/articles/liveportrait-webgpu-port/"><img src="/articles/assets/liveportrait-webgpu.webp" alt="LivePortrait 5D 张量到 WebGPU 的转换概念图"><div class="article-card-body"><span class="tag">WebGPU 深潜 · 15 分钟</span><h2>5D GridSample 进不了浏览器之后:LivePortrait 的 WebGPU 移植实战</h2><p>如何改写 ONNX 图、验证数值等价,并让大型数字人管线在浏览器里完成闭环。</p></div></a></section></main></body></html>
|
||||
@@ -0,0 +1,19 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>LivePortrait 的 WebGPU 移植实战 | Timeline Studio</title><meta name="description" content="拆解 LivePortrait ONNX 从 5D GridSample 到浏览器 WebGPU 的等价图改写、数值验证和运行时工程。"><meta property="og:title" content="5D GridSample 进不了浏览器之后:LivePortrait 的 WebGPU 移植实战"><meta property="og:image" content="/articles/assets/liveportrait-webgpu.webp"><link rel="stylesheet" href="/articles/article.css"></head><body><header class="site-header"><nav class="nav"><a class="brand" href="/"><span class="brand-mark">TS</span>Timeline Studio</a><div class="nav-links"><a href="/articles/">技术文章</a><a href="https://github.com/MartinDelophy/ai-video-editor">GitHub ↗</a></div></nav></header><main><header class="hero"><p class="eyebrow">ONNX · WebGPU · Graph Surgery</p><h1>5D GridSample 进不了浏览器之后:LivePortrait 的 WebGPU 移植实战</h1><p class="deck">当一个神经网络算子没有浏览器实现时,真正的问题不是“换哪个库”,而是能否把计算改写成 WebGPU 支持的图,并证明它在数值上仍然是同一个模型。</p><div class="meta"><span>Timeline Studio 工程手记</span><span>2026-07-17</span><span>约 15 分钟</span></div></header><div class="hero-image"><img src="/articles/assets/liveportrait-webgpu.webp" alt="5D 张量改写为 4D 采样平面并进入 WebGPU 的概念图"></div><div class="layout"><article class="article"><p class="lede">Timeline Studio 的数字人链路使用 JoyVASA 从音频生成动作,再由 LivePortrait 把动作施加到源肖像。模型本身可以导出为 ONNX,真正阻塞浏览器的是生成器中的 rank-5 运算和两个 5D <code>GridSample</code>。</p>
|
||||
<h2 id="pipeline">01. 先把“数字人”拆成可验证的流水线</h2><p>这条链路不是单模型调用。它至少包含外观特征提取、源图动作提取、音频驱动、嘴型重定向、关键点拼接、3D 特征形变与 SPADE 图像生成。JoyVASA 的 HuBERT 与 diffusion denoiser 负责把语音转成动作序列,LivePortrait 则负责神经渲染。</p><div class="diagram"><div class="flow"><div>Audio<br>JoyVASA</div><div>Motion<br>Keypoints</div><div>3D Warp<br>LivePortrait</div><div>SPADE<br>RGB Frame</div></div></div><p>先拆管线的价值是可定位:音频驱动的误差、关键点组合的误差、warping 的误差和最终生成器的误差可以分别测量。否则最终人脸“不对”,你几乎无法知道问题来自哪一段。</p>
|
||||
<h2 id="blocker">02. 真正的阻塞点:浏览器没有 5D GridSample</h2><p>基线 combined generator 使用 opset 20,共 277 个节点,其中有 13 个 rank-5 Conv 与两个 rank-5 GridSample。原仓库附带的 Linux <code>.so</code> 插件无法在浏览器加载,而 ONNX Runtime Web 的 WebGPU 执行提供程序也不能直接执行这两个 5D 采样节点。</p><p>输入特征可写成 <code>[N, C, D, H, W]</code>,采样网格则在三个空间轴上给出目标坐标。Web 端现成的 GridSample 只处理二维平面。直接删除深度维、把它当批次维或者只取最近切片,都会改变模型含义。</p><div class="callout"><p><strong>工程原则:</strong>当目标运行时缺少算子时,图改写必须保持数学语义。视觉上“差不多”不能替代误差统计。</p></div>
|
||||
<h2 id="rewrite">03. 等价改写:4D 采样 + 深度线性插值</h2><p>三线性采样可以拆成两步:先在深度轴上找到目标坐标两侧的切片 <code>d0</code> 与 <code>d1</code>;分别对这两个 2D 平面执行双线性 GridSample;最后按深度小数部分 <code>α</code> 做线性插值。</p><pre><code>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</code></pre><p>实现时需要把深度切片组织成批次,使 WebGPU 能并行执行 4D GridSample,再还原为原来的空间布局。稀疏动作网格还存在经过验证的共享 XY 结构,可以去掉重复的深度采样。改写后的图从 277 个节点增加到 316 个节点,但全部落在 Web 端已支持的算子集合里。</p>
|
||||
<h2 id="validation">04. 数值验证:证明改写前后是同一个函数</h2><p>验证使用固定输入,将原始 512×512 generator 与 WebGPU 改写图的完整输出逐元素比较。除了最大误差,还同时查看均值和高分位误差,以免少量异常点被平均值掩盖。</p><div class="metrics"><div class="metric"><b>7.8976e-6</b><span>最大绝对误差</span></div><div class="metric"><b>1.3853e-7</b><span>平均绝对误差</span></div><div class="metric"><b>1.7881e-6</b><span>99.9% 分位误差</span></div></div><p>JoyVASA 的 HuBERT 与 diffusion denoiser ONNX 导出也分别对齐 PyTorch,最大绝对误差为 <code>7.75e-6</code> 和 <code>6.44e-6</code>。只有每一段都建立基线,端到端结果才具有可解释性。</p>
|
||||
<h2 id="runtime">05. 图能跑以后,运行时问题才刚开始</h2><p>ONNX Runtime Web 的 WebGPU Worker 必须加载匹配的 Asyncify glue 与 WASM 文件。使用普通或 JSEP glue 会触发 <code>webgpuInit is not a function</code>。多个大型执行提供程序会话还需要串行创建,否则 ORT 可能拒绝并发初始化。</p><p>模型包约 906 MB,不适合进入 Git 仓库。项目把它拆成 50 MB 分片,发布到 revision-pinned 的 Hugging Face 模型仓库,并由 Service Worker 缓存。版本固定同时保护了两个假设:图结构不变,运行时代码期待的输入输出也不变。</p><pre><code>await createJoyVasaSession();
|
||||
releaseTransientGpuResources();
|
||||
await createLivePortraitSession();
|
||||
appearanceFeature = await extractOnce(sourcePortrait);
|
||||
for (const motion of sparseMotions)
|
||||
frames.push(await render(appearanceFeature, motion));</code></pre>
|
||||
<h2 id="performance">06. “跑通”不等于“实时”</h2><p>项目提供 mixed-FP16 256px 快速预览与 mixed-FP16 512px 质量档。外观特征在帧间保持 GPU 驻留,神经关键帧以 1–2 fps 稀疏渲染,再插值到编码帧率,降低总推理次数。</p><p>但必须诚实:在验证设备上,512×512 神经帧仍需要约 25–60 秒。界面展示真实阶段、帧数与耗时,不把稀疏关键帧插值包装成“实时神经渲染”。生成帧会检查非有限值与时间异常,问题帧重试一次,仍失败则沿用上一有效帧。</p>
|
||||
<h2 id="acceptance">07. 端到端验收必须走完媒体闭环</h2><p>单个 ONNX session 返回 tensor 只代表算子层通过。真正的验收还包括:模型分片下载、WebGPU 初始化、JoyVASA 50 步动作生成、LivePortrait 渲染、WebM 编码、浏览器播放、媒体库插入和视觉轨替换。</p><p>最终验收产物是一段可播放的 3.56 秒 WebM。抽帧能看到张嘴、闭嘴以及头眼运动,完成后浏览器控制台错误为 0。这个闭环很重要,因为编码、Blob 生命周期或轨道替换中的任意错误,都能让“模型成功”变成“用户什么也得不到”。</p>
|
||||
<h2 id="takeaway">结论:算子移植的核心是可证明</h2><p>将桌面端模型带进浏览器,最有价值的能力不是写一段兼容代码,而是建立完整证据链:审计图、定位不支持算子、构造等价变换、逐层对齐、统计误差、验证真实运行时,最后走完整个媒体产品闭环。</p><p>WebGPU 正在快速扩大浏览器的计算边界。但在这个边界上,最可靠的优化不是更响亮的性能口号,而是每一步都有数字、失败路径和可复现产物。</p><footer class="article-footer"><a class="next-card" href="/articles/local-first-browser-ai-video-editor/"><small>继续阅读 · 系统架构</small><strong>把 AI 视频编辑器装进浏览器:六个关键决策 →</strong></a></footer></article><aside class="toc"><p class="toc-title">本文目录</p><a href="#pipeline">拆解流水线</a><a href="#blocker">5D GridSample 阻塞</a><a href="#rewrite">等价图改写</a><a href="#validation">数值验证</a><a href="#runtime">浏览器运行时</a><a href="#performance">性能边界</a><a href="#acceptance">端到端验收</a><a href="#takeaway">工程结论</a></aside></div></main></body></html>
|
||||
@@ -0,0 +1,19 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>把 AI 视频编辑器装进浏览器 | Timeline Studio</title><meta name="description" content="拆解 Timeline Studio 本地优先浏览器 AI 视频编辑器的 Worker、模型缓存、多轨时间线与导出架构。"><meta property="og:title" content="把 AI 视频编辑器装进浏览器:本地优先架构的六个关键决策"><meta property="og:image" content="/articles/assets/local-first-architecture.webp"><link rel="stylesheet" href="/articles/article.css"></head><body><header class="site-header"><nav class="nav"><a class="brand" href="/"><span class="brand-mark">TS</span>Timeline Studio</a><div class="nav-links"><a href="/articles/">技术文章</a><a href="https://github.com/MartinDelophy/ai-video-editor">GitHub ↗</a></div></nav></header><main><header class="hero"><p class="eyebrow">Local-first Architecture</p><h1>把 AI 视频编辑器装进浏览器:本地优先架构的六个关键决策</h1><p class="deck">浏览器 AI 的难点从来不只是“把模型加载进来”。真正的挑战,是把推理、时间线、缓存、渲染与失败恢复组合成一个可信的创作工具。</p><div class="meta"><span>Timeline Studio 工程手记</span><span>2026-07-17</span><span>约 12 分钟</span></div></header><div class="hero-image"><img src="/articles/assets/local-first-architecture.webp" alt="浏览器端本地优先 AI 视频编辑器系统概念图"></div><div class="layout"><article class="article"><p class="lede">Timeline Studio 是一个 React 19 + Vite 6 构建的本地优先视频编辑器。语音合成、自动字幕、主体识别、数字人与视频导出都尽可能在用户设备内完成。本文不讨论“浏览器能不能跑 AI”,而是讨论如何让它跑得像一个产品。</p>
|
||||
<h2 id="why">01. 本地优先不是离线口号,而是一组架构约束</h2><p>把媒体留在浏览器里,首先解决的是隐私和上传等待:用户选择的原始视频不必先经过服务端。但代价也会立刻转移到客户端——数百 MB 的模型下载、不同设备的内存上限、执行后端差异,以及浏览器编码能力的不一致。</p><p>因此“本地优先”的准确含义不是所有资源都内嵌在安装包里,而是:<strong>媒体与核心计算默认留在本机,模型按需从固定版本地址获取,重复使用时命中浏览器缓存,任何云端依赖都必须显式可见。</strong></p><div class="callout"><p><strong>关键判断:</strong>把服务器成本移走,并不会让成本消失。它只是变成了下载、存储、内存、GPU 兼容性和更复杂的进度反馈。</p></div>
|
||||
<h2 id="runtime">02. 不追求“一个模型解决一切”</h2><p>不同任务对模型、量化方式和执行后端的要求不同。Timeline Studio 选择多条专用路径:中文与多语种语音走 Piper/VITS ONNX,英文语音走 Kokoro 82M q8,字幕使用 Whisper small q8,视觉理解使用 YOLOS tiny 与 MODNet,而数字人管线由 JoyVASA 和 LivePortrait 组合完成。</p><div class="diagram"><div class="flow"><div>输入媒体<br>File / Blob</div><div>专用 Worker<br>WASM / WebGPU</div><div>统一时间线<br>Clip Model</div><div>Canvas + Audio<br>导出</div></div></div><p>这里最重要的选择是<strong>延迟加载</strong>。用户打开编辑器时,不应该同时下载字幕、数字人、视觉分割和所有语音模型。功能面板被真正使用时才创建对应运行时;同一个会话中则复用热会话,避免重复初始化 ONNX 图。</p><pre><code>async function getDetector() {
|
||||
detectorPromise ??= pipeline("object-detection",
|
||||
"Xenova/yolos-tiny", { device: "wasm", dtype: "q8" });
|
||||
return detectorPromise;
|
||||
}</code></pre>
|
||||
<h2 id="workers">03. Worker 不只是性能优化,而是产品边界</h2><p>模型推理、音频解码、逐帧分析和编码任何一项都足以阻塞主线程。如果点击“生成字幕”后整个界面失去响应,那么即使模型最终给出正确结果,产品体验仍然是失败的。</p><p>项目把 ASR、视觉分析、数字人、画质增强和人声分离分散到独立 Worker。主线程只负责发送任务、接收结构化进度,并把完成结果转换成时间线资产。对大型 WebGPU 会话还需要串行创建,因为执行提供程序可能拒绝并发初始化。</p><p>Worker 同样提供了清晰的取消与错误边界:取消完整视频增强时,原片段保持不变;某个数字人关键帧出现非有限值或时间异常时,系统只重试该帧,并在必要时沿用上一张有效帧,而不是输出损坏纹理。</p>
|
||||
<h2 id="timeline">04. 时间线必须是 AI 结果的唯一归宿</h2><p>很多 AI Demo 的终点是一个下载按钮。编辑器不能这样工作:生成的语音要插入播放头位置,字幕需要与语音绑定,重叠片段要自动进入新轨道,移动和删除时还要保持关联。</p><p>Timeline Studio 把 AI 输出统一变成 <code>asset + clip</code>。界面、预览与导出都读取同一份时间模型。生成语音时不会替换上一个结果,而是在播放头位置创建新的 voice clip;对应字幕共享关联 ID,并根据解码后的真实音频时长对齐。</p><pre><code>voiceClip = {
|
||||
id, assetId, start, duration, volume,
|
||||
fadeIn, fadeOut, linkedCaptionId, captionSync: true
|
||||
};</code></pre><p>这个决定也解决了 WYSIWYG:字幕大小、智能裁切、贴纸、滤镜与转场不再有两份互相漂移的状态,而是在指定时间点解析同一个 clip 模型。</p>
|
||||
<h2 id="temporal">05. 视频 AI 的输出必须是时间数据</h2><p>对视频第一帧做一次主体检测,然后把结果应用到全片,是最容易实现、也最容易出错的方案。人物一移动,智能裁切、字幕避让和背景移除都会立刻失真。</p><p>项目会以自适应间隔预分析视频,保存带时间戳的 YOLOS 几何与 MODNet 蒙版。预览和导出在当前源时间解析最近的分析记录。长视频扩大采样间隔,以可控的精度损失换取有上限的推理时间与内存。</p><pre><code>temporalTrack = [
|
||||
{ time: 0.0, box: A, matte: A1 },
|
||||
{ time: 0.8, box: B, matte: B1 },
|
||||
{ time: 1.6, box: C, matte: C1 }
|
||||
];</code></pre>
|
||||
<h2 id="cache">06. 缓存要与版本绑定,导出要接受现实</h2><p>服务工作线程对模型资源使用 cache-first,对应用壳使用 network-first。模型 URL 固定到不可变 revision,避免缓存中的图与运行时代码悄悄漂移。用户也可以主动清理模型缓存,因为“本地”不等于可以无限占用磁盘。</p><p>导出侧同样采用分层策略:浏览器原生支持目标格式时走快速路径;需要 MP4 转码时再加载 FFmpeg WASM;如果转码失败,保留已成功渲染的 WebM,不让用户因最后一步兼容性问题失去全部工作。</p>
|
||||
<h2 id="lessons">结论:浏览器 AI 是系统工程</h2><p>模型准确率只是起点。一个可信的浏览器创作工具还需要明确的计算边界、可取消的 Worker、按需模型生命周期、时间化的视觉分析、统一的时间线语义、版本化缓存与保底导出。</p><p>这套架构不会让浏览器变成桌面工作站,但它证明了另一件更有价值的事:只要诚实地处理限制,复杂的 AI 媒体流程已经可以在一个链接里完成,并且不必默认交出用户的原始素材。</p><footer class="article-footer"><a class="next-card" href="/articles/liveportrait-webgpu-port/"><small>下一篇 · WebGPU 深潜</small><strong>5D GridSample 进不了浏览器之后:LivePortrait 移植实战 →</strong></a></footer></article><aside class="toc"><p class="toc-title">本文目录</p><a href="#why">本地优先的约束</a><a href="#runtime">多运行时策略</a><a href="#workers">Worker 边界</a><a href="#timeline">时间线模型</a><a href="#temporal">时间化视觉数据</a><a href="#cache">缓存与导出</a><a href="#lessons">工程结论</a></aside></div></main></body></html>
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -6,4 +6,7 @@
|
||||
<url><loc>https://video-editor.ai-creator.top/faq/</loc><lastmod>2026-07-16</lastmod><changefreq>monthly</changefreq><priority>0.8</priority></url>
|
||||
<url><loc>https://video-editor.ai-creator.top/privacy/</loc><lastmod>2026-07-16</lastmod><changefreq>yearly</changefreq><priority>0.5</priority></url>
|
||||
<url><loc>https://video-editor.ai-creator.top/about/</loc><lastmod>2026-07-16</lastmod><changefreq>monthly</changefreq><priority>0.7</priority></url>
|
||||
<url><loc>https://video-editor.ai-creator.top/articles/</loc><lastmod>2026-07-17</lastmod><changefreq>monthly</changefreq><priority>0.8</priority></url>
|
||||
<url><loc>https://video-editor.ai-creator.top/articles/local-first-browser-ai-video-editor/</loc><lastmod>2026-07-17</lastmod><changefreq>monthly</changefreq><priority>0.8</priority></url>
|
||||
<url><loc>https://video-editor.ai-creator.top/articles/liveportrait-webgpu-port/</loc><lastmod>2026-07-17</lastmod><changefreq>monthly</changefreq><priority>0.8</priority></url>
|
||||
</urlset>
|
||||
+31
-175
@@ -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}
|
||||
/>
|
||||
|
||||
<VoicePanel
|
||||
t={t}
|
||||
activeTool={activeTool}
|
||||
captionVoiceFocusRequest={captionVoiceFocusRequest}
|
||||
status={status}
|
||||
statusText={statusText}
|
||||
voiceTab={voiceTab}
|
||||
@@ -958,12 +820,6 @@ export function App() {
|
||||
visualLocalTime={visualLocalTime}
|
||||
visualTimelineStart={selectedVisualRange?.start ?? 0}
|
||||
updateSelectedVisualEffects={updateSelectedVisualEffects}
|
||||
remasterJob={remasterJob}
|
||||
remasterQuality={remasterQuality}
|
||||
setRemasterQuality={setRemasterQuality}
|
||||
enhanceSelectedVisualFrame={enhanceSelectedVisualFrame}
|
||||
enhanceSelectedVisualClip={enhanceSelectedVisualClip}
|
||||
clearSelectedVisualEnhancement={clearSelectedVisualEnhancement}
|
||||
selectedFilterId={selectedFilterId}
|
||||
setSelectedFilterId={setSelectedFilterId}
|
||||
trOption={trOption}
|
||||
@@ -990,6 +846,7 @@ export function App() {
|
||||
selectedTrack={selectedTrack}
|
||||
setSelectedTrack={setSelectedTrack}
|
||||
setActiveTool={setActiveTool}
|
||||
requestCaptionVoiceFocus={() => setCaptionVoiceFocusRequest((request) => request + 1)}
|
||||
trackVisibility={trackVisibility}
|
||||
toggleTrackVisibility={toggleTrackVisibility}
|
||||
trackLocks={trackLocks}
|
||||
@@ -1060,7 +917,6 @@ export function App() {
|
||||
|
||||
<AssetDragPreview preview={assetDragPreview} t={t} />
|
||||
<ExportProgressOverlay exporting={exporting} percent={exportPercent} phase={exportPhase} elapsedSeconds={exportElapsedSeconds} t={t} />
|
||||
<RemasterProgressOverlay job={remasterJob} onCancel={cancelRemasterEnhancement} t={t} />
|
||||
{shouldShowLanguageIntro ? (
|
||||
<LanguageIntro t={t} closing={introClosing} onChoose={chooseInterfaceLanguage} />
|
||||
) : null}
|
||||
|
||||
@@ -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 ? (
|
||||
<div className="visual-media-layer" style={visualMaskStyle}>
|
||||
@@ -276,11 +263,6 @@ export function PreviewStage({
|
||||
onDoubleClick={() => setActiveTool("caption")}
|
||||
/>
|
||||
) : null}
|
||||
{captionDraft ? (
|
||||
<form className="inline-caption-editor" style={{ left: `${captionDraft.x}%`, top: `${captionDraft.y}%` }} onSubmit={(event) => { event.preventDefault(); commitCaptionDraft(); }}>
|
||||
<input autoFocus value={captionDraft.text} placeholder={t("typeCaptionHere", "在此输入字幕…")} onChange={(event) => 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); }} />
|
||||
</form>
|
||||
) : null}
|
||||
{selectedSticker.src ? (
|
||||
<img className="sticker-overlay is-image" src={selectedSticker.src} alt="" draggable={false} />
|
||||
) : selectedSticker.text ? (
|
||||
|
||||
+68
-22
@@ -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({
|
||||
<span ref={zoomReadoutRef} className="zoom-readout" data-testid="timeline-zoom-readout">{zoomReadout}</span>
|
||||
<IconButton
|
||||
label={t("fitTimeline")}
|
||||
active={Math.abs(localTimelineZoom - TIMELINE_MIN_ZOOM) < 0.001}
|
||||
onClick={() => adjustTimelineZoom(TIMELINE_MIN_ZOOM)}
|
||||
active={Math.abs(localTimelineZoom - fitTimelineZoom) < 0.001}
|
||||
onClick={() => adjustTimelineZoom(fitTimelineZoom)}
|
||||
>
|
||||
<MonitorPlay size={17} />
|
||||
</IconButton>
|
||||
@@ -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({
|
||||
</div>
|
||||
) : null}
|
||||
{contextMenu ? (
|
||||
<div className="timeline-context-menu" role="menu" aria-label="时间线右键菜单" style={{ left: contextMenu.x, top: contextMenu.y }} onPointerDown={(event) => event.stopPropagation()}>
|
||||
<div className="timeline-context-heading">{contextMenu.kind === "clip" ? "片段操作" : "轨道操作"}<span>{contextMenu.track}</span></div>
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(() => openTrackPanel(contextMenu.track))}><SlidersHorizontal size={16} />打开对应面板</button>
|
||||
<div className="timeline-context-menu" role="menu" aria-label={t("timelineContextMenu")} style={{ left: contextMenu.x, top: contextMenu.y }} onPointerDown={(event) => event.stopPropagation()}>
|
||||
<div className="timeline-context-heading">{contextMenu.kind === "clip" ? t("clipActions") : t("trackActions")}<span>{t({ image: "imageTrack", caption: "caption", sticker: "stickerTrack", source: "sourceTrack", voice: "voiceTrack", music: "musicTrack" }[contextMenu.track], contextMenu.track)}</span></div>
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(() => openTrackPanel(contextMenu.track))}><SlidersHorizontal size={16} />{t("openTrackPanel")}</button>
|
||||
{contextMenu.kind === "clip" ? (
|
||||
<>
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(handleCutTrack)}><Scissors size={16} />在播放头处分割</button>
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(handleDuplicateTrack)}><CopySimple size={16} />复制片段</button>
|
||||
{contextMenu.track === "caption" ? (
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(() => {
|
||||
openTrackPanel("caption");
|
||||
requestCaptionVoiceFocus?.();
|
||||
})}><Waveform size={16} />{t("aiVoice")}</button>
|
||||
) : null}
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(handleCutTrack)}><Scissors size={16} />{t("splitAtPlayhead")}</button>
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(handleDuplicateTrack)}><CopySimple size={16} />{t("duplicateClip")}</button>
|
||||
<div className="timeline-context-divider" />
|
||||
<button className="is-danger" type="button" role="menuitem" onClick={() => runContextAction(handleDeleteTrack)}><Trash size={16} />删除片段</button>
|
||||
<button className="is-danger" type="button" role="menuitem" onClick={() => runContextAction(handleDeleteTrack)}><Trash size={16} />{t("deleteClip")}</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{["image", "caption"].includes(contextMenu.track) ? <button type="button" role="menuitem" onClick={() => runContextAction(handleAddSegment)}><PlusCircle size={16} />新增片段</button> : null}
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(() => toggleTrackVisibility(contextMenu.track))}>{trackVisibility[contextMenu.track] ? <EyeSlash size={16} /> : <Eye size={16} />}{trackVisibility[contextMenu.track] ? "隐藏轨道" : "显示轨道"}</button>
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(() => toggleTrackLock(contextMenu.track))}>{trackLocks[contextMenu.track] ? <LockKeyOpen size={16} /> : <LockKey size={16} />}{trackLocks[contextMenu.track] ? "解锁轨道" : "锁定轨道"}</button>
|
||||
{["image", "caption"].includes(contextMenu.track) ? <button type="button" role="menuitem" onClick={() => runContextAction(() => handleAddSegment(contextMenu.targetTime))}><PlusCircle size={16} />{t("addClip")}</button> : null}
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(() => toggleTrackVisibility(contextMenu.track))}>{trackVisibility[contextMenu.track] ? <EyeSlash size={16} /> : <Eye size={16} />}{t(trackVisibility[contextMenu.track] ? "hideTrack" : "showTrack")}</button>
|
||||
<button type="button" role="menuitem" onClick={() => runContextAction(() => toggleTrackLock(contextMenu.track))}>{trackLocks[contextMenu.track] ? <LockKeyOpen size={16} /> : <LockKey size={16} />}{t(trackLocks[contextMenu.track] ? "unlockTrack" : "lockTrack")}</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -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({
|
||||
<div className="caption-context-empty">
|
||||
<ClosedCaptioning size={28} weight="duotone" />
|
||||
<strong>{t("noCaptionSegments")}</strong>
|
||||
<span>{t("captionEmptyHint", "选择时间线字幕片段后,这里会同步编辑。")}</span>
|
||||
<span>{t("captionEmptyHint", "字幕片段可拖动到字幕轨道,并在这里同步编辑。")}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -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 (
|
||||
<aside className={`voice-panel ${isCaptionContext ? "is-caption-context" : ""} ${isAvatarContext ? "is-avatar-context" : ""} ${isAudioClipContext ? "is-audio-clip-context" : ""} ${isVisualContext ? "is-visual-context" : ""}`}>
|
||||
<aside ref={panelRef} className={`voice-panel ${isCaptionContext ? "is-caption-context" : ""} ${isAvatarContext ? "is-avatar-context" : ""} ${isAudioClipContext ? "is-audio-clip-context" : ""} ${isVisualContext ? "is-visual-context" : ""}`}>
|
||||
<div className="panel-title-row">
|
||||
<h1>{title}</h1>
|
||||
<span className={`status-pill ${isCaptionContext ? "done" : status}`}>
|
||||
@@ -377,8 +390,31 @@ export function VoicePanel({
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{isCaptionContext ? (
|
||||
<div className="tabs compact caption-context-tabs" role="tablist" aria-label={t("captionTools", "字幕工具")}>
|
||||
<button
|
||||
className={captionPanelTab === "caption" ? "is-active" : ""}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={captionPanelTab === "caption"}
|
||||
onClick={() => setCaptionPanelTab("caption")}
|
||||
>
|
||||
{t("caption", "字幕")}
|
||||
</button>
|
||||
<button
|
||||
className={captionPanelTab === "voice" ? "is-active" : ""}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={captionPanelTab === "voice"}
|
||||
onClick={() => setCaptionPanelTab("voice")}
|
||||
>
|
||||
{t("aiVoice", "AI 配音")}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="voice-tab-body">
|
||||
{isVisualContext ? (
|
||||
{isVisualContext && selectedVisualSegment ? (
|
||||
<VisualEffectsPanel
|
||||
contextMode
|
||||
t={t}
|
||||
@@ -390,15 +426,16 @@ export function VoicePanel({
|
||||
trOption={trOption}
|
||||
onSelectFilter={(id) => { setSelectedFilterId(id); notify(t("effectApplied")); }}
|
||||
sourceAudioLinked={sourceAudioLinked}
|
||||
enhancementJob={remasterJob}
|
||||
enhancementQuality={remasterQuality}
|
||||
onEnhancementQualityChange={setRemasterQuality}
|
||||
onEnhance={enhanceSelectedVisualFrame}
|
||||
onEnhanceClip={enhanceSelectedVisualClip}
|
||||
onClearEnhancement={clearSelectedVisualEnhancement}
|
||||
/>
|
||||
) : null}
|
||||
{isCaptionContext ? (
|
||||
{isVisualContext && !selectedVisualSegment ? (
|
||||
<div className="visual-context-empty">
|
||||
<ImageSquare size={30} weight="duotone" />
|
||||
<strong>{t("visualSelectClip")}</strong>
|
||||
<span>{t("previewEmptyTitle")}</span>
|
||||
</div>
|
||||
) : null}
|
||||
{isCaptionContext && captionPanelTab === "caption" ? (
|
||||
<CaptionContextPanel
|
||||
t={t}
|
||||
captionSegments={captionSegments}
|
||||
@@ -418,6 +455,41 @@ export function VoicePanel({
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{isCaptionContext && captionPanelTab === "voice" ? (
|
||||
<div className="caption-voice-panel">
|
||||
<p className="caption-voice-hint">
|
||||
{selectedCaptionSegment
|
||||
? t("captionVoiceHint", "仅为当前选中的字幕片段生成配音,并自动对齐到片段起点。")
|
||||
: t("captionVoiceEmptyHint", "请先在时间线中选择一个字幕片段。")}
|
||||
</p>
|
||||
<VoiceSynthesisPanel
|
||||
script={selectedCaptionSegment?.text ?? ""}
|
||||
updateScript={(text) => selectedCaptionSegment && updateCaptionSegmentText(selectedCaptionSegment.id, text)}
|
||||
selectedVoiceId={selectedVoiceId}
|
||||
setSelectedVoiceId={setSelectedVoiceId}
|
||||
selectedVoice={selectedVoice}
|
||||
filteredVoices={filteredVoices}
|
||||
voiceFilter={voiceFilter}
|
||||
setVoiceFilter={setVoiceFilter}
|
||||
showVoiceFilter={showVoiceFilter}
|
||||
setShowVoiceFilter={setShowVoiceFilter}
|
||||
speed={speed}
|
||||
setSpeed={setSpeed}
|
||||
volume={volume}
|
||||
setVolume={setVolume}
|
||||
status={status}
|
||||
progressPercent={progressPercent}
|
||||
audioBlob={selectedCaptionAudioSegment?.blob ?? null}
|
||||
audioUrl={selectedCaptionAudioSegment?.url ?? ""}
|
||||
generateVoiceover={() => selectedCaptionSegment && generateVoiceover(selectedCaptionSegment)}
|
||||
downloadBlob={downloadBlob}
|
||||
favoriteVoiceIds={favoriteVoiceIds}
|
||||
setFavoriteVoiceIds={setFavoriteVoiceIds}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{isAvatarContext ? <AvatarContextPanel t={t} hasVisual={hasVisual} visualType={visualType} audioBlob={audioBlob} audioDuration={audioDuration} captionSegments={captionSegments} selectedVoice={selectedVoice} avatarJob={avatarJob} generateAvatarAcceptanceFrame={generateAvatarAcceptanceFrame} /> : null}
|
||||
|
||||
{isAudioClipContext ? <AudioClipContextPanel t={t} segment={selectedAudioSegment} updateAudioSegment={updateAudioSegment} toggleAudioSegmentReverse={toggleAudioSegmentReverse} deleteAudioSegment={deleteAudioSegment} downloadBlob={downloadBlob} /> : null}
|
||||
|
||||
+49
-28
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
|
||||
import {
|
||||
BoundingBox,
|
||||
@@ -31,7 +32,6 @@ import {
|
||||
VOICES,
|
||||
} from "../config/editor.js";
|
||||
import { APP_LANGUAGES } from "../i18n.js";
|
||||
import { translateRemasterPhase } from "../lib/remasterProgress.js";
|
||||
import { formatClock, formatTime, getSegmentStartTime } from "../lib/timeline.js";
|
||||
import { hasVisualPropertyKeyframe, normalizeVisualKeyframes, resolveVisualTransform } from "../lib/visualEffects.js";
|
||||
import { Popover } from "./ui.jsx";
|
||||
@@ -325,8 +325,8 @@ export function ToolPanel(props) {
|
||||
<div className="caption-style-heading"><strong>{t("captionStyle")}</strong><span>{t("captionStyleHint")}</span></div>
|
||||
<div className="caption-style-presets">
|
||||
<button type="button" className={captionStyle.backgroundOpacity === 0 && captionStyle.borderWidth === 0 ? "is-active" : ""} onClick={() => setCaptionStyle((style) => ({ ...style, effect: "normal", backgroundOpacity: 0, borderWidth: 0, shadowOpacity: 0 }))}>{t("captionPresetNone")}</button>
|
||||
{[['normal', t('captionPresetClassic')], ['neon', t('captionPresetNeon')], ['bubble', t('captionPresetBubble')]].map(([effect, label]) => (
|
||||
<button key={effect} type="button" className={captionStyle.effect === effect ? "is-active" : ""} onClick={() => setCaptionStyle((style) => ({ ...style, effect, ...(effect === 'neon' ? { backgroundOpacity: 0.18, borderWidth: 1, borderColor: '#35f0dd' } : effect === 'bubble' ? { backgroundOpacity: 0.88, borderWidth: 0, radius: 18 } : {}) }))}>{label}</button>
|
||||
{[['normal', t('captionPresetClassic')], ['neon', t('captionPresetNeon')]].map(([effect, label]) => (
|
||||
<button key={effect} type="button" className={captionStyle.effect === effect ? "is-active" : ""} onClick={() => setCaptionStyle((style) => ({ ...style, effect, ...(effect === 'neon' ? { backgroundOpacity: 0.18, borderWidth: 1, borderColor: '#35f0dd' } : {}) }))}>{label}</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="caption-color-row">
|
||||
@@ -568,7 +568,7 @@ export function ToolPanel(props) {
|
||||
);
|
||||
}
|
||||
|
||||
export function VisualEffectsPanel({ t, segment, localTime, onChange, onSeek, selectedFilterId, trOption, onSelectFilter, contextMode = false, sourceAudioLinked = false, enhancementJob = null, enhancementQuality = "fast", onEnhancementQualityChange, onEnhance, onEnhanceClip, onClearEnhancement }) {
|
||||
export function VisualEffectsPanel({ t, segment, localTime, onChange, onSeek, selectedFilterId, trOption, onSelectFilter, contextMode = false, sourceAudioLinked = false }) {
|
||||
const [activeTab, setActiveTab] = useState("transform");
|
||||
const keyframes = normalizeVisualKeyframes(segment?.keyframes ?? []);
|
||||
const transform = resolveVisualTransform(keyframes, localTime);
|
||||
@@ -578,18 +578,12 @@ export function VisualEffectsPanel({ t, segment, localTime, onChange, onSeek, se
|
||||
const isVideo = segment?.type === "video";
|
||||
const playbackRate = Math.max(0.25, Math.min(4, Number(segment?.playbackRate) || 1));
|
||||
const sourceDuration = Math.max(0, Number(segment?.sourceDuration) || (Number(segment?.duration) || 0) * playbackRate);
|
||||
const enhancement = segment?.enhancement ?? null;
|
||||
const fullClipEnhanced = enhancement?.mode === "remaster-drunet-full";
|
||||
const hasEnhancement = Boolean(fullClipEnhanced || enhancement?.previewUrl);
|
||||
const enhancementRunning = Boolean(enhancementJob?.running && enhancementJob.segmentId === segment?.id);
|
||||
const enhancementBackend = enhancementRunning ? enhancementJob?.backend : enhancement?.backend;
|
||||
const updateTransform = (key, value) => onChange?.({ propertyKeyframe: { time: localTime, key, value } });
|
||||
const tabs = [
|
||||
["transform", t("visualTabTransform")],
|
||||
["mask", t("visualTabMask")],
|
||||
["speed", t("visualTabSpeed")],
|
||||
["effects", t("visualTabEffects")],
|
||||
["ai", t("visualTabAi")],
|
||||
];
|
||||
return (
|
||||
<div className={`tool-panel visual-effects-panel ${contextMode ? "is-context-mode" : ""}`}>
|
||||
@@ -630,19 +624,6 @@ export function VisualEffectsPanel({ t, segment, localTime, onChange, onSeek, se
|
||||
</> : <div className="empty-state visual-speed-empty">{t("visualSpeedImageHint")}</div>}
|
||||
</section> : null}
|
||||
{activeTab === "effects" ? <VisualChoicePanel title={t("visualEffects")} kind="effect" options={EFFECT_OPTIONS} selectedId={selectedFilterId} trOption={trOption} onSelect={onSelectFilter} /> : null}
|
||||
{activeTab === "ai" ?
|
||||
<section className="visual-editor-card remaster-card">
|
||||
<div className="visual-editor-heading"><strong>{t("remasterTitle")}</strong><em>{t("remasterExperimental")}</em></div>
|
||||
<div className="remaster-model-row"><span><strong>Remaster DRUNet</strong><em>{t("remasterModelMeta")}</em></span><i className={hasEnhancement ? "is-ready" : ""}>{fullClipEnhanced ? t("remasterFullReadyBadge") : enhancement?.previewUrl ? t("remasterReadyBadge") : t("remasterNotRun")}</i></div>
|
||||
{isVideo ? <div className="remaster-performance-row"><div className="visual-speed-presets" aria-label={t("remasterPerformanceMode")}><button type="button" className={enhancementQuality === "fast" ? "is-active" : ""} disabled={enhancementRunning} onClick={() => onEnhancementQualityChange?.("fast")}>{t("remasterFastMode")}</button><button type="button" className={enhancementQuality === "quality" ? "is-active" : ""} disabled={enhancementRunning} onClick={() => onEnhancementQualityChange?.("quality")}>{t("remasterQualityMode")}</button></div><span className={`remaster-backend ${enhancementBackend === "webgpu" ? "is-gpu" : enhancementBackend ? "is-cpu" : ""}`}>{enhancementBackend === "webgpu" ? t("remasterGpuActive") : enhancementBackend === "wasm" ? t("remasterCpuFallback") : t("remasterGpuAuto")}</span></div> : null}
|
||||
{hasEnhancement ? <label className="switch-row remaster-preview-toggle"><input type="checkbox" checked={enhancement.enabled !== false} onChange={(event) => onChange?.({ enhancementEnabled: event.target.checked })} />{fullClipEnhanced ? t("remasterUseEnhanced") : t("remasterShowResult")}</label> : null}
|
||||
{enhancementRunning ? <div className="remaster-progress" role="status" aria-live="polite"><span><i style={{ width: `${Math.max(2, enhancementJob.progress || 0)}%` }} /></span><small>{translateRemasterPhase(enhancementJob, t)} · {Math.round(enhancementJob.progress || 0)}%</small></div> : null}
|
||||
{isVideo ? <button className="panel-primary" type="button" disabled={enhancementRunning || !onEnhanceClip} onClick={onEnhanceClip}>{enhancementRunning && enhancementJob?.mode === "clip" ? t("remasterProcessing") : fullClipEnhanced ? t("remasterRerunClip") : t("remasterEnhanceClip")}</button> : null}
|
||||
<button className={isVideo ? "panel-secondary" : "panel-primary"} type="button" disabled={enhancementRunning || !onEnhance || fullClipEnhanced} onClick={onEnhance}>{enhancementRunning && enhancementJob?.mode === "frame" ? t("remasterProcessing") : t("remasterFramePreview")}</button>
|
||||
{hasEnhancement ? <div className="remaster-result-meta"><span>{fullClipEnhanced ? `${enhancement.totalFrames} ${t("remasterFramesShort")}` : `${enhancement.width}×${enhancement.height}`}</span><span>{fullClipEnhanced ? `${enhancement.frameRate} fps` : `${Math.max(0, enhancement.inferenceMs || 0)} ms`}</span><button type="button" onClick={onClearEnhancement}>{t("remasterClear")}</button></div> : null}
|
||||
<p className="visual-speed-hint">{segment?.type === "video" ? t("remasterVideoHint") : t("remasterImageHint")}</p>
|
||||
</section>
|
||||
: null}
|
||||
</>}
|
||||
</div>
|
||||
);
|
||||
@@ -1089,6 +1070,31 @@ export function VoiceSynthesisPanel({
|
||||
t,
|
||||
}) {
|
||||
const voiceLanguages = useMemo(() => [...new Set(VOICES.map((voice) => voice.language))], []);
|
||||
const voiceSampleRef = useRef(null);
|
||||
const previousVoiceSampleIdRef = useRef(selectedVoiceId);
|
||||
|
||||
const selectAndPlayVoiceSample = (voice) => {
|
||||
previousVoiceSampleIdRef.current = voice.id;
|
||||
flushSync(() => setSelectedVoiceId(voice.id));
|
||||
const player = voiceSampleRef.current;
|
||||
if (!player) return;
|
||||
player.pause();
|
||||
player.load();
|
||||
delete player.dataset.autoplayStarted;
|
||||
delete player.dataset.autoplayError;
|
||||
player.play()
|
||||
.then(() => { player.dataset.autoplayStarted = "true"; })
|
||||
.catch((error) => { player.dataset.autoplayError = error.name || "PlaybackError"; });
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const player = voiceSampleRef.current;
|
||||
if (!player) return;
|
||||
if (previousVoiceSampleIdRef.current === selectedVoiceId) return;
|
||||
previousVoiceSampleIdRef.current = selectedVoiceId;
|
||||
player.pause();
|
||||
player.load();
|
||||
}, [selectedVoiceId]);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -1124,7 +1130,7 @@ export function VoiceSynthesisPanel({
|
||||
setVoiceFilter(filter);
|
||||
if (filter !== "all") {
|
||||
const firstVoiceForLanguage = VOICES.find((voice) => voice.language === filter);
|
||||
if (firstVoiceForLanguage) setSelectedVoiceId(firstVoiceForLanguage.id);
|
||||
if (firstVoiceForLanguage) selectAndPlayVoiceSample(firstVoiceForLanguage);
|
||||
}
|
||||
setShowVoiceFilter(false);
|
||||
}}
|
||||
@@ -1144,7 +1150,7 @@ export function VoiceSynthesisPanel({
|
||||
className={`voice-card ${voice.id === selectedVoiceId ? "is-selected" : ""}`}
|
||||
type="button"
|
||||
key={voice.id}
|
||||
onClick={() => setSelectedVoiceId(voice.id)}
|
||||
onClick={() => selectAndPlayVoiceSample(voice)}
|
||||
>
|
||||
<span className="avatar">
|
||||
<MicrophoneStage size={17} weight="fill" />
|
||||
@@ -1161,7 +1167,7 @@ export function VoiceSynthesisPanel({
|
||||
</div>
|
||||
|
||||
<div className="model-row">
|
||||
<span>{selectedVoice.detail}</span>
|
||||
<span title={selectedVoice.detail}>{selectedVoice.detail}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
@@ -1170,10 +1176,25 @@ export function VoiceSynthesisPanel({
|
||||
)
|
||||
}
|
||||
>
|
||||
{favoriteVoiceIds.includes(selectedVoiceId) ? t("saved") : t("favoriteVoice")}
|
||||
{favoriteVoiceIds.includes(selectedVoiceId) ? t("saved") : t("favorite")}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="voice-sample-preview">
|
||||
<div>
|
||||
<strong>{t("voiceSampleTitle", "音色样音")}</strong>
|
||||
<span>{selectedVoice.name} · {t("voiceSampleHint", "切换音色后试听对应的预生成样音")}</span>
|
||||
</div>
|
||||
<audio
|
||||
ref={voiceSampleRef}
|
||||
data-testid="voice-sample-player"
|
||||
data-voice-id={selectedVoice.id}
|
||||
controls
|
||||
preload="metadata"
|
||||
src={selectedVoice.sampleUrl}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="slider-field">
|
||||
<div>
|
||||
<label htmlFor="speed">{t("speed")}</label>
|
||||
@@ -1207,7 +1228,7 @@ export function VoiceSynthesisPanel({
|
||||
</div>
|
||||
{audioBlob && audioUrl ? (
|
||||
<div className="generated-voice-result" aria-live="polite">
|
||||
<div><Check size={18} weight="bold" /><span><strong>{t("voiceAddedToTimeline", "已加入配音时间线")}</strong><em>{t("voicePreviewHint", "可立即试听,时间线片段可继续调整")}</em></span></div>
|
||||
<div><Check size={18} weight="bold" /><span><strong>{t("voiceAddedToTimeline", "已加入配音时间线")}</strong><em>{t("voicePreviewHint", "试听本次已生成的时间线配音")}</em></span></div>
|
||||
<audio controls preload="metadata" src={audioUrl} />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
+10
-1
@@ -11,7 +11,7 @@ import {
|
||||
export { MODEL_ID, AUTOMATIC_CAPTION_MODEL_ID, AUTOMATIC_CAPTION_MODEL_LABEL } from "./models.js";
|
||||
|
||||
export const SAMPLE_IMAGE = "/assets/sample-portrait.png";
|
||||
export const DEFAULT_TIMELINE_DURATION_SECONDS = 30 * 60;
|
||||
export const DEFAULT_TIMELINE_DURATION_SECONDS = 10;
|
||||
export const MAX_TIMELINE_DURATION_SECONDS = 24 * 60 * 60;
|
||||
export const IMAGE_SEGMENT_SECONDS = 2;
|
||||
export const MIN_VISUAL_SEGMENT_SECONDS = 0.5;
|
||||
@@ -74,6 +74,7 @@ export const VOICES = [
|
||||
gender: "自然女声",
|
||||
engine: "piper",
|
||||
badge: "推荐",
|
||||
sampleUrl: "/assets/voice-samples/zh_CN-xiao_ya-medium.mp3",
|
||||
},
|
||||
{
|
||||
id: "zh_CN-chaowen-medium",
|
||||
@@ -83,6 +84,7 @@ export const VOICES = [
|
||||
gender: "自然人声",
|
||||
engine: "piper",
|
||||
badge: "ONNX",
|
||||
sampleUrl: "/assets/voice-samples/zh_CN-chaowen-medium.mp3",
|
||||
},
|
||||
{
|
||||
id: "af_heart",
|
||||
@@ -92,6 +94,7 @@ export const VOICES = [
|
||||
gender: "Warm female",
|
||||
engine: "kokoro",
|
||||
badge: "ONNX",
|
||||
sampleUrl: "/assets/voice-samples/af_heart.mp3",
|
||||
},
|
||||
{
|
||||
id: "am_fenrir",
|
||||
@@ -101,6 +104,7 @@ export const VOICES = [
|
||||
gender: "Steady male",
|
||||
engine: "kokoro",
|
||||
badge: "ONNX",
|
||||
sampleUrl: "/assets/voice-samples/am_fenrir.mp3",
|
||||
},
|
||||
{
|
||||
id: "de_DE-thorsten-medium",
|
||||
@@ -110,6 +114,7 @@ export const VOICES = [
|
||||
gender: "Natural male",
|
||||
engine: "piper",
|
||||
badge: "ONNX",
|
||||
sampleUrl: "/assets/voice-samples/de_DE-thorsten-medium.mp3",
|
||||
},
|
||||
{
|
||||
id: "es_ES-davefx-medium",
|
||||
@@ -119,6 +124,7 @@ export const VOICES = [
|
||||
gender: "Natural male",
|
||||
engine: "piper",
|
||||
badge: "ONNX",
|
||||
sampleUrl: "/assets/voice-samples/es_ES-davefx-medium.mp3",
|
||||
},
|
||||
{
|
||||
id: "fr_FR-siwis-medium",
|
||||
@@ -128,6 +134,7 @@ export const VOICES = [
|
||||
gender: "Natural voice",
|
||||
engine: "piper",
|
||||
badge: "ONNX",
|
||||
sampleUrl: "/assets/voice-samples/fr_FR-siwis-medium.mp3",
|
||||
},
|
||||
{
|
||||
id: "it_IT-riccardo-x_low",
|
||||
@@ -137,6 +144,7 @@ export const VOICES = [
|
||||
gender: "Natural male",
|
||||
engine: "piper",
|
||||
badge: "ONNX",
|
||||
sampleUrl: "/assets/voice-samples/it_IT-riccardo-x_low.mp3",
|
||||
},
|
||||
{
|
||||
id: "pt_BR-faber-medium",
|
||||
@@ -146,6 +154,7 @@ export const VOICES = [
|
||||
gender: "Natural male",
|
||||
engine: "piper",
|
||||
badge: "ONNX",
|
||||
sampleUrl: "/assets/voice-samples/pt_BR-faber-medium.mp3",
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ import { RATIO_OPTIONS } from "../config/editor.js";
|
||||
import { decodeWaveform } from "../lib/media.js";
|
||||
import { disposeVisionWorker } from "../lib/vision.js";
|
||||
import { disposeVocalSeparationWorker } from "../lib/vocalSeparation.js";
|
||||
import { disposeRemasterWorker } from "../lib/remasterEnhancement.js";
|
||||
import {
|
||||
getNearestRatioIdForSize,
|
||||
revokeVisionObjectUrls,
|
||||
@@ -157,11 +156,9 @@ export function useEditorLifecycle(d) {
|
||||
d.imageUrlRefs.current.forEach((url) => URL.revokeObjectURL(url));
|
||||
d.imageUrlRefs.current.clear();
|
||||
d.visionAbortControllerRef.current?.abort();
|
||||
d.remasterAbortControllerRef.current?.abort();
|
||||
d.visionObjectUrlsRef.current.forEach((urls) => revokeVisionObjectUrls(urls));
|
||||
d.visionObjectUrlsRef.current.clear();
|
||||
disposeVisionWorker();
|
||||
disposeRemasterWorker();
|
||||
disposeVocalSeparationWorker();
|
||||
d.voiceRecorderStreamRef.current?.getTracks().forEach((track) => track.stop());
|
||||
window.clearInterval(d.voiceRecorderTimerRef.current);
|
||||
|
||||
@@ -23,7 +23,6 @@ export function useEditorRefs() {
|
||||
previewCanvasRef: useRef(null),
|
||||
previewShellRef: useRef(null),
|
||||
previewVideoRef: useRef(null),
|
||||
remasterAbortControllerRef: useRef(null),
|
||||
projectFileInputRef: useRef(null),
|
||||
sourceAudioRef: useRef(null),
|
||||
sourceAudioUrlRef: useRef(""),
|
||||
|
||||
@@ -35,7 +35,7 @@ export function useEditorUiState() {
|
||||
const [showFileMenu, setShowFileMenu] = useState(false);
|
||||
const [compactRail, setCompactRail] = useState(false);
|
||||
const [selectedTrack, setSelectedTrack] = useState("image");
|
||||
const [timelineZoom, setTimelineZoom] = useState(0.25);
|
||||
const [timelineZoom, setTimelineZoom] = useState(1);
|
||||
const [trackVisibility, setTrackVisibility] = useState(DEFAULT_TRACK_VISIBILITY);
|
||||
const [trackLocks, setTrackLocks] = useState(DEFAULT_TRACK_LOCKS);
|
||||
const [timelineClipDrag, setTimelineClipDrag] = useState(null);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback } from "react";
|
||||
import { DEFAULT_SCRIPT, RATIO_OPTIONS, VOICES } from "../config/editor.js";
|
||||
import { DEFAULT_SCRIPT, DEFAULT_TIMELINE_DURATION_SECONDS, RATIO_OPTIONS, VOICES } from "../config/editor.js";
|
||||
import { decodeWaveform, downloadBlob } from "../lib/media.js";
|
||||
import { createProjectArchive, readProjectArchive, readProjectFileAsText } from "../lib/projectArchive.js";
|
||||
import { createCaptionSegments, getImageThumbnailCount, getVisualSegmentsTotal } from "../lib/timeline.js";
|
||||
@@ -44,6 +44,7 @@ export function useProjectFiles(deps) {
|
||||
deps.setSelectedSegmentId(""); deps.clearImageTrack(""); deps.clearAudioTrack("");
|
||||
deps.clearSourceAudioTrack(""); deps.clearMusicTrack(""); deps.setStickerSegments([]);
|
||||
deps.setSelectedStickerSegmentId(""); deps.clearAllVisionState(); deps.setCurrentTime(0);
|
||||
deps.setTimelineHorizon(DEFAULT_TIMELINE_DURATION_SECONDS); deps.setTimelineZoom(1);
|
||||
deps.setShowFileMenu(false); deps.notify("已新建空白工程");
|
||||
}, [deps]);
|
||||
|
||||
@@ -59,8 +60,10 @@ export function useProjectFiles(deps) {
|
||||
}
|
||||
const { payload, visualMedia, audio, sourceAudio, music } = archive;
|
||||
const data = payload.project;
|
||||
deps.setTimelineHorizon(DEFAULT_TIMELINE_DURATION_SECONDS);
|
||||
deps.setScript(typeof data.script === "string" ? data.script : DEFAULT_SCRIPT);
|
||||
const captions = Array.isArray(data.captionSegments) ? data.captionSegments : createCaptionSegments(data.script || DEFAULT_SCRIPT);
|
||||
deps.markTimelineViewRestored?.(Boolean(captions.length || data.visualSegments?.length || audio || sourceAudio || music));
|
||||
deps.setCaptionSegments(captions); deps.setSelectedSegmentId(captions[0]?.id ?? "");
|
||||
deps.setSelectedVoiceId(data.selectedVoiceId || VOICES[0].id); deps.setSpeed(Number(data.speed) || 1);
|
||||
deps.setVolume(Number(data.volume) || 1); deps.setRatioId(RATIO_OPTIONS.some((option) => option.id === data.ratioId) ? data.ratioId : "16:9");
|
||||
@@ -78,7 +81,7 @@ export function useProjectFiles(deps) {
|
||||
deps.setVisualSegments(visuals); deps.setImageDuration(getVisualSegmentsTotal(visuals));
|
||||
deps.setImageClipCount(getImageThumbnailCount(getVisualSegmentsTotal(visuals))); deps.setCurrentVisualAsset(visuals[0] || null);
|
||||
if (audio) { const decoded = await decodeWaveform(audio); deps.replaceAudio(audio, Number(data.audioDuration) || decoded.duration, decoded.peaks, "已恢复工程配音"); } else deps.clearAudioTrack("");
|
||||
if (sourceAudio) { const decoded = await decodeWaveform(sourceAudio); deps.replaceSourceAudio(sourceAudio, Number(data.sourceAudioDuration) || decoded.duration, decoded.peaks, data.sourceAudioName || "source-audio", "", Number(data.sourceAudioStart) || 0, data.sourceAudioAssetId || ""); } else deps.clearSourceAudioTrack("");
|
||||
if (sourceAudio) { const decoded = await decodeWaveform(sourceAudio); deps.replaceSourceAudio(sourceAudio, Number(data.sourceAudioDuration) || decoded.duration, decoded.peaks, data.sourceAudioName || "source-audio", "", Number(data.sourceAudioStart) || 0, data.sourceAudioAssetId || "", { focusAudio: false }); } else deps.clearSourceAudioTrack("");
|
||||
if (music) { const decoded = await decodeWaveform(music); deps.replaceMusic(music, Number(data.musicDuration) || decoded.duration, decoded.peaks, data.musicName || "background-music", ""); deps.setMusicStart(Math.max(0, Number(data.musicStart) || 0)); } else deps.clearMusicTrack("");
|
||||
deps.setMusicVolume(Number(data.musicVolume) || 0.35); deps.setSourceAudioVolume(Number(data.sourceAudioVolume) || 1);
|
||||
deps.setSourceAudioAssetId(data.sourceAudioAssetId || ""); deps.setSourceAudioLinked(data.sourceAudioLinked !== false);
|
||||
|
||||
@@ -8,7 +8,7 @@ export function useSourceAudioExtraction(d) {
|
||||
try {
|
||||
const blob = await extractAudioFromVideo(asset.blob, asset.name); d.setStatusText("解析视频原声波形"); d.setProgress(78);
|
||||
const decoded = await decodeWaveform(blob, 96); if (!decoded.duration) throw new Error("视频没有可识别的音频轨");
|
||||
d.replaceSourceAudio(blob, decoded.duration, decoded.peaks, `${asset.name.replace(/\.[^.]+$/, "")} 原声.wav`, "视频原声已分离到时间线", timelineStart, asset.id);
|
||||
d.replaceSourceAudio(blob, decoded.duration, decoded.peaks, `${asset.name.replace(/\.[^.]+$/, "")} 原声.wav`, "视频原声已分离到时间线", timelineStart, asset.id, { focusAudio: false });
|
||||
} catch (error) {
|
||||
console.warn(error); d.clearSourceAudioTrack(null); d.setStatus("ready"); d.setStatusText("视频未检测到可分离原声");
|
||||
d.setProgress(0); d.notify("视频画面已添加,但没有可分离的原声音轨");
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
VOICES,
|
||||
} from "../config/editor.js";
|
||||
import {
|
||||
estimateDuration,
|
||||
getCaptionTimeline,
|
||||
getSegmentIndexAtTime,
|
||||
getTimedSegmentIndexAtTime,
|
||||
@@ -21,6 +20,7 @@ import {
|
||||
} from "../lib/timeline.js";
|
||||
import { getVisionKey } from "../lib/vision.js";
|
||||
import { getVisualSourceTime } from "../lib/visualEffects.js";
|
||||
import { getTimelineProjectDuration } from "../lib/timelineScale.js";
|
||||
|
||||
export function useTimelineModel(d) {
|
||||
const selectedVoice = useMemo(
|
||||
@@ -83,21 +83,18 @@ export function useTimelineModel(d) {
|
||||
d.sourceAudioBlob ? (d.sourceAudioTimelineEnd ?? d.sourceAudioStart + d.sourceAudioDuration) : 0,
|
||||
d.musicBlob ? d.musicStart + d.musicDuration : 0,
|
||||
stickerDuration,
|
||||
estimateDuration(d.script),
|
||||
d.imageSrc ? d.imageDuration : 0,
|
||||
), [
|
||||
voiceTrackDuration, captionDuration, d.imageDuration, d.imageSrc, d.musicBlob,
|
||||
d.musicDuration, d.musicStart, d.script, d.sourceAudioBlob, d.sourceAudioDuration,
|
||||
d.musicDuration, d.musicStart, d.sourceAudioBlob, d.sourceAudioDuration,
|
||||
d.sourceAudioStart, d.sourceAudioTimelineEnd, stickerDuration,
|
||||
]);
|
||||
const timelineDuration = useMemo(() => Math.min(
|
||||
MAX_TIMELINE_DURATION_SECONDS,
|
||||
Math.max(
|
||||
d.timelineHorizon,
|
||||
DEFAULT_TIMELINE_DURATION_SECONDS,
|
||||
Math.ceil((estimatedDuration + 1) / 10) * 10,
|
||||
),
|
||||
), [estimatedDuration, d.timelineHorizon]);
|
||||
const timelineDuration = useMemo(() => estimatedDuration <= 0
|
||||
? DEFAULT_TIMELINE_DURATION_SECONDS
|
||||
: Math.min(
|
||||
MAX_TIMELINE_DURATION_SECONDS,
|
||||
Math.max(d.timelineHorizon, getTimelineProjectDuration(estimatedDuration)),
|
||||
), [estimatedDuration, d.timelineHorizon]);
|
||||
d.timelineDurationRef.current = timelineDuration;
|
||||
|
||||
const currentSegmentIndex = getSegmentIndexAtTime(
|
||||
|
||||
@@ -4,8 +4,8 @@ import { predictPiperVoice } from "../lib/piperVoiceRuntime.js";
|
||||
import { clearPiperCacheIfStorageTight, isPiperSymbolError, isStorageQuotaError, prepareTextForVoice, TtsInputError } from "../lib/ttsText.js";
|
||||
|
||||
export function useVoiceGeneration(d) {
|
||||
return useCallback(async () => {
|
||||
const rawText = d.script.trim();
|
||||
return useCallback(async (captionSegment = null) => {
|
||||
const rawText = (captionSegment?.text ?? d.script).trim();
|
||||
if (!rawText || d.status === "generating" || d.status === "captioning") return;
|
||||
let prepared;
|
||||
try { prepared = prepareTextForVoice(rawText, d.selectedVoice); }
|
||||
@@ -23,7 +23,15 @@ export function useVoiceGeneration(d) {
|
||||
d.setStatusText(d.selectedVoice.language === "中文"
|
||||
? d.t("ttsStatusLoadingChineseModel")
|
||||
: `Loading ${d.selectedVoice.language} Piper model…`);
|
||||
const progress = (event) => { if (event?.total) d.setProgress((current) => Math.max(current, Math.min(88, Math.max(12, Math.round((event.loaded / event.total) * 76))))); };
|
||||
const progress = (event) => {
|
||||
if (event?.backend) d.setStatusText(d.t(event.backend === "webgpu" ? "ttsStatusGeneratingWebGpu" : "ttsStatusGeneratingWasm"));
|
||||
if (event?.total) {
|
||||
d.setProgress((current) => Math.max(
|
||||
current,
|
||||
Math.min(88, Math.max(12, Math.round((event.loaded / event.total) * 76))),
|
||||
));
|
||||
}
|
||||
};
|
||||
const input = { text: prepared.text, voiceId: d.selectedVoice.id };
|
||||
try { blob = await predictPiperVoice(tts, input, progress); }
|
||||
catch (error) {
|
||||
@@ -32,13 +40,31 @@ export function useVoiceGeneration(d) {
|
||||
}
|
||||
} else {
|
||||
const { KokoroTTS } = await import("kokoro-js"); d.setStatusText(d.t("ttsStatusLoadingKokoro"));
|
||||
const tts = await KokoroTTS.from_pretrained(MODEL_ID, { dtype: "q8", device: "wasm",
|
||||
progress_callback: (event) => { if (event?.progress) d.setProgress((current) => Math.max(current, Math.min(86, Math.max(10, Math.round(event.progress))))); } });
|
||||
d.setStatusText(d.t("ttsStatusGeneratingEnglish"));
|
||||
blob = (await tts.generate(prepared.text, { voice: d.selectedVoice.id, speed: d.speed })).toBlob();
|
||||
const progressCallback = (event) => { if (event?.progress) d.setProgress((current) => Math.max(current, Math.min(86, Math.max(10, Math.round(event.progress))))); };
|
||||
let tts;
|
||||
if (globalThis.navigator?.gpu) {
|
||||
try {
|
||||
d.setStatusText(d.t("ttsStatusLoadingWebGpu"));
|
||||
tts = await KokoroTTS.from_pretrained(MODEL_ID, { dtype: "fp32", device: "webgpu", progress_callback: progressCallback });
|
||||
d.setStatusText(d.t("ttsStatusGeneratingWebGpu"));
|
||||
blob = (await tts.generate(prepared.text, { voice: d.selectedVoice.id, speed: d.speed })).toBlob();
|
||||
} catch (error) {
|
||||
console.warn("Kokoro WebGPU failed; retrying with WASM.", error);
|
||||
d.setStatusText(d.t("ttsStatusFallingBackWasm"));
|
||||
}
|
||||
}
|
||||
if (!blob) {
|
||||
tts = await KokoroTTS.from_pretrained(MODEL_ID, { dtype: "q8", device: "wasm", progress_callback: progressCallback });
|
||||
d.setStatusText(d.t("ttsStatusGeneratingWasm"));
|
||||
blob = (await tts.generate(prepared.text, { voice: d.selectedVoice.id, speed: d.speed })).toBlob();
|
||||
}
|
||||
}
|
||||
d.setStatusText(d.t("ttsStatusDecodingWaveform"));
|
||||
await d.commitAudio(blob, `${d.selectedVoice.name} · ${d.t("ttsGenerated")}`); d.notify(d.t("ttsNoticeGenerated"));
|
||||
await d.commitAudio(blob, `${d.selectedVoice.name} · ${d.t("ttsGenerated")}`, {
|
||||
captionSegment,
|
||||
script: rawText,
|
||||
});
|
||||
d.notify(d.t("ttsNoticeGenerated"));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
const message = error instanceof TtsInputError ? d.t(error.code)
|
||||
|
||||
+73
-2
@@ -26,6 +26,19 @@ const VISUAL_EDITOR_COPY = {
|
||||
vi: { visualSelectClip: "Chọn một clip trên rãnh Visuals", visualKeyframes: "Khung hình chính", visualFrames: "khung", visualScale: "Tỷ lệ", visualPositionX: "Vị trí ngang", visualPositionY: "Vị trí dọc", visualRotation: "Xoay", visualOpacity: "Độ mờ", visualDeleteKeyframe: "Xóa khung hình chính hiện tại", visualMask: "Mặt nạ", visualMaskResize: "Đổi kích thước mặt nạ", visualClipScoped: "Clip", visualMaskNone: "Không", visualMaskRectangle: "Chữ nhật", visualMaskRounded: "Bo góc", visualMaskCircle: "Tròn", visualFeather: "Làm mềm", visualHorizontal: "Ngang", visualVertical: "Dọc", visualWidth: "Rộng", visualHeight: "Cao", visualInvertMask: "Đảo mặt nạ", visualEffects: "Hiệu ứng hình ảnh" },
|
||||
};
|
||||
|
||||
const VISUAL_PANEL_TITLE_COPY = {
|
||||
zh: { visualPanelTitle: "画面" },
|
||||
en: { visualPanelTitle: "Visuals" },
|
||||
ja: { visualPanelTitle: "映像" },
|
||||
ko: { visualPanelTitle: "화면" },
|
||||
es: { visualPanelTitle: "Visuales" },
|
||||
fr: { visualPanelTitle: "Visuels" },
|
||||
de: { visualPanelTitle: "Bildmaterial" },
|
||||
pt: { visualPanelTitle: "Visuais" },
|
||||
th: { visualPanelTitle: "ภาพ" },
|
||||
vi: { visualPanelTitle: "Hình ảnh" },
|
||||
};
|
||||
|
||||
const VISUAL_MASK_SHAPE_COPY = {
|
||||
zh: { visualDiameter: "直径", visualCornerRadius: "圆角半径", visualMaskNoneHint: "选择一种蒙版后显示对应参数" },
|
||||
en: { visualDiameter: "Diameter", visualCornerRadius: "Corner radius", visualMaskNoneHint: "Choose a mask to show its parameters" },
|
||||
@@ -160,9 +173,36 @@ const REMASTER_PHASE_COPY = {
|
||||
vi: { remasterPhasePrepareFrame: "Đang chuẩn bị khung hiện tại", remasterPhaseReadClip: "Đang đọc clip video", remasterPhaseReuseVideo: "Đang đọc video từ trình phát", remasterPhaseDownloadModel: "Đang tải {model}", remasterPhaseInitModel: "Đang khởi tạo mô hình tăng cường", remasterPhaseGpuReady: "Đã bật WebGPU", remasterPhaseCpuFallback: "Không dùng được WebGPU; đang dùng CPU", remasterPhaseGpuFrame: "Đang tăng cường khung bằng GPU", remasterPhaseCpuFrame: "Đang tăng cường khung bằng CPU", remasterPhaseGeneratePreview: "Đang tạo khung đã tăng cường", remasterPhaseEnhancingFrame: "Đang tăng cường khung {current} / {total}", remasterPhaseFrameEnhanced: "Đã tăng cường {current} / {total} khung", remasterPhaseLoadEncoder: "Đang tải bộ mã hóa video", remasterPhaseEncodeVideo: "Đang mã hóa video tăng cường", remasterPhaseCreateAsset: "Đang tạo nội dung tăng cường" },
|
||||
};
|
||||
|
||||
const CONTEXT_PANEL_COPY = {
|
||||
zh: { timelineContextMenu: "时间线右键菜单", clipActions: "片段操作", trackActions: "轨道操作", openTrackPanel: "打开对应面板", splitAtPlayhead: "在播放头处分割", duplicateClip: "复制片段", deleteClip: "删除片段", addClip: "新增片段", hideTrack: "隐藏轨道", showTrack: "显示轨道", unlockTrack: "解锁轨道", lockTrack: "锁定轨道", voiceSampleTitle: "音色样音", voiceSampleHint: "切换音色后试听对应的预生成样音", voiceAddedToTimeline: "已加入配音时间线", voicePreviewHint: "试听本次已生成的时间线配音", captionTools: "字幕工具", captionVoiceHint: "仅为当前选中的字幕片段生成配音,并自动对齐到片段起点。", captionVoiceEmptyHint: "请先在时间线中选择一个字幕片段。" },
|
||||
en: { timelineContextMenu: "Timeline context menu", clipActions: "Clip actions", trackActions: "Track actions", openTrackPanel: "Open panel", splitAtPlayhead: "Split at playhead", duplicateClip: "Duplicate clip", deleteClip: "Delete clip", addClip: "Add clip", hideTrack: "Hide track", showTrack: "Show track", unlockTrack: "Unlock track", lockTrack: "Lock track", voiceSampleTitle: "Voice sample", voiceSampleHint: "Switch voices to hear its pre-generated sample", voiceAddedToTimeline: "Added to voiceover timeline", voicePreviewHint: "Preview this generated timeline voiceover", captionTools: "Caption tools", captionVoiceHint: "Generate voice for the selected caption only and align it to the caption start.", captionVoiceEmptyHint: "Select a caption clip on the timeline first." },
|
||||
ja: { timelineContextMenu: "タイムラインのコンテキストメニュー", clipActions: "クリップ操作", trackActions: "トラック操作", openTrackPanel: "パネルを開く", splitAtPlayhead: "再生ヘッドで分割", duplicateClip: "クリップを複製", deleteClip: "クリップを削除", addClip: "クリップを追加", hideTrack: "トラックを非表示", showTrack: "トラックを表示", unlockTrack: "トラックのロックを解除", lockTrack: "トラックをロック", voiceAddedToTimeline: "ボイスオーバーのタイムラインに追加しました", voicePreviewHint: "すぐに試聴でき、タイムライン上で引き続き調整できます", captionTools: "字幕ツール", captionVoiceHint: "選択中の字幕だけに音声を生成し、字幕の開始位置に合わせます。", captionVoiceEmptyHint: "先にタイムラインで字幕クリップを選択してください。" },
|
||||
ko: { timelineContextMenu: "타임라인 컨텍스트 메뉴", clipActions: "클립 작업", trackActions: "트랙 작업", openTrackPanel: "패널 열기", splitAtPlayhead: "재생 헤드에서 분할", duplicateClip: "클립 복제", deleteClip: "클립 삭제", addClip: "클립 추가", hideTrack: "트랙 숨기기", showTrack: "트랙 표시", unlockTrack: "트랙 잠금 해제", lockTrack: "트랙 잠금", voiceAddedToTimeline: "보이스오버 타임라인에 추가됨", voicePreviewHint: "바로 미리 듣고 타임라인에서 계속 조정할 수 있습니다" },
|
||||
es: { timelineContextMenu: "Menú contextual de la línea de tiempo", clipActions: "Acciones del clip", trackActions: "Acciones de la pista", openTrackPanel: "Abrir panel", splitAtPlayhead: "Dividir en el cabezal", duplicateClip: "Duplicar clip", deleteClip: "Eliminar clip", addClip: "Añadir clip", hideTrack: "Ocultar pista", showTrack: "Mostrar pista", unlockTrack: "Desbloquear pista", lockTrack: "Bloquear pista", voiceAddedToTimeline: "Añadido a la pista de voz", voicePreviewHint: "Listo para escuchar y seguir ajustando en la línea de tiempo" },
|
||||
fr: { timelineContextMenu: "Menu contextuel de la timeline", clipActions: "Actions du clip", trackActions: "Actions de la piste", openTrackPanel: "Ouvrir le panneau", splitAtPlayhead: "Scinder à la tête de lecture", duplicateClip: "Dupliquer le clip", deleteClip: "Supprimer le clip", addClip: "Ajouter un clip", hideTrack: "Masquer la piste", showTrack: "Afficher la piste", unlockTrack: "Déverrouiller la piste", lockTrack: "Verrouiller la piste", voiceAddedToTimeline: "Ajouté à la piste voix off", voicePreviewHint: "Prêt à écouter et à ajuster dans la timeline" },
|
||||
de: { timelineContextMenu: "Timeline-Kontextmenü", clipActions: "Clip-Aktionen", trackActions: "Spur-Aktionen", openTrackPanel: "Bereich öffnen", splitAtPlayhead: "Am Abspielkopf teilen", duplicateClip: "Clip duplizieren", deleteClip: "Clip löschen", addClip: "Clip hinzufügen", hideTrack: "Spur ausblenden", showTrack: "Spur einblenden", unlockTrack: "Spur entsperren", lockTrack: "Spur sperren", voiceAddedToTimeline: "Zur Voiceover-Spur hinzugefügt", voicePreviewHint: "Bereit zum Anhören und weiteren Bearbeiten in der Timeline" },
|
||||
pt: { timelineContextMenu: "Menu de contexto da linha do tempo", clipActions: "Ações do clipe", trackActions: "Ações da faixa", openTrackPanel: "Abrir painel", splitAtPlayhead: "Dividir no cursor", duplicateClip: "Duplicar clipe", deleteClip: "Excluir clipe", addClip: "Adicionar clipe", hideTrack: "Ocultar faixa", showTrack: "Mostrar faixa", unlockTrack: "Desbloquear faixa", lockTrack: "Bloquear faixa", voiceAddedToTimeline: "Adicionado à faixa de narração", voicePreviewHint: "Pronto para ouvir e continuar ajustando na linha do tempo" },
|
||||
th: { timelineContextMenu: "เมนูบริบทไทม์ไลน์", clipActions: "การทำงานกับคลิป", trackActions: "การทำงานกับแทร็ก", openTrackPanel: "เปิดแผง", splitAtPlayhead: "แยกที่หัวเล่น", duplicateClip: "ทำสำเนาคลิป", deleteClip: "ลบคลิป", addClip: "เพิ่มคลิป", hideTrack: "ซ่อนแทร็ก", showTrack: "แสดงแทร็ก", unlockTrack: "ปลดล็อกแทร็ก", lockTrack: "ล็อกแทร็ก", voiceAddedToTimeline: "เพิ่มลงในไทม์ไลน์เสียงพากย์แล้ว", voicePreviewHint: "พร้อมฟังตัวอย่างและปรับต่อบนไทม์ไลน์" },
|
||||
vi: { timelineContextMenu: "Trình đơn ngữ cảnh dòng thời gian", clipActions: "Thao tác clip", trackActions: "Thao tác rãnh", openTrackPanel: "Mở bảng", splitAtPlayhead: "Tách tại đầu phát", duplicateClip: "Nhân đôi clip", deleteClip: "Xóa clip", addClip: "Thêm clip", hideTrack: "Ẩn rãnh", showTrack: "Hiện rãnh", unlockTrack: "Mở khóa rãnh", lockTrack: "Khóa rãnh", voiceAddedToTimeline: "Đã thêm vào rãnh lồng tiếng", voicePreviewHint: "Sẵn sàng nghe thử và tiếp tục chỉnh trên dòng thời gian" },
|
||||
};
|
||||
|
||||
const TTS_BACKEND_COPY = {
|
||||
zh: { ttsStatusLoadingWebGpu: "正在加载 WebGPU 配音模型", ttsStatusGeneratingWebGpu: "正在使用 WebGPU 生成配音", ttsStatusFallingBackWasm: "WebGPU 不可用,正在切换到 WASM", ttsStatusGeneratingWasm: "正在使用 WASM 生成配音" },
|
||||
en: { ttsStatusLoadingWebGpu: "Loading WebGPU voice model", ttsStatusGeneratingWebGpu: "Generating voice with WebGPU", ttsStatusFallingBackWasm: "WebGPU unavailable; switching to WASM", ttsStatusGeneratingWasm: "Generating voice with WASM" },
|
||||
ja: { ttsStatusLoadingWebGpu: "WebGPU音声モデルを読み込み中", ttsStatusGeneratingWebGpu: "WebGPUで音声を生成中", ttsStatusFallingBackWasm: "WebGPUを利用できないためWASMに切り替え中", ttsStatusGeneratingWasm: "WASMで音声を生成中" },
|
||||
ko: { ttsStatusLoadingWebGpu: "WebGPU 음성 모델 로드 중", ttsStatusGeneratingWebGpu: "WebGPU로 음성 생성 중", ttsStatusFallingBackWasm: "WebGPU를 사용할 수 없어 WASM으로 전환 중", ttsStatusGeneratingWasm: "WASM으로 음성 생성 중" },
|
||||
es: { ttsStatusLoadingWebGpu: "Cargando modelo de voz WebGPU", ttsStatusGeneratingWebGpu: "Generando voz con WebGPU", ttsStatusFallingBackWasm: "WebGPU no disponible; cambiando a WASM", ttsStatusGeneratingWasm: "Generando voz con WASM" },
|
||||
fr: { ttsStatusLoadingWebGpu: "Chargement du modèle vocal WebGPU", ttsStatusGeneratingWebGpu: "Génération vocale avec WebGPU", ttsStatusFallingBackWasm: "WebGPU indisponible ; passage à WASM", ttsStatusGeneratingWasm: "Génération vocale avec WASM" },
|
||||
de: { ttsStatusLoadingWebGpu: "WebGPU-Sprachmodell wird geladen", ttsStatusGeneratingWebGpu: "Stimme wird mit WebGPU erzeugt", ttsStatusFallingBackWasm: "WebGPU nicht verfügbar; Wechsel zu WASM", ttsStatusGeneratingWasm: "Stimme wird mit WASM erzeugt" },
|
||||
pt: { ttsStatusLoadingWebGpu: "Carregando modelo de voz WebGPU", ttsStatusGeneratingWebGpu: "Gerando voz com WebGPU", ttsStatusFallingBackWasm: "WebGPU indisponível; mudando para WASM", ttsStatusGeneratingWasm: "Gerando voz com WASM" },
|
||||
th: { ttsStatusLoadingWebGpu: "กำลังโหลดโมเดลเสียง WebGPU", ttsStatusGeneratingWebGpu: "กำลังสร้างเสียงด้วย WebGPU", ttsStatusFallingBackWasm: "ใช้ WebGPU ไม่ได้ กำลังเปลี่ยนเป็น WASM", ttsStatusGeneratingWasm: "กำลังสร้างเสียงด้วย WASM" },
|
||||
vi: { ttsStatusLoadingWebGpu: "Đang tải mô hình giọng nói WebGPU", ttsStatusGeneratingWebGpu: "Đang tạo giọng nói bằng WebGPU", ttsStatusFallingBackWasm: "Không dùng được WebGPU; đang chuyển sang WASM", ttsStatusGeneratingWasm: "Đang tạo giọng nói bằng WASM" },
|
||||
};
|
||||
|
||||
export const UI_COPY = {
|
||||
zh: {
|
||||
...VISUAL_EDITOR_COPY.zh,
|
||||
...VISUAL_PANEL_TITLE_COPY.zh,
|
||||
...VISUAL_MASK_SHAPE_COPY.zh,
|
||||
...VISUAL_KEYFRAME_ACTION_COPY.zh,
|
||||
...VISUAL_TAB_COPY.zh,
|
||||
@@ -172,6 +212,8 @@ export const UI_COPY = {
|
||||
...REMASTER_GPU_COPY.zh,
|
||||
...REMASTER_PHASE_COPY.zh,
|
||||
...SOURCE_AUDIO_SYNC_COPY.zh,
|
||||
...CONTEXT_PANEL_COPY.zh,
|
||||
...TTS_BACKEND_COPY.zh,
|
||||
...CAPTION_WORKSPACE_COPY.zh,
|
||||
...RESOURCE_LINK_COPY.zh,
|
||||
languageKicker: "AI Voice Studio",
|
||||
@@ -452,7 +494,7 @@ export const UI_COPY = {
|
||||
captionScriptLabel: "字幕文案",
|
||||
captionList: "字幕列表",
|
||||
captionSegmentsUnit: "条字幕",
|
||||
captionEmptyHint: "选择时间线字幕片段后,这里会同步编辑。",
|
||||
captionEmptyHint: "字幕片段可拖动到字幕轨道,并在这里同步编辑。",
|
||||
showCurrentCaption: "显示当前字幕",
|
||||
hideCurrentCaption: "隐藏当前字幕",
|
||||
deleteCurrentCaption: "删除当前字幕",
|
||||
@@ -528,6 +570,7 @@ export const UI_COPY = {
|
||||
},
|
||||
en: {
|
||||
...VISUAL_EDITOR_COPY.en,
|
||||
...VISUAL_PANEL_TITLE_COPY.en,
|
||||
...VISUAL_MASK_SHAPE_COPY.en,
|
||||
...VISUAL_KEYFRAME_ACTION_COPY.en,
|
||||
...VISUAL_TAB_COPY.en,
|
||||
@@ -537,6 +580,8 @@ export const UI_COPY = {
|
||||
...REMASTER_GPU_COPY.en,
|
||||
...REMASTER_PHASE_COPY.en,
|
||||
...SOURCE_AUDIO_SYNC_COPY.en,
|
||||
...CONTEXT_PANEL_COPY.en,
|
||||
...TTS_BACKEND_COPY.en,
|
||||
...CAPTION_WORKSPACE_COPY.en,
|
||||
...RESOURCE_LINK_COPY.en,
|
||||
languageKicker: "AI Voice Studio",
|
||||
@@ -817,7 +862,7 @@ export const UI_COPY = {
|
||||
captionScriptLabel: "Caption text",
|
||||
captionList: "Caption list",
|
||||
captionSegmentsUnit: "caption segment(s)",
|
||||
captionEmptyHint: "Select a caption segment on the timeline to edit it here.",
|
||||
captionEmptyHint: "Drag caption clips onto the caption track and edit them here in sync.",
|
||||
showCurrentCaption: "Show caption",
|
||||
hideCurrentCaption: "Hide caption",
|
||||
deleteCurrentCaption: "Delete caption",
|
||||
@@ -893,6 +938,7 @@ export const UI_COPY = {
|
||||
},
|
||||
ja: {
|
||||
...VISUAL_EDITOR_COPY.ja,
|
||||
...VISUAL_PANEL_TITLE_COPY.ja,
|
||||
...VISUAL_MASK_SHAPE_COPY.ja,
|
||||
...VISUAL_KEYFRAME_ACTION_COPY.ja,
|
||||
...VISUAL_TAB_COPY.ja,
|
||||
@@ -902,6 +948,8 @@ export const UI_COPY = {
|
||||
...REMASTER_GPU_COPY.ja,
|
||||
...REMASTER_PHASE_COPY.ja,
|
||||
...SOURCE_AUDIO_SYNC_COPY.ja,
|
||||
...CONTEXT_PANEL_COPY.ja,
|
||||
...TTS_BACKEND_COPY.ja,
|
||||
...CAPTION_WORKSPACE_COPY.ja,
|
||||
...RESOURCE_LINK_COPY.ja,
|
||||
languageTitle: "表示言語を選択",
|
||||
@@ -967,6 +1015,7 @@ export const UI_COPY = {
|
||||
Object.assign(UI_COPY, {
|
||||
ko: {
|
||||
...VISUAL_EDITOR_COPY.ko,
|
||||
...VISUAL_PANEL_TITLE_COPY.ko,
|
||||
...VISUAL_MASK_SHAPE_COPY.ko,
|
||||
...VISUAL_KEYFRAME_ACTION_COPY.ko,
|
||||
...VISUAL_TAB_COPY.ko,
|
||||
@@ -976,7 +1025,11 @@ Object.assign(UI_COPY, {
|
||||
...REMASTER_GPU_COPY.ko,
|
||||
...REMASTER_PHASE_COPY.ko,
|
||||
...SOURCE_AUDIO_SYNC_COPY.ko,
|
||||
...CONTEXT_PANEL_COPY.ko,
|
||||
...TTS_BACKEND_COPY.ko,
|
||||
...UI_COPY.en,
|
||||
...CONTEXT_PANEL_COPY.ko,
|
||||
...TTS_BACKEND_COPY.ko,
|
||||
...CAPTION_WORKSPACE_COPY.ko,
|
||||
...RESOURCE_LINK_COPY.ko,
|
||||
languageTitle: "인터페이스 언어 선택",
|
||||
@@ -1021,6 +1074,7 @@ Object.assign(UI_COPY, {
|
||||
es: {
|
||||
...UI_COPY.en,
|
||||
...VISUAL_EDITOR_COPY.es,
|
||||
...VISUAL_PANEL_TITLE_COPY.es,
|
||||
...VISUAL_MASK_SHAPE_COPY.es,
|
||||
...VISUAL_KEYFRAME_ACTION_COPY.es,
|
||||
...VISUAL_TAB_COPY.es,
|
||||
@@ -1030,6 +1084,8 @@ Object.assign(UI_COPY, {
|
||||
...REMASTER_GPU_COPY.es,
|
||||
...REMASTER_PHASE_COPY.es,
|
||||
...SOURCE_AUDIO_SYNC_COPY.es,
|
||||
...CONTEXT_PANEL_COPY.es,
|
||||
...TTS_BACKEND_COPY.es,
|
||||
...CAPTION_WORKSPACE_COPY.es,
|
||||
...RESOURCE_LINK_COPY.es,
|
||||
languageTitle: "Elige el idioma",
|
||||
@@ -1074,6 +1130,7 @@ Object.assign(UI_COPY, {
|
||||
fr: {
|
||||
...UI_COPY.en,
|
||||
...VISUAL_EDITOR_COPY.fr,
|
||||
...VISUAL_PANEL_TITLE_COPY.fr,
|
||||
...VISUAL_MASK_SHAPE_COPY.fr,
|
||||
...VISUAL_KEYFRAME_ACTION_COPY.fr,
|
||||
...VISUAL_TAB_COPY.fr,
|
||||
@@ -1083,6 +1140,8 @@ Object.assign(UI_COPY, {
|
||||
...REMASTER_GPU_COPY.fr,
|
||||
...REMASTER_PHASE_COPY.fr,
|
||||
...SOURCE_AUDIO_SYNC_COPY.fr,
|
||||
...CONTEXT_PANEL_COPY.fr,
|
||||
...TTS_BACKEND_COPY.fr,
|
||||
...CAPTION_WORKSPACE_COPY.fr,
|
||||
...RESOURCE_LINK_COPY.fr,
|
||||
languageTitle: "Choisir la langue",
|
||||
@@ -1127,6 +1186,7 @@ Object.assign(UI_COPY, {
|
||||
de: {
|
||||
...UI_COPY.en,
|
||||
...VISUAL_EDITOR_COPY.de,
|
||||
...VISUAL_PANEL_TITLE_COPY.de,
|
||||
...VISUAL_MASK_SHAPE_COPY.de,
|
||||
...VISUAL_KEYFRAME_ACTION_COPY.de,
|
||||
...VISUAL_TAB_COPY.de,
|
||||
@@ -1136,6 +1196,8 @@ Object.assign(UI_COPY, {
|
||||
...REMASTER_GPU_COPY.de,
|
||||
...REMASTER_PHASE_COPY.de,
|
||||
...SOURCE_AUDIO_SYNC_COPY.de,
|
||||
...CONTEXT_PANEL_COPY.de,
|
||||
...TTS_BACKEND_COPY.de,
|
||||
...CAPTION_WORKSPACE_COPY.de,
|
||||
...RESOURCE_LINK_COPY.de,
|
||||
languageTitle: "Sprache wählen",
|
||||
@@ -1180,6 +1242,7 @@ Object.assign(UI_COPY, {
|
||||
pt: {
|
||||
...UI_COPY.en,
|
||||
...VISUAL_EDITOR_COPY.pt,
|
||||
...VISUAL_PANEL_TITLE_COPY.pt,
|
||||
...VISUAL_MASK_SHAPE_COPY.pt,
|
||||
...VISUAL_KEYFRAME_ACTION_COPY.pt,
|
||||
...VISUAL_TAB_COPY.pt,
|
||||
@@ -1189,6 +1252,8 @@ Object.assign(UI_COPY, {
|
||||
...REMASTER_GPU_COPY.pt,
|
||||
...REMASTER_PHASE_COPY.pt,
|
||||
...SOURCE_AUDIO_SYNC_COPY.pt,
|
||||
...CONTEXT_PANEL_COPY.pt,
|
||||
...TTS_BACKEND_COPY.pt,
|
||||
...CAPTION_WORKSPACE_COPY.pt,
|
||||
...RESOURCE_LINK_COPY.pt,
|
||||
languageTitle: "Escolha o idioma",
|
||||
@@ -1233,6 +1298,7 @@ Object.assign(UI_COPY, {
|
||||
th: {
|
||||
...UI_COPY.en,
|
||||
...VISUAL_EDITOR_COPY.th,
|
||||
...VISUAL_PANEL_TITLE_COPY.th,
|
||||
...VISUAL_MASK_SHAPE_COPY.th,
|
||||
...VISUAL_KEYFRAME_ACTION_COPY.th,
|
||||
...VISUAL_TAB_COPY.th,
|
||||
@@ -1242,6 +1308,8 @@ Object.assign(UI_COPY, {
|
||||
...REMASTER_GPU_COPY.th,
|
||||
...REMASTER_PHASE_COPY.th,
|
||||
...SOURCE_AUDIO_SYNC_COPY.th,
|
||||
...CONTEXT_PANEL_COPY.th,
|
||||
...TTS_BACKEND_COPY.th,
|
||||
...CAPTION_WORKSPACE_COPY.th,
|
||||
...RESOURCE_LINK_COPY.th,
|
||||
languageTitle: "เลือกภาษาอินเทอร์เฟซ",
|
||||
@@ -1286,6 +1354,7 @@ Object.assign(UI_COPY, {
|
||||
vi: {
|
||||
...UI_COPY.en,
|
||||
...VISUAL_EDITOR_COPY.vi,
|
||||
...VISUAL_PANEL_TITLE_COPY.vi,
|
||||
...VISUAL_MASK_SHAPE_COPY.vi,
|
||||
...VISUAL_KEYFRAME_ACTION_COPY.vi,
|
||||
...VISUAL_TAB_COPY.vi,
|
||||
@@ -1295,6 +1364,8 @@ Object.assign(UI_COPY, {
|
||||
...REMASTER_GPU_COPY.vi,
|
||||
...REMASTER_PHASE_COPY.vi,
|
||||
...SOURCE_AUDIO_SYNC_COPY.vi,
|
||||
...CONTEXT_PANEL_COPY.vi,
|
||||
...TTS_BACKEND_COPY.vi,
|
||||
...CAPTION_WORKSPACE_COPY.vi,
|
||||
...RESOURCE_LINK_COPY.vi,
|
||||
languageTitle: "Chọn ngôn ngữ giao diện",
|
||||
|
||||
@@ -8,10 +8,10 @@ import {
|
||||
} from "./timeline.js";
|
||||
|
||||
export function createAudioTrackActions(d) {
|
||||
function replaceAudio(blob, duration, nextPeaks, nextStatusText) {
|
||||
function replaceAudio(blob, duration, nextPeaks, nextStatusText, options = {}) {
|
||||
const nextUrl = URL.createObjectURL(blob);
|
||||
const nextDuration = duration || estimateDuration(d.script);
|
||||
const start = Math.max(0, d.currentTimeRef.current || 0);
|
||||
const nextDuration = duration || estimateDuration(options.script ?? d.script);
|
||||
const start = Math.max(0, options.start ?? d.currentTimeRef.current ?? 0);
|
||||
const id = crypto.randomUUID();
|
||||
const segment = {
|
||||
id,
|
||||
@@ -24,9 +24,17 @@ export function createAudioTrackActions(d) {
|
||||
fadeIn: 0,
|
||||
fadeOut: 0,
|
||||
reversed: false,
|
||||
name: d.selectedVoice?.name || d.t("voiceTrack"),
|
||||
name: options.name || d.selectedVoice?.name || d.t("voiceTrack"),
|
||||
};
|
||||
d.setAudioSegments((segments) => [...segments, segment]);
|
||||
if (options.replaceSegmentId) {
|
||||
const replaced = d.audioSegments.find((item) => item.id === options.replaceSegmentId);
|
||||
d.audioSegmentRefs.current.get?.(options.replaceSegmentId)?.pause?.();
|
||||
if (replaced?.url) URL.revokeObjectURL(replaced.url);
|
||||
}
|
||||
d.setAudioSegments((segments) => [
|
||||
...segments.filter((item) => item.id !== options.replaceSegmentId),
|
||||
segment,
|
||||
]);
|
||||
d.setSelectedAudioSegmentId(id);
|
||||
d.setSelectedTrack("audio");
|
||||
d.setTimelineHorizon((value) => Math.max(value, Math.ceil((start + nextDuration + 5) / 10) * 10));
|
||||
@@ -72,6 +80,7 @@ export function createAudioTrackActions(d) {
|
||||
message = "视频原声已分离到时间线",
|
||||
timelineStart = 0,
|
||||
assetId = d.sourceAudioAssetId,
|
||||
options = {},
|
||||
) {
|
||||
if (d.sourceAudioUrlRef.current) URL.revokeObjectURL(d.sourceAudioUrlRef.current);
|
||||
const nextUrl = URL.createObjectURL(blob);
|
||||
@@ -86,8 +95,10 @@ export function createAudioTrackActions(d) {
|
||||
d.setSourceAudioStart(nextStart);
|
||||
d.setSourceAudioAssetId(assetId || "");
|
||||
d.setSourceAudioLinked(true);
|
||||
d.setSelectedTrack("source");
|
||||
d.setActiveTool("audio");
|
||||
if (options.focusAudio !== false) {
|
||||
d.setSelectedTrack("source");
|
||||
d.setActiveTool("audio");
|
||||
}
|
||||
d.setStatus("done");
|
||||
d.setStatusText("视频原声已分离");
|
||||
d.setProgress(100);
|
||||
@@ -144,9 +155,36 @@ export function createAudioTrackActions(d) {
|
||||
d.notify(message);
|
||||
}
|
||||
|
||||
async function commitAudio(blob, nextStatusText) {
|
||||
async function commitAudio(blob, nextStatusText, options = {}) {
|
||||
const decoded = await decodeWaveform(blob);
|
||||
const audioSegment = replaceAudio(blob, decoded.duration, decoded.peaks, nextStatusText);
|
||||
const captionSegment = options.captionSegment;
|
||||
const audioSegment = replaceAudio(blob, decoded.duration, decoded.peaks, nextStatusText, captionSegment ? {
|
||||
start: captionSegment.start || 0,
|
||||
script: options.script || captionSegment.text,
|
||||
replaceSegmentId: captionSegment.audioSegmentId || "",
|
||||
} : options);
|
||||
|
||||
if (captionSegment) {
|
||||
d.setCaptionSegments((segments) => segments.map((segment) => segment.id === captionSegment.id ? {
|
||||
...segment,
|
||||
audioSegmentId: audioSegment.id,
|
||||
start: audioSegment.start,
|
||||
end: audioSegment.start + audioSegment.duration,
|
||||
} : segment).sort((a, b) => (a.start || 0) - (b.start || 0)));
|
||||
d.setSelectedSegmentId(captionSegment.id);
|
||||
d.setHistoryItems((items) => [{
|
||||
id: crypto.randomUUID(),
|
||||
blob,
|
||||
voiceId: d.selectedVoiceId,
|
||||
voiceName: d.selectedVoice.name,
|
||||
script: options.script || captionSegment.text,
|
||||
duration: decoded.duration || estimateDuration(options.script || captionSegment.text),
|
||||
peaks: decoded.peaks,
|
||||
createdAt: formatSavedTime(),
|
||||
}, ...items.slice(0, 8)]);
|
||||
return;
|
||||
}
|
||||
|
||||
const generatedCaptions = createCaptionSegments(d.script);
|
||||
const generatedTimeline = getCaptionTimeline(generatedCaptions, audioSegment.duration);
|
||||
const boundCaptions = generatedCaptions.map((segment, index) => ({
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
export function getCaptionVoiceSegment(audioSegments, captionSegment) {
|
||||
if (!captionSegment?.audioSegmentId) return null;
|
||||
return audioSegments.find((segment) => segment.id === captionSegment.audioSegmentId) ?? null;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { getCaptionVoiceSegment } from "./captionVoice.js";
|
||||
|
||||
describe("getCaptionVoiceSegment", () => {
|
||||
const oldVoice = { id: "voice-old", url: "blob:old", blob: { size: 10 } };
|
||||
const newVoice = { id: "voice-new", url: "blob:new", blob: { size: 20 } };
|
||||
const audioSegments = [oldVoice, newVoice];
|
||||
|
||||
it("returns only the voice linked to the selected caption", () => {
|
||||
expect(getCaptionVoiceSegment(audioSegments, { id: "caption-old", audioSegmentId: "voice-old" })).toBe(oldVoice);
|
||||
expect(getCaptionVoiceSegment(audioSegments, { id: "caption-new", audioSegmentId: "voice-new" })).toBe(newVoice);
|
||||
});
|
||||
|
||||
it("does not leak the previously selected caption voice into an unvoiced caption", () => {
|
||||
expect(getCaptionVoiceSegment(audioSegments, { id: "caption-fresh" })).toBeNull();
|
||||
expect(getCaptionVoiceSegment(audioSegments, { id: "caption-missing", audioSegmentId: "removed-voice" })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -20,6 +20,7 @@ export function createEditorCommandActions(d) {
|
||||
d.setSelectedTrack("audio");
|
||||
d.setVoiceTab("synthesis");
|
||||
}
|
||||
if (toolId === "media") d.setSelectedTrack("image");
|
||||
if (toolId === "caption") d.setSelectedTrack("caption");
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { pinyin } from "pinyin-pro";
|
||||
ort.env.wasm.numThreads = 1;
|
||||
ort.env.wasm.simd = true;
|
||||
ort.env.wasm.wasmPaths = { mjs: ortWasmMjsUrl, wasm: ortWasmUrl };
|
||||
ort.env.webgpu.powerPreference = "high-performance";
|
||||
|
||||
const PINYIN_VOICES = {
|
||||
"zh_CN-xiao_ya-medium": "zh/zh_CN/xiao_ya/medium",
|
||||
@@ -96,8 +97,35 @@ async function loadPinyinVoice(voiceId, onProgress) {
|
||||
if (!configResponse.ok) throw new Error(`${voiceName}配置下载失败 (${configResponse.status})`);
|
||||
const config = await configResponse.json();
|
||||
const model = await fetchArrayBufferWithProgress(`${voiceBase}/${voiceId}.onnx`, onProgress, voiceName);
|
||||
const session = await ort.InferenceSession.create(model, { executionProviders: ["wasm"] });
|
||||
return { config, session };
|
||||
if (globalThis.navigator?.gpu) {
|
||||
try {
|
||||
const session = await ort.InferenceSession.create(model, {
|
||||
executionProviders: [{ name: "webgpu", preferredLayout: "NHWC" }],
|
||||
graphOptimizationLevel: "all",
|
||||
});
|
||||
onProgress?.({ backend: "webgpu" });
|
||||
return { backend: "webgpu", config, model, session };
|
||||
} catch (error) {
|
||||
console.warn("Piper WebGPU initialization failed; using WASM.", error);
|
||||
onProgress?.({ backend: "wasm", fallbackReason: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
}
|
||||
const session = await ort.InferenceSession.create(model, { executionProviders: ["wasm"], graphOptimizationLevel: "all" });
|
||||
onProgress?.({ backend: "wasm" });
|
||||
return { backend: "wasm", config, model, session };
|
||||
}
|
||||
|
||||
function createPinyinFeeds(input, config) {
|
||||
const ids = phonemizeXiaoYa(input.text.trim(), config.phoneme_id_map);
|
||||
return {
|
||||
input: new ort.Tensor("int64", BigInt64Array.from(ids, BigInt), [1, ids.length]),
|
||||
input_lengths: new ort.Tensor("int64", BigInt64Array.from([ids.length], BigInt), [1]),
|
||||
scales: new ort.Tensor("float32", Float32Array.from([
|
||||
config.inference.noise_scale,
|
||||
config.inference.length_scale,
|
||||
config.inference.noise_w,
|
||||
]), [3]),
|
||||
};
|
||||
}
|
||||
|
||||
async function predictPinyinVoice(input, onProgress) {
|
||||
@@ -110,23 +138,25 @@ async function predictPinyinVoice(input, onProgress) {
|
||||
}),
|
||||
);
|
||||
}
|
||||
const { config, session } = await pinyinRuntimePromises.get(input.voiceId);
|
||||
const ids = phonemizeXiaoYa(input.text.trim(), config.phoneme_id_map);
|
||||
const feeds = {
|
||||
input: new ort.Tensor("int64", BigInt64Array.from(ids, BigInt), [1, ids.length]),
|
||||
input_lengths: new ort.Tensor("int64", BigInt64Array.from([ids.length], BigInt), [1]),
|
||||
scales: new ort.Tensor("float32", Float32Array.from([
|
||||
config.inference.noise_scale,
|
||||
config.inference.length_scale,
|
||||
config.inference.noise_w,
|
||||
]), [3]),
|
||||
};
|
||||
const result = await session.run(feeds);
|
||||
let runtime = await pinyinRuntimePromises.get(input.voiceId);
|
||||
const feeds = createPinyinFeeds(input, runtime.config);
|
||||
let result;
|
||||
try {
|
||||
result = await runtime.session.run(feeds);
|
||||
} catch (error) {
|
||||
if (runtime.backend !== "webgpu") throw error;
|
||||
console.warn("Piper WebGPU inference failed; retrying with WASM.", error);
|
||||
onProgress?.({ backend: "wasm", fallbackReason: error instanceof Error ? error.message : String(error) });
|
||||
const session = await ort.InferenceSession.create(runtime.model, { executionProviders: ["wasm"], graphOptimizationLevel: "all" });
|
||||
runtime = { ...runtime, backend: "wasm", session };
|
||||
pinyinRuntimePromises.set(input.voiceId, Promise.resolve(runtime));
|
||||
result = await session.run(feeds);
|
||||
}
|
||||
const samples = result.output.data;
|
||||
if (!(samples instanceof Float32Array) || !samples.length || samples.some((sample) => !Number.isFinite(sample))) {
|
||||
throw new Error("小雅生成了无效音频");
|
||||
}
|
||||
return encodeWav(samples, config.audio.sample_rate);
|
||||
return encodeWav(samples, runtime.config.audio.sample_rate);
|
||||
}
|
||||
|
||||
export async function predictPiperVoice(tts, input, onProgress) {
|
||||
|
||||
@@ -16,6 +16,8 @@ import {
|
||||
} from "./timeline.js";
|
||||
import {
|
||||
getTimelineAutoFitZoom,
|
||||
getTimelineInitialContentZoom,
|
||||
getTimelineProjectDuration,
|
||||
getTimelineVisibleDuration,
|
||||
getTimelineZoomForVisibleDuration,
|
||||
} from "./timelineScale.js";
|
||||
@@ -29,10 +31,25 @@ describe("timeline primitives", () => {
|
||||
});
|
||||
|
||||
it("clamps automatic timeline fitting to supported zoom limits", () => {
|
||||
expect(getTimelineVisibleDuration(getTimelineZoomForVisibleDuration(10_000))).toBeCloseTo(1800, 2);
|
||||
expect(getTimelineVisibleDuration(getTimelineZoomForVisibleDuration(100_000))).toBeCloseTo(86_400, 2);
|
||||
expect(getTimelineVisibleDuration(getTimelineAutoFitZoom(0.5))).toBeCloseTo(5, 2);
|
||||
});
|
||||
|
||||
it("uses an approachable empty and first-content timeline window", () => {
|
||||
expect(getTimelineVisibleDuration(getTimelineInitialContentZoom(0))).toBeCloseTo(10, 2);
|
||||
expect(getTimelineVisibleDuration(getTimelineInitialContentZoom(1.8))).toBeCloseTo(5, 2);
|
||||
expect(getTimelineVisibleDuration(getTimelineInitialContentZoom(15))).toBeCloseTo(15 / 0.82, 2);
|
||||
expect(getTimelineVisibleDuration(getTimelineInitialContentZoom(90))).toBeCloseTo(30, 2);
|
||||
});
|
||||
|
||||
it("grows the project horizon from real content with bounded tail room", () => {
|
||||
expect(getTimelineProjectDuration(0)).toBe(10);
|
||||
expect(getTimelineProjectDuration(1.8)).toBe(10);
|
||||
expect(getTimelineProjectDuration(12)).toBe(17);
|
||||
expect(getTimelineProjectDuration(100)).toBe(105);
|
||||
expect(getTimelineProjectDuration(1_000)).toBe(1_030);
|
||||
});
|
||||
|
||||
it("reorders without mutating the source array", () => {
|
||||
const source = [{ id: "a" }, { id: "b" }, { id: "c" }];
|
||||
const result = reorderTimelineItems(source, 0, 2);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { DEFAULT_TIMELINE_DURATION_SECONDS } from "../config/editor.js";
|
||||
import { DEFAULT_TIMELINE_DURATION_SECONDS, MAX_TIMELINE_DURATION_SECONDS } from "../config/editor.js";
|
||||
|
||||
export const TIMELINE_MIN_ZOOM = 0.25;
|
||||
export const TIMELINE_MAX_ZOOM = 16;
|
||||
@@ -18,7 +18,7 @@ export function getTimelineVisibleDuration(zoom) {
|
||||
|
||||
if (clampedZoom <= 1) {
|
||||
const progress = (clampedZoom - TIMELINE_MIN_ZOOM) / (1 - TIMELINE_MIN_ZOOM);
|
||||
const maxLog = Math.log(DEFAULT_TIMELINE_DURATION_SECONDS);
|
||||
const maxLog = Math.log(MAX_TIMELINE_DURATION_SECONDS);
|
||||
const defaultLog = Math.log(TIMELINE_DEFAULT_VISIBLE_SECONDS);
|
||||
return Math.exp(maxLog + (defaultLog - maxLog) * progress);
|
||||
}
|
||||
@@ -32,7 +32,7 @@ export function getTimelineVisibleDuration(zoom) {
|
||||
export function getTimelineZoomForVisibleDuration(visibleDuration) {
|
||||
const target = Math.max(
|
||||
TIMELINE_MIN_VISIBLE_SECONDS,
|
||||
Math.min(DEFAULT_TIMELINE_DURATION_SECONDS, Number(visibleDuration) || TIMELINE_DEFAULT_VISIBLE_SECONDS),
|
||||
Math.min(MAX_TIMELINE_DURATION_SECONDS, Number(visibleDuration) || TIMELINE_DEFAULT_VISIBLE_SECONDS),
|
||||
);
|
||||
let low = TIMELINE_MIN_ZOOM;
|
||||
let high = TIMELINE_MAX_ZOOM;
|
||||
@@ -53,6 +53,30 @@ export function getTimelineAutoFitZoom(contentDuration, fillRatio = 0.82) {
|
||||
return getTimelineZoomForVisibleDuration(paddedVisibleDuration);
|
||||
}
|
||||
|
||||
export function getTimelineInitialContentZoom(contentDuration) {
|
||||
const safeDuration = Math.max(0, Number(contentDuration) || 0);
|
||||
if (safeDuration <= 0) return getTimelineZoomForVisibleDuration(TIMELINE_DEFAULT_VISIBLE_SECONDS);
|
||||
if (safeDuration > 60) return getTimelineZoomForVisibleDuration(30);
|
||||
return getTimelineAutoFitZoom(safeDuration);
|
||||
}
|
||||
|
||||
export function getTimelineTailPadding(contentDuration) {
|
||||
const safeDuration = Math.max(0, Number(contentDuration) || 0);
|
||||
if (safeDuration <= 0) return 0;
|
||||
if (safeDuration < 10) return 2;
|
||||
if (safeDuration <= 60) return 5;
|
||||
return Math.min(30, safeDuration * 0.05);
|
||||
}
|
||||
|
||||
export function getTimelineProjectDuration(contentDuration) {
|
||||
const safeDuration = Math.max(0, Number(contentDuration) || 0);
|
||||
if (safeDuration <= 0) return DEFAULT_TIMELINE_DURATION_SECONDS;
|
||||
return Math.min(
|
||||
MAX_TIMELINE_DURATION_SECONDS,
|
||||
Math.max(DEFAULT_TIMELINE_DURATION_SECONDS, Math.ceil((safeDuration + getTimelineTailPadding(safeDuration)) * 2) / 2),
|
||||
);
|
||||
}
|
||||
|
||||
export function getTimelineTrackWidthPercent(timelineDuration, zoom) {
|
||||
if (timelineDuration <= 0) {
|
||||
return 100;
|
||||
|
||||
@@ -11,7 +11,7 @@ export function createTimelineSegmentCountActions(d) {
|
||||
const index = stickerIndex(); const next = d.stickerSegments.filter((_, position) => position !== index);
|
||||
d.commitStickerSegments(next, next.length ? "已删除当前贴纸片段" : "已删除最后一个贴纸片段", next[Math.max(0, index - 1)]?.id ?? "");
|
||||
};
|
||||
const handleAddSegment = () => {
|
||||
const handleAddSegment = (requestedStart = null) => {
|
||||
if (d.selectedTrack === "sticker") {
|
||||
if (d.trackLocks.sticker) return void d.notify("贴纸轨已锁定,无法新增贴纸片段");
|
||||
const source = d.stickerSegments[stickerIndex()] ?? d.getStickerDragAsset(d.selectedSticker);
|
||||
@@ -30,6 +30,19 @@ export function createTimelineSegmentCountActions(d) {
|
||||
return void d.commitVisualSegments([...source, segment], "已新增一个视觉片段", source.length);
|
||||
}
|
||||
if (["audio", "source", "music"].includes(d.selectedTrack)) return void d.notify(d.selectedTrack === "music" ? "背景音乐暂不支持切片,请删除后重新上传" : d.selectedTrack === "source" ? "视频原声暂不支持切片,可删除后重新上传视频" : "音频片段由生成结果决定,请重新生成或复制 WAV");
|
||||
if (Number.isFinite(requestedStart)) {
|
||||
const start = Math.max(0, Math.min(MAX_TIMELINE_DURATION_SECONDS - 0.45, requestedStart));
|
||||
const segment = {
|
||||
id: makeId("caption"),
|
||||
text: "新的字幕片段",
|
||||
weight: 1,
|
||||
hidden: false,
|
||||
start,
|
||||
end: Math.min(MAX_TIMELINE_DURATION_SECONDS, start + 1.8),
|
||||
};
|
||||
const next = [...d.captionSegments, segment].sort((a, b) => (a.start || 0) - (b.start || 0));
|
||||
return void d.commitCaptionSegments(next, "已在点击位置新增字幕片段", next.findIndex((item) => item.id === segment.id));
|
||||
}
|
||||
const index = d.selectedSegmentId ? d.selectedSegmentIndex : d.focusedSegmentIndex;
|
||||
const previous = d.captionSegments[index]; const nextCaption = d.captionSegments[index + 1];
|
||||
const start = hasExplicitCaptionTiming(previous) ? previous.end : null;
|
||||
|
||||
@@ -8,14 +8,8 @@ import {
|
||||
getImageThumbnailCount,
|
||||
getVisualSegmentsTotal,
|
||||
} from "./timeline.js";
|
||||
import { getTimelineAutoFitZoom } from "./timelineScale.js";
|
||||
|
||||
export function createVisualTimelineActions(d) {
|
||||
function fitTimelineToVideo(duration) {
|
||||
if (typeof d.setTimelineZoom !== "function") return;
|
||||
d.setTimelineZoom(getTimelineAutoFitZoom(duration));
|
||||
}
|
||||
|
||||
function getVisualDurationForAsset(asset, fallbackDuration = 4) {
|
||||
if (asset?.type === "video" && asset.duration) {
|
||||
return Math.min(
|
||||
@@ -92,7 +86,6 @@ export function createVisualTimelineActions(d) {
|
||||
d.setSelectedVisualSegmentId(segment.id);
|
||||
d.setImageDuration(segment.duration);
|
||||
d.setImageClipCount(getImageThumbnailCount(segment.duration));
|
||||
if (asset?.type === "video") fitTimelineToVideo(segment.duration);
|
||||
}
|
||||
|
||||
function appendVisualAssetToTimeline(asset) {
|
||||
@@ -120,7 +113,6 @@ export function createVisualTimelineActions(d) {
|
||||
`${asset.type === "video" ? "视频" : "图片"}素材已追加到图片轨`,
|
||||
sourceSegments.length,
|
||||
);
|
||||
if (asset.type === "video") fitTimelineToVideo(totalDuration + segmentDuration);
|
||||
d.seekTo(totalDuration);
|
||||
if (asset.type === "video") d.extractVideoSourceAudio(asset, totalDuration);
|
||||
}
|
||||
@@ -128,7 +120,6 @@ export function createVisualTimelineActions(d) {
|
||||
function updateVisualAssetInTimeline(assetId, updates) {
|
||||
if (!assetId) return;
|
||||
d.setVisualSegments((segments) => {
|
||||
const matchingSegment = segments.find((segment) => segment.assetId === assetId);
|
||||
const nextSegments = segments.map((segment) =>
|
||||
segment.assetId === assetId
|
||||
? {
|
||||
@@ -149,9 +140,6 @@ export function createVisualTimelineActions(d) {
|
||||
const nextDuration = getVisualSegmentsTotal(nextSegments);
|
||||
d.setImageDuration(nextDuration);
|
||||
d.setImageClipCount(getImageThumbnailCount(nextDuration));
|
||||
if (matchingSegment?.type === "video" && updates.duration) {
|
||||
fitTimelineToVideo(nextDuration);
|
||||
}
|
||||
return nextSegments;
|
||||
});
|
||||
if (d.previewVisualSegment?.assetId === assetId || d.previewVisualSegment?.src === updates.src) {
|
||||
|
||||
+202
-29
@@ -1841,6 +1841,13 @@ button:disabled {
|
||||
|
||||
.caption-tool-panel::-webkit-scrollbar { display: none; width: 0; height: 0; }
|
||||
|
||||
.caption-tool-panel > .segmented button {
|
||||
min-height: 32px;
|
||||
padding: 5px 8px;
|
||||
font-size: 12px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.caption-tool-panel > h2,
|
||||
.caption-tool-panel > .switch-row,
|
||||
.caption-tool-panel > .segmented,
|
||||
@@ -1877,9 +1884,8 @@ button:disabled {
|
||||
}
|
||||
|
||||
.caption-style-panel { display: grid; gap: 10px; padding: 11px; border: 1px solid rgba(255,255,255,.07); border-radius: 9px; background: rgba(255,255,255,.025); }
|
||||
.caption-style-panel .compact-slider { margin: 2px 0; }
|
||||
.tool-helper-copy { margin: 0; color: #8fa0ab; font-size: 12px; line-height: 1.5; }
|
||||
.inline-caption-editor { position: absolute; z-index: 12; transform: translate(-50%, -50%); margin: 0; }
|
||||
.inline-caption-editor input { width: min(260px, 45vw); padding: 9px 11px; border: 1px solid #37e8d8; border-radius: 7px; outline: none; color: #f5ffff; background: rgba(7,14,18,.92); box-shadow: 0 8px 30px rgba(0,0,0,.35); }
|
||||
.generated-voice-result { display: grid; gap: 9px; padding: 11px; border: 1px solid rgba(55,232,216,.28); border-radius: 9px; background: rgba(55,232,216,.07); }
|
||||
.generated-voice-result > div { display: flex; gap: 8px; color: #37e8d8; }
|
||||
.generated-voice-result span { display: grid; gap: 2px; }
|
||||
@@ -1889,9 +1895,9 @@ button:disabled {
|
||||
.caption-style-heading { display: grid; gap: 2px; }
|
||||
.caption-style-heading strong { font-size: 13px; color: #eaf7f7; }
|
||||
.caption-style-heading span { font-size: 11px; color: #82909c; }
|
||||
.caption-style-presets { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 7px; }
|
||||
.caption-style-presets { display: grid; grid-template-columns: minmax(0, 1.35fr) repeat(2, minmax(0, 1fr)); gap: 8px; }
|
||||
.caption-color-row { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; }
|
||||
.caption-style-presets button { min-width: 0; min-height: 38px; padding: 7px 9px; border: 1px solid rgba(255,255,255,.08); border-radius: 6px; color: #b8c5cd; font-size: 12px; line-height: 1.2; white-space: normal; overflow-wrap: anywhere; background: rgba(255,255,255,.04); cursor:pointer; }
|
||||
.caption-style-presets button { min-width: 0; min-height: 36px; padding: 6px 4px; border: 1px solid rgba(255,255,255,.08); border-radius: 6px; color: #b8c5cd; font-size: 10px; line-height: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; background: rgba(255,255,255,.04); cursor:pointer; }
|
||||
.caption-style-presets button.is-active { color: #061515; border-color: #37e8d8; background: #37e8d8; }
|
||||
.caption-color-row label { display:grid; gap:4px; color:#93a0aa; font-size:11px; }
|
||||
.caption-color-row input { width:100%; height:28px; padding:2px; border:1px solid rgba(255,255,255,.1); border-radius:5px; background:#0c1015; }
|
||||
@@ -2149,7 +2155,7 @@ button:disabled {
|
||||
.visual-effects-panel { gap: 12px; }
|
||||
.visual-effects-panel > .tool-panel { padding: 0; }
|
||||
.visual-effects-panel > .tool-panel > h2 { font-size: 13px; color: #9ba9b2; }
|
||||
.visual-context-tabs { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 4px; padding: 4px; border: 1px solid rgba(255,255,255,.075); border-radius: 9px; background: rgba(4,10,14,.42); }
|
||||
.visual-context-tabs { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 4px; padding: 4px; border: 1px solid rgba(255,255,255,.075); border-radius: 9px; background: rgba(4,10,14,.42); }
|
||||
.visual-context-tabs button { min-width: 0; border: 0; border-radius: 6px; padding: 8px 3px; color: #82919b; background: transparent; font-size: 11px; cursor: pointer; }
|
||||
.visual-context-tabs button:hover { color: #c8d8de; background: rgba(255,255,255,.04); }
|
||||
.visual-context-tabs button.is-active { color: #dffffb; background: rgba(53,234,217,.13); box-shadow: inset 0 0 0 1px rgba(53,234,217,.38); }
|
||||
@@ -2810,6 +2816,33 @@ button:disabled {
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.caption-context-tabs {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.caption-context-tabs button {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.caption-voice-panel {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.caption-voice-hint {
|
||||
margin: 2px 0 12px;
|
||||
border: 1px solid rgba(53, 234, 217, 0.16);
|
||||
border-radius: 7px;
|
||||
padding: 10px 12px;
|
||||
color: #9eabb4;
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
background: rgba(53, 234, 217, 0.055);
|
||||
}
|
||||
|
||||
.caption-voice-panel .field-label:first-of-type {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.caption-context-panel .field-label {
|
||||
margin-top: 2px;
|
||||
}
|
||||
@@ -2846,6 +2879,34 @@ button:disabled {
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.visual-context-empty {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
gap: 8px;
|
||||
min-height: 210px;
|
||||
border: 1px dashed rgba(173, 184, 196, 0.18);
|
||||
border-radius: 8px;
|
||||
padding: 24px 18px;
|
||||
color: #88959f;
|
||||
text-align: center;
|
||||
background: rgba(255, 255, 255, 0.025);
|
||||
}
|
||||
|
||||
.visual-context-empty svg {
|
||||
color: #5eece0;
|
||||
}
|
||||
|
||||
.visual-context-empty strong {
|
||||
color: #dce8ec;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.visual-context-empty span {
|
||||
max-width: 250px;
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.caption-context-actions {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
@@ -2995,29 +3056,74 @@ button:disabled {
|
||||
|
||||
.model-row {
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
gap: 12px;
|
||||
margin-top: 10px;
|
||||
padding: 9px 10px;
|
||||
border-radius: 7px;
|
||||
min-height: 42px;
|
||||
padding: 7px 8px 7px 12px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.045);
|
||||
border-radius: 8px;
|
||||
color: #8b98a4;
|
||||
font-size: 12px;
|
||||
background: rgba(255, 255, 255, 0.045);
|
||||
background: rgba(255, 255, 255, 0.035);
|
||||
}
|
||||
|
||||
.voice-sample-preview {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
padding: 10px;
|
||||
border: 1px solid rgba(136, 184, 255, 0.18);
|
||||
border-radius: 8px;
|
||||
background: rgba(136, 184, 255, 0.06);
|
||||
}
|
||||
|
||||
.voice-sample-preview > div {
|
||||
display: grid;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.voice-sample-preview strong {
|
||||
color: #dce8ef;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.voice-sample-preview span {
|
||||
color: #8b9aa5;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.voice-sample-preview audio {
|
||||
width: 100%;
|
||||
height: 34px;
|
||||
}
|
||||
|
||||
.model-row span:first-child {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
color: #cbd5dc;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.model-row button {
|
||||
flex: 0 0 auto;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
padding: 5px 8px;
|
||||
border-radius: 999px;
|
||||
min-width: 70px;
|
||||
padding: 6px 11px;
|
||||
color: #83eee5;
|
||||
font-size: 12px;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
background: rgba(46, 234, 216, 0.08);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.model-row button:hover {
|
||||
background: rgba(46, 234, 216, 0.14);
|
||||
}
|
||||
|
||||
.slider-field {
|
||||
margin-top: 14px;
|
||||
}
|
||||
@@ -3314,7 +3420,7 @@ button:disabled {
|
||||
|
||||
.timeline-board {
|
||||
display: grid;
|
||||
grid-template-columns: 128px 1fr;
|
||||
grid-template-columns: 164px minmax(0, 1fr);
|
||||
min-height: 0;
|
||||
max-height: min(430px, 48vh);
|
||||
overflow-y: auto;
|
||||
@@ -3328,7 +3434,7 @@ button:disabled {
|
||||
|
||||
.track-labels {
|
||||
display: grid;
|
||||
grid-template-rows: 46px 46px 58px 58px 58px;
|
||||
grid-template-rows: repeat(5, 48px);
|
||||
padding-top: 28px;
|
||||
border-right: 1px solid rgba(255, 255, 255, 0.07);
|
||||
}
|
||||
@@ -3336,8 +3442,8 @@ button:disabled {
|
||||
.track-labels div {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
padding: 0 12px;
|
||||
gap: 6px;
|
||||
padding: 0 10px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.045);
|
||||
color: #c8d3db;
|
||||
font-size: 13px;
|
||||
@@ -3386,11 +3492,14 @@ button:disabled {
|
||||
width: auto;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
padding: 0 0 0 2px;
|
||||
color: inherit;
|
||||
font-size: 13px;
|
||||
font-weight: 650;
|
||||
text-align: left;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
@@ -3410,11 +3519,15 @@ button:disabled {
|
||||
.track-scroll {
|
||||
position: relative;
|
||||
display: grid;
|
||||
grid-template-rows: 28px 46px 46px 58px 58px 58px;
|
||||
grid-template-rows: 28px repeat(5, 48px);
|
||||
min-width: 25%;
|
||||
transition: width 140ms cubic-bezier(0.16, 1, 0.3, 1);
|
||||
}
|
||||
|
||||
.track-scroll.is-wheel-zooming {
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.ruler {
|
||||
position: relative;
|
||||
display: block;
|
||||
@@ -3596,17 +3709,21 @@ button:disabled {
|
||||
}
|
||||
|
||||
.image-thumbnails {
|
||||
display: flex;
|
||||
display: grid;
|
||||
grid-auto-flow: column;
|
||||
grid-auto-columns: var(--thumbnail-cell-width, 84px);
|
||||
align-items: stretch;
|
||||
justify-content: start;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.image-thumbnails img {
|
||||
width: auto;
|
||||
min-width: 42px;
|
||||
display: block;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
height: 36px;
|
||||
flex: 1 1 max(42px, calc(106px * var(--timeline-zoom, 1)));
|
||||
object-fit: cover;
|
||||
user-select: none;
|
||||
-webkit-user-drag: none;
|
||||
@@ -3626,10 +3743,9 @@ button:disabled {
|
||||
}
|
||||
|
||||
.image-thumbnails.is-video img {
|
||||
width: 0;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
height: 36px;
|
||||
flex: 1 1 0;
|
||||
object-fit: cover;
|
||||
background: #05070a;
|
||||
}
|
||||
@@ -4014,14 +4130,14 @@ button:disabled {
|
||||
|
||||
.audio-track {
|
||||
overflow: hidden;
|
||||
padding: 7px 0;
|
||||
padding: 4px 0;
|
||||
}
|
||||
|
||||
.audio-clip {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
height: 44px;
|
||||
height: 40px;
|
||||
container-type: inline-size;
|
||||
}
|
||||
|
||||
@@ -4033,7 +4149,7 @@ button:disabled {
|
||||
|
||||
.audio-track:not(.source-track):not(.music-track) .audio-clip {
|
||||
position: absolute;
|
||||
top: 7px;
|
||||
top: 4px;
|
||||
cursor: grab;
|
||||
}
|
||||
|
||||
@@ -4053,7 +4169,7 @@ button:disabled {
|
||||
|
||||
.audio-clip.is-source.is-linked {
|
||||
position: absolute;
|
||||
top: 7px;
|
||||
top: 4px;
|
||||
}
|
||||
|
||||
.audio-clip.is-source .waveform-strip span {
|
||||
@@ -4241,7 +4357,7 @@ button:disabled {
|
||||
align-items: center;
|
||||
gap: 1px;
|
||||
width: 100%;
|
||||
height: 54px;
|
||||
height: 40px;
|
||||
overflow: hidden;
|
||||
border: 1px solid rgba(41, 225, 204, 0.52);
|
||||
border-radius: 6px;
|
||||
@@ -4251,7 +4367,7 @@ button:disabled {
|
||||
|
||||
.waveform-strip span {
|
||||
width: auto;
|
||||
height: calc(7px + var(--bar) * 37px);
|
||||
height: calc(4px + var(--bar) * 22px);
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
border-radius: 999px;
|
||||
@@ -4259,6 +4375,63 @@ button:disabled {
|
||||
background: #20d2bf;
|
||||
}
|
||||
|
||||
@container (max-width: 160px) {
|
||||
.waveform-strip {
|
||||
padding-inline: 6px;
|
||||
}
|
||||
|
||||
.waveform-strip span {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.waveform-strip span:nth-child(2n + 1) {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
@container (max-width: 96px) {
|
||||
.waveform-strip {
|
||||
padding-inline: 4px;
|
||||
}
|
||||
|
||||
.waveform-strip span:nth-child(2n + 1) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.waveform-strip span:nth-child(4n + 1) {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
@container (max-width: 52px) {
|
||||
.waveform-strip {
|
||||
padding-inline: 3px;
|
||||
}
|
||||
|
||||
.waveform-strip span:nth-child(4n + 1) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.waveform-strip span:nth-child(8n + 1) {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
@container (max-width: 28px) {
|
||||
.waveform-strip {
|
||||
gap: 0.5px;
|
||||
padding-inline: 2px;
|
||||
}
|
||||
|
||||
.waveform-strip span:nth-child(8n + 1) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.waveform-strip span:nth-child(16n + 1) {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
.audio-clip-duration {
|
||||
position: absolute;
|
||||
right: 8px;
|
||||
|
||||
Reference in new issue
Block a user