Merge pull request #20 from MartinDelophy/codex/v0.4.0-release

Release Timeline Studio v0.4.0
This commit is contained in:
Martin Delophy authored and GitHub committed 2026-07-18 16:07:24 +08:00
commit c1e5719e1f
66 files changed
+2246 -545

No files matched your search

+47 -190
View File
@@ -1,229 +1,86 @@
# Timeline Studio — Browser AI Video Editor
Language: **English** | [中文](README.zh-CN.md)
**English** | [中文](README.zh-CN.md)
[![Live Demo](https://img.shields.io/badge/Live_Demo-Timeline_Studio-35ead9?style=flat-square)](https://video-editor.ai-creator.top/)
[![Hugging Face Space](https://img.shields.io/badge/%F0%9F%A4%97_Hugging_Face-Space-ffd21e?style=flat-square)](https://huggingface.co/spaces/haixin/timeline-studio)
[![GitHub stars](https://img.shields.io/github/stars/MartinDelophy/ai-video-editor?style=flat-square)](https://github.com/MartinDelophy/ai-video-editor/stargazers)
[![GitHub forks](https://img.shields.io/github/forks/MartinDelophy/ai-video-editor?style=flat-square)](https://github.com/MartinDelophy/ai-video-editor/forks)
[![GitHub release](https://img.shields.io/github/v/release/MartinDelophy/ai-video-editor?style=flat-square)](https://github.com/MartinDelophy/ai-video-editor/releases)
[![MIT License](https://img.shields.io/github/license/MartinDelophy/ai-video-editor?style=flat-square)](LICENSE)
[![Discord](https://img.shields.io/discord/1526147673290313768?label=Discord&logo=discord&style=flat-square)](https://discord.gg/uq2uvUTBr)
A local-first, browser-based AI video editor with ONNX voiceover generation, Whisper automatic captions, JoyVASA + LivePortrait talking avatars, multi-track timeline editing, and MP4/WebM export. Timeline Studio runs its core AI workflows directly in the browser and is inspired by modern editors such as CapCut.
Timeline Studio is a local-first AI video editor that runs in the browser. It combines a CapCut-style multi-track timeline with browser-side AI voiceovers, automatic captions, vision tools, talking-avatar generation, and deterministic offline export.
## Demo Video
[Open the editor](https://video-editor.ai-creator.top/) · [Watch the demo](https://youtu.be/mUXduGpBmwE) · [Hugging Face Space](https://huggingface.co/spaces/haixin/timeline-studio)
[Watch the AI video editor demo on YouTube](https://youtu.be/mUXduGpBmwE)
![Timeline Studio editor](docs/screenshots/editor-timeline.png)
## Screenshots
## AI capabilities
### English editor workspace
- **Multilingual voiceover:** Chinese Piper/VITS ONNX voices, English Kokoro 82M, and browser Piper voices for German, Spanish, French, Italian, and Brazilian Portuguese.
- **Automatic captions:** Whisper small q8 ONNX with waveform-aware timing and conservative Chinese recognition cleanup.
- **Smart framing:** YOLOS tiny subject detection and MODNet portrait matting for smart crop, caption avoidance, and background removal across images and complete videos.
- **AI vocal separation:** isolate vocals and place the instrumental stem on the music track without leaving the browser workflow.
- **Digital human:** JoyVASA audio-to-motion and LivePortrait neural rendering with WebGPU, 256px preview and 512px quality paths.
- **Local-first inference:** large models are lazy-loaded, revision-pinned, and cached by the service worker; supported workflows run without uploading project media to an editing backend.
![English editor workspace](docs/screenshots/editor-empty-en.png)
## Editing and export
### Timeline editing and AI voiceover workspace
- Contiguous main Visuals track plus timed picture-in-picture overlays.
- Direct canvas selection, movement, proportional resize, rotation, masks, filters, effects, animation, speed, and explicit keyframes.
- Captions, stickers, voiceover, separated source audio, and music on independent timed tracks.
- CapCut-style snapping, alignment guides, clip menus, split/duplicate/delete, timeline zoom, undo/redo, and portable `.timeline` projects.
- Native media playback for a responsive preview; export uses a separate deterministic offline rendering path.
- WebCodecs MP4/WebM composition with shared preview/export geometry, audio mixing, captions, overlays, effects, and MediaRecorder fallback.
- Installable PWA with a cached app shell and multilingual UI.
![Timeline editing and AI voiceover workspace](docs/screenshots/editor-timeline.png)
## Agent Skill
### Voiceover and caption alignment
The repository includes [`edit-timeline-studio`](skills/edit-timeline-studio/SKILL.md), a Codex-compatible Skill for planning, executing, and verifying editable video timelines.
![Voiceover and caption alignment](docs/screenshots/voice-caption-alignment.png)
It helps an agent:
### Export progress overlay
- inspect media and preserve the user's editing brief;
- describe reversible edits with stable clip IDs and explicit timestamps;
- operate the hosted or local editor through the browser compatibility path;
- validate declarative edit plans with `skills/edit-timeline-studio/scripts/validate_edit_plan.mjs`;
- verify track placement, transitions, captions, overlays, audible audio, and final export artifacts;
- keep the editable `.timeline` project as the source of truth instead of returning only an opaque render.
![Export progress overlay](docs/screenshots/export-progress.png)
The current Skill is honest about its boundary: browser-driven editing is available today, while the versioned headless command runner described in its command contract is the next automation layer.
## What It Can Do
## Quick start
- Upload local images, videos, and audio files.
- Display uploaded media in a compact grid-based asset library.
- Drag assets from the media library into matching timeline tracks.
- Arrange, reorder, split, delete, and resize visual clips on the image/video track.
- Preview a project even before generating voiceover audio.
- Generate AI voiceover from typed scripts.
- Insert every generated voiceover at the current playhead without replacing existing audio.
- Automatically create additional voiceover and caption lanes when clips overlap, then compact them again when overlaps are removed.
- Keep generated captions bound to their matching voiceover clip when moving, duplicating, or deleting it.
- Edit voiceover clip position, volume, fade-in, and fade-out from a dedicated context panel.
- Edit captions by dragging, hiding, deleting, and changing placement or size.
- Navigate a dynamic 30-minute default timeline that expands for longer projects and supports frame-level zoom.
- Upload video and separate its original audio onto a dedicated source-audio track.
- Add background music on a dedicated music track.
- Browse generated sticker packs in a 3x3 infinite-loading sticker panel.
- Drop stickers anywhere on the timeline to automatically create a sticker track under the image/video track.
- Move sticker segments on the timeline and render sticker overlays in preview/export.
- Use multi-track controls: visibility, lock, delete, duplicate, split, zoom, snap, and reorder.
- Apply filters, visual effects, stickers, and transition presets.
- Detect the primary subject in an image or scan a complete video into a timestamped YOLOS tiny subject track in a browser worker.
- Generate transparent portrait cutouts with MODNet; videos are pre-analyzed into a full-duration temporal mask track used by preview and export.
- Use normalized subject geometry for smart caption avoidance and subject-aware cropping across aspect ratios.
- Generate a talking portrait from a front-facing image and the current voiceover with the browser JoyVASA audio driver and LivePortrait neural renderer.
- Choose a mixed-FP16 256px fast-preview path or a mixed-FP16 512px quality path, with adaptive neural keyframes and WebM visual-track replacement.
- Export MP4 when browser support is available, with WebM fallback.
- Show export progress during browser-side rendering.
- Persist language selection in `localStorage`.
## Recent Prototype Updates
- Added timeline-native sticker overlays with generated PNG sticker assets, automatic sticker-track creation, movable sticker clips, and a cleaner scrollbar-free sticker picker.
- Added installable PWA metadata, app icons, service-worker app shell/model caching, and cached sticker assets for faster repeat sessions.
- Added browser-side automatic caption groundwork using Whisper ONNX workers, plus timeline snapping/alignment improvements for captions, source audio, and generated voiceover.
- Added lazy-loaded YOLOS tiny and MODNet vision workers with subject overlays, portrait matting, caption avoidance, and preview/export-consistent smart crop geometry.
- Added an end-to-end browser talking-avatar pipeline: JoyVASA audio-to-motion ONNX, LivePortrait WebGPU rendering, adaptive 1–2fps neural keyframes, safe frame holding at the output frame rate, and automatic visual-track replacement.
- Added playhead-based multi-voiceover insertion, automatic overlapping audio/caption lanes, linked caption movement, audio clip properties, and a dynamically expanding 30-minute timeline.
- Moved the 906MB avatar model bundle to the revision-pinned [Timeline Studio ONNX model repository](https://huggingface.co/haixin/timeline-studio-onnx-models/tree/a201b681c8f96672b5c3f624e32d4dc932f150af), keeping large model binaries out of this Git repository.
## AI Features
Current AI capabilities are designed to run in the browser as much as possible:
- Text-to-speech with ONNX/browser engines.
- Chinese voiceover via Piper/VITS browser ONNX models.
- English voice options via Kokoro 82M ONNX.
- Automatic caption generation with Whisper small q8 ONNX running through a browser WASM worker, waveform-aware timestamp snapping, and conservative Chinese homophone cleanup.
- Lightweight voice preview and generation history restore.
- Script-to-caption timeline alignment based on generated audio duration.
- Browser voice recording for manually captured narration.
- Local waveform decoding for voiceover, source audio, and background music.
- YOLOS tiny q8 ONNX subject detection and MODNet q8 ONNX portrait matting with revision-pinned, service-worker-cached model assets.
- JoyVASA and LivePortrait ONNX talking-avatar generation with WebGPU execution, mixed-FP16 generators, GPU feature reuse, parallel model-part downloads, and explicit GPU-session isolation between the two large pipelines.
Talking-avatar model files are loaded from Hugging Face at the immutable revision `a201b681c8f96672b5c3f624e32d4dc932f150af`. Generated keyframes are checked for non-finite or temporally anomalous output; a suspect frame is retried once and, if necessary, replaced with the previous valid frame instead of being encoded as a corrupted texture.
MODNet is portrait-oriented, while YOLOS tiny covers common COCO categories. Images support the full matting path. Videos are pre-analyzed across their full duration before export, then resolve timestamped YOLOS geometry and MODNet masks for preview, caption avoidance, smart crop, and every rendered export time instead of freezing the first-frame result. Long videos automatically use a wider temporal sampling interval to keep WASM inference and memory bounded.
## Multilingual UI
The editor includes a first-run language picker and stores the chosen language locally.
Currently included languages:
- Chinese
- English
- Japanese
- Korean
- Spanish
- French
- German
- Portuguese
- Thai
- Vietnamese
The language picker includes English guidance so non-Chinese users can understand the first screen.
## Future AI Roadmap
Planned or desirable AI capabilities:
- Subtitle translation and multi-language caption refinement.
- AI script writing and rewrite modes for marketing, education, short video, and product demos.
- Voice cloning or custom speaker adaptation, with explicit consent and privacy controls.
- Multi-speaker dubbing and role-based dialogue generation.
- Smart alignment between narration, captions, images, and visual beats.
- AI scene detection for uploaded videos.
- Automatic highlight extraction from long videos.
- AI background music recommendation and beat matching.
- Noise reduction, loudness normalization, and vocal enhancement.
- General-purpose product/animal segmentation and offline per-frame video background removal.
- Cloud-assisted model loading for larger models while keeping an offline/local-first mode.
- Batch export and template-based video generation.
## Tech Stack
- React 19
- Vite 6
- ONNX/browser TTS dependencies
- `@ffmpeg/ffmpeg` for browser-side media processing support
- Browser MediaRecorder/export pipeline
- Phosphor Icons
- Netlify deployment configuration
## Project Structure
```text
src/
App.jsx
components/
PreviewStage.jsx
Timeline.jsx
Topbar.jsx
VoicePanel.jsx
panels.jsx
ui.jsx
config/
editor.js
models.js
joyVasa.js
livePortrait.js
lib/
asr.js
media.js
serviceWorker.js
timeline.js
timelineScale.js
ttsText.js
vision.js
visualGeometry.js
workers/
joyvasa.worker.js
liveportrait.worker.js
vision.worker.js
i18n.js
main.jsx
styles.css
public/
assets/
stickers/
icons/
manifest.webmanifest
model-cache-sw.js
netlify.toml
```
## Local Development
Requirements: Node.js 20+ and a modern Chromium browser. WebGPU is recommended for the heaviest AI workflows.
```bash
git clone https://github.com/MartinDelophy/ai-video-editor.git
cd ai-video-editor
npm install
npm run dev
```
Build for production:
Open the local URL printed by Vite. The first AI run may download model files; later runs reuse the browser cache.
## Validate and build
```bash
npm test
npm run build
```
Preview the production build:
```bash
npm run preview
```
## Deployment
Run the complete repository check with:
This project includes Netlify configuration:
```bash
npm run check
```
## Deploy
The included [`netlify.toml`](netlify.toml) builds with `npm run build`, publishes `dist`, enables the cross-origin isolation headers required by browser AI/media workers, and provides the SPA fallback.
```bash
npm run build
npx netlify-cli deploy --prod --dir=dist
```
`netlify.toml` defines:
- build command: `npm run build`
- publish directory: `dist`
- SPA fallback redirect to `index.html`
## License
Released under the [MIT License](LICENSE). You may use, modify, and distribute this project with attribution.
## Community
Join the Discord community for questions, feedback, and project updates:
[Join the Timeline Studio Discord](https://discord.gg/uq2uvUTBr)
The current star count is updated live in the GitHub Stars badge at the top of this README.
[View current stargazers](https://github.com/MartinDelophy/ai-video-editor/stargazers) · [Star Timeline Studio](https://github.com/MartinDelophy/ai-video-editor)
[MIT](LICENSE)
+43 -171
View File
@@ -1,214 +1,86 @@
# Timeline Studio — 浏览器 AI 视频编辑器
语言:[English](README.md) | **中文**
[English](README.md) | **中文**
[![在线体验](https://img.shields.io/badge/在线体验-Timeline_Studio-35ead9?style=flat-square)](https://video-editor.ai-creator.top/)
[![Hugging Face Space](https://img.shields.io/badge/%F0%9F%A4%97_Hugging_Face-Space-ffd21e?style=flat-square)](https://huggingface.co/spaces/haixin/timeline-studio)
[![GitHub Stars](https://img.shields.io/github/stars/MartinDelophy/ai-video-editor?style=flat-square)](https://github.com/MartinDelophy/ai-video-editor/stargazers)
[![GitHub Forks](https://img.shields.io/github/forks/MartinDelophy/ai-video-editor?style=flat-square)](https://github.com/MartinDelophy/ai-video-editor/forks)
[![GitHub Release](https://img.shields.io/github/v/release/MartinDelophy/ai-video-editor?style=flat-square)](https://github.com/MartinDelophy/ai-video-editor/releases)
[![MIT License](https://img.shields.io/github/license/MartinDelophy/ai-video-editor?style=flat-square)](LICENSE)
[![Discord](https://img.shields.io/discord/1526147673290313768?label=Discord&logo=discord&style=flat-square)](https://discord.gg/uq2uvUTBr)
一个本地优先的浏览器 AI 视频编辑器,支持 ONNX AI 配音、Whisper 自动字幕、JoyVASA + LivePortrait 数字人、多轨时间线以及 MP4/WebM 导出。核心 AI 流程直接在浏览器运行,交互参考 CapCut/剪映等现代时间线编辑器。
Timeline Studio 是一个本地优先、直接运行在浏览器中的 AI 视频编辑器。它把接近剪映/CapCut 的多轨时间线,与浏览器 AI 配音、自动字幕、智能画面、数字人和确定性离线导出结合在一起。
## 演示视频
[打开在线编辑器](https://video-editor.ai-creator.top/) · [观看演示](https://youtu.be/mUXduGpBmwE) · [Hugging Face Space](https://huggingface.co/spaces/haixin/timeline-studio)
[在 YouTube 观看 AI 视频编辑器演示](https://youtu.be/mUXduGpBmwE)
![Timeline Studio 编辑器](docs/screenshots/editor-timeline.png)
## 界面截图
## AI 能力
### 英文编辑工作台
- **多语言 AI 配音:** 中文 Piper/VITS ONNX、英文 Kokoro 82M,以及德语、西班牙语、法语、意大利语和巴西葡萄牙语的浏览器 Piper 声音。
- **自动字幕:** Whisper small q8 ONNX,结合音频能量修正时间戳,并对中文识别结果做克制的高置信纠错。
- **智能画面:** YOLOS tiny 主体检测与 MODNet 人像抠图,用于图片和完整视频的智能裁切、字幕避让与背景移除。
- **AI 人声分离:** 在浏览器工作流中提取人声,并把伴奏放入音乐轨。
- **数字人:** JoyVASA 音频驱动 + LivePortrait 神经渲染,支持 WebGPU、256px 快速预览与 512px 高质量路径。
- **本地优先推理:** 大模型按需加载、锁定版本并由 Service Worker 缓存;受支持的流程不需要把项目素材上传到编辑后端。
![英文编辑工作台](docs/screenshots/editor-empty-en.png)
## 剪辑与导出
### 时间线编辑与 AI 配音工作区
- 连续主画面轨,以及可自由定时的画中画图层。
- 在画布中直接选择、移动、等比缩放和旋转,并支持遮罩、滤镜、效果、动画、速度与显式关键帧。
- 字幕、贴纸、配音、分离后的视频原声和背景音乐使用独立时间轨。
- 支持磁吸、全轨对齐线、右键菜单、切分/复制/删除、双指缩放、撤销重做和可移植 `.timeline` 项目。
- 播放预览使用原生媒体路径保证流畅;导出使用独立的确定性离线渲染路径。
- WebCodecs MP4/WebM 合成统一处理画面、音频混音、字幕、画中画、效果与变换,并提供 MediaRecorder 兼容回退。
- 支持安装为 PWA,缓存应用外壳,并提供多语言界面。
![时间线编辑与 AI 配音工作区](docs/screenshots/editor-timeline.png)
## Agent Skill
### 配音与字幕对齐
仓库包含 Codex 兼容的 [`edit-timeline-studio`](skills/edit-timeline-studio/SKILL.md) Skill,用于规划、执行和验证可继续编辑的视频时间线。
![配音与字幕对齐](docs/screenshots/voice-caption-alignment.png)
它可以帮助 Agent:
### 导出进度浮层
- 检查素材并保留用户的原始剪辑意图;
- 使用稳定片段 ID 和明确秒数描述可撤销的编辑计划;
- 通过浏览器兼容路径操作在线版或本地编辑器;
- 使用 `skills/edit-timeline-studio/scripts/validate_edit_plan.mjs` 校验声明式编辑计划;
- 验证轨道位置、转场、字幕、画中画、实际可听音频和最终导出文件;
- 始终保留可编辑的 `.timeline` 项目,而不是只交付不可逆的视频成片。
![导出进度浮层](docs/screenshots/export-progress.png)
当前 Skill 会明确说明能力边界:现阶段已经可以通过浏览器驱动编辑;Skill 中的版本化无头命令协议是下一阶段自动化层,不会把尚未实现的 CLI 描述成现成功能。
## 当前能力
## 快速启动
- 本地上传图片、视频、音频素材。
- 素材库使用紧凑九宫格展示本地上传资源。
- 素材可从媒体库拖拽到匹配的时间线轨道。
- 图片/视频轨道支持多片段、拖拽排序、切分、删除和缩放时长。
- 无需先生成配音,也可以播放图片/视频时间线预览。
- 可根据输入文案生成 AI 配音。
- 每次生成的配音会按当前播放头新增,不会替换已有音频。
- 配音或字幕发生时间重叠时自动创建新子轨,不再重叠后自动收拢。
- 生成字幕与对应配音片段绑定,移动、复制或删除配音时同步联动。
- 选中配音片段后,可在右侧调整时间轴位置、音量、淡入和淡出。
- 默认使用可动态扩展的 30 分钟时间轴,并支持放大到帧级刻度。
- 字幕可拖动、隐藏、删除,并支持位置和字号调整。
- 上传视频后,可把视频原声分离到独立原声轨。
- 支持独立背景音乐轨。
- 支持多轨道控制:显示/隐藏、锁定、删除、复制、切分、缩放、磁吸和重排。
- 支持滤镜、视觉效果、贴纸和转场预设。
- 使用 YOLOS tiny 在浏览器 Worker 中识别图片主体,或扫描整段视频生成带时间戳的主体轨迹。
- 使用 MODNet 为图片生成透明人像抠图;视频会先生成覆盖全片的时序遮罩,再用于播放与导出。
- 基于归一化主体框自动做字幕避让和跨画幅智能裁切。
- 使用当前正脸图片与配音,通过浏览器 JoyVASA 音频驱动和 LivePortrait 神经渲染生成数字人口型视频。
- 数字人支持混合 FP16 256px 快速预览与 512px 高质量档、自适应神经关键帧以及自动替换画面轨。
- 浏览器支持时导出 MP4,不支持时回退到 WebM。
- 本地渲染导出时显示导出进度。
- 首次语言选择会保存到 `localStorage`。
## 最近更新
- 完成 JoyVASA 音频到运动 ONNX 与 LivePortrait WebGPU 的浏览器端到端数字人链路。
- 使用自适应 1–2fps 神经关键帧、输出帧保持和画面轨自动替换,避免整张人脸交叉淡化造成重影。
- 将约 906MB 数字人模型迁移到锁定 revision 的 [Timeline Studio ONNX 模型仓库](https://huggingface.co/haixin/timeline-studio-onnx-models/tree/a201b681c8f96672b5c3f624e32d4dc932f150af),Git 仓库不再保存大模型二进制文件。
- 新增播放头位置配音插入、音频/字幕自动分轨、绑定字幕联动、音频片段属性面板和动态 30 分钟时间轴。
## AI 功能
当前 AI 能力尽量在浏览器端运行:
- 基于 ONNX/browser engine 的文本转语音。
- 中文配音方向:Piper/VITS browser ONNX 模型。
- 英文配音方向:Kokoro 82M ONNX。
- Whisper small q8 ONNX 自动字幕,使用 WASM Worker、波形能量时间戳吸附和保守的中文同音词清理。
- 轻量语音预览和生成历史恢复。
- 根据生成音频时长对齐文案字幕时间线。
- 浏览器录音,可手动录制旁白并写入配音轨。
- 本地解析配音、视频原声、背景音乐波形。
- YOLOS tiny q8 ONNX 主体检测与 MODNet q8 ONNX 人像抠图,模型按需加载并由 Service Worker 缓存。
- JoyVASA + LivePortrait ONNX 数字人生成,包含 WebGPU 推理、混合 FP16 生成器、人物 GPU 特征复用、模型分片并行下载,以及两套大型 GPU 模型之间的显存隔离。
数字人模型固定从 Hugging Face revision `a201b681c8f96672b5c3f624e32d4dc932f150af` 加载。每个神经关键帧都会检查非有限数值和时序离群;异常帧会原位重推一次,仍异常则沿用上一正常帧,不会把损坏纹理编码进视频。
MODNet 主要面向人像抠图,YOLOS tiny 覆盖 COCO 常见类别。图片支持完整抠图;视频采用导出前全片预分析,按时间解析 YOLOS 主体轨迹与 MODNet 遮罩,因此预览、字幕避让、智能裁切和导出不再静态复用首帧。为控制浏览器内存与 WASM 推理耗时,长视频会自动降低时序采样密度并在相邻主体帧之间插值。
## 多语言界面
编辑器提供首次进入语言选择,并将选择保存到本地。
当前包含语言:
- 中文
- English
- 日本語
- 한국어
- Español
- Français
- Deutsch
- Português
- ไทย
- Tiếng Việt
语言选择首屏包含英文说明,方便非中文用户理解第一步操作。
## 后续 AI Roadmap
计划或值得支持的 AI 能力:
- 字幕翻译和多语言字幕润色。
- 面向营销、教育、短视频、产品演示等场景的 AI 文案生成和改写。
- 声音克隆或自定义说话人适配,并提供明确授权和隐私控制。
- 多角色配音和对话生成。
- 旁白、字幕、图片和视觉节奏点的智能对齐。
- 上传视频的 AI 场景检测。
- 长视频自动高光提取。
- AI 背景音乐推荐和节拍匹配。
- 降噪、响度标准化和人声增强。
- 更通用的商品/动物分割与视频逐帧背景移除。
- 在保留离线/本地优先模式的同时,支持云端辅助加载更大模型。
- 批量导出和基于模板的视频生成。
## 技术栈
- React 19
- Vite 6
- ONNX/browser TTS 相关依赖
- `@ffmpeg/ffmpeg` 浏览器端媒体处理支持
- Browser MediaRecorder/export pipeline
- Phosphor Icons
- Netlify 部署配置
## 项目结构
```text
src/
App.jsx
components/
PreviewStage.jsx
Timeline.jsx
Topbar.jsx
VoicePanel.jsx
panels.jsx
ui.jsx
config/
editor.js
joyVasa.js
livePortrait.js
lib/
media.js
timeline.js
vision.js
visualGeometry.js
workers/
joyvasa.worker.js
liveportrait.worker.js
vision.worker.js
i18n.js
main.jsx
styles.css
public/
assets/
netlify.toml
```
## 本地开发
建议使用 Node.js 20+ 和现代 Chromium 浏览器;运行大型 AI 模型时推荐 WebGPU。
```bash
git clone https://github.com/MartinDelophy/ai-video-editor.git
cd ai-video-editor
npm install
npm run dev
```
生产构建:
打开 Vite 输出的本地地址即可。首次使用某项 AI 能力时可能需要下载模型,后续会复用浏览器缓存。
## 验证与构建
```bash
npm test
npm run build
npm run preview
```
预览生产构建:
运行完整仓库检查:
```bash
npm run preview
npm run check
```
## 部署
项目包含 Netlify 配置:
仓库中的 [`netlify.toml`](netlify.toml) 会执行 `npm run build`、发布 `dist`、配置 SPA 回退,并启用浏览器 AI/媒体 Worker 所需的跨域隔离响应头。
```bash
npm run build
npx netlify-cli deploy --prod --dir=dist
```
`netlify.toml` 定义了:
- 构建命令:`npm run build`
- 发布目录:`dist`
- SPA fallback redirect 到 `index.html`
## License
本项目采用 [MIT License](LICENSE)。在保留版权声明的前提下,可以自由使用、修改和分发。
## 社区
欢迎加入 Discord 社区,交流使用问题、产品建议和项目进展:
[加入 Timeline Studio Discord 社区](https://discord.gg/uq2uvUTBr)
README 顶部的 GitHub Stars 徽章会实时显示当前 Star 数量。
[查看当前 Stargazers](https://github.com/MartinDelophy/ai-video-editor/stargazers) · [为 Timeline Studio 点 Star](https://github.com/MartinDelophy/ai-video-editor)
[MIT](LICENSE)
Binary file not shown.

After

Width:  |  Height:  |  Size: 198 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

+51
View File
@@ -0,0 +1,51 @@
import { expect, test } from "@playwright/test";
test("offline export restores enabled embedded video audio when no separated source track exists", async ({ page }) => {
test.setTimeout(180_000);
await page.goto("/");
const result = await page.evaluate(async () => {
const [{ exportOfflineVideo }, { prepareEmbeddedVideoAudio }] = await Promise.all([
import("/src/lib/offlineVideoExport.js"),
import("/src/lib/embeddedVideoAudioExport.js"),
]);
const canvas = document.createElement("canvas"); canvas.width = 160; canvas.height = 90;
const context = canvas.getContext("2d"); context.fillStyle = "#254fd4"; context.fillRect(0, 0, 160, 90);
const image = canvas.toDataURL("image/png");
const sampleRate = 48_000; const frames = sampleRate / 2;
const wav = new ArrayBuffer(44 + frames * 2); const view = new DataView(wav);
const write = (offset, value) => [...value].forEach((char, index) => view.setUint8(offset + index, char.charCodeAt(0)));
write(0, "RIFF"); view.setUint32(4, 36 + frames * 2, true); write(8, "WAVEfmt ");
view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, 1, true);
view.setUint32(24, sampleRate, true); view.setUint32(28, sampleRate * 2, true);
view.setUint16(32, 2, true); view.setUint16(34, 16, true); write(36, "data"); view.setUint32(40, frames * 2, true);
for (let index = 0; index < frames; index += 1) view.setInt16(44 + index * 2, Math.sin(index / sampleRate * Math.PI * 2 * 440) * 9000, true);
const voice = new Blob([wav], { type: "audio/wav" });
const source = await exportOfflineVideo({
imageSrc: image, visualType: "image", visualSegments: [{ id: "image", src: image, type: "image", duration: 0.5 }],
voiceAudioSegments: [{ id: "voice", blob: voice, start: 0, duration: 0.5, volume: 1 }],
sourceAudioBlob: null, sourceAudioSegments: [], musicBlob: null, text: "", captionSegments: [],
duration: 0.5, ratio: { width: 16, height: 9 }, fitMode: "cover", filter: "none", captionsEnabled: false,
captionSize: 12, captionStyle: {}, captionReferenceSize: { width: 160, height: 90 }, stickerSegments: [],
exportSettings: { codec: "vp9", width: 160, height: 90, frameRate: 24, videoBitsPerSecond: 800_000 },
});
const sourceUrl = URL.createObjectURL(source.blob);
const visuals = [{ id: "video", assetId: "video-asset", name: "source.webm", src: sourceUrl, blob: source.blob, type: "video", duration: 0.5, sourceStart: 0, sourceDuration: 0.5, playbackRate: 1 }];
const embedded = await prepareEmbeddedVideoAudio(visuals);
const exported = await exportOfflineVideo({
imageSrc: sourceUrl, visualType: "video", visualSegments: visuals,
voiceAudioSegments: [], sourceAudioBlob: embedded.blob, sourceAudioSegments: embedded.segments,
musicBlob: null, text: "", captionSegments: [], duration: 0.5, ratio: { width: 16, height: 9 },
fitMode: "cover", filter: "none", captionsEnabled: false, captionSize: 12, captionStyle: {},
captionReferenceSize: { width: 160, height: 90 }, stickerSegments: [],
exportSettings: { codec: "vp9", width: 160, height: 90, frameRate: 24, videoBitsPerSecond: 800_000 },
});
const audioContext = new AudioContext();
const decoded = await audioContext.decodeAudioData((await exported.blob.arrayBuffer()).slice(0));
await audioContext.close(); URL.revokeObjectURL(sourceUrl);
return { duration: decoded.duration, samples: decoded.length, segmentCount: embedded.segments.length, size: exported.blob.size };
});
expect(result.segmentCount).toBe(1);
expect(result.duration).toBeGreaterThan(0.45);
expect(result.samples).toBeGreaterThan(20_000);
expect(result.size).toBeGreaterThan(2_000);
});
+7 -1
View File
@@ -18,6 +18,9 @@ test("offline export preserves stickers, captions, voice audio, dimensions and d
context.clearRect(0, 0, 320, 180);
context.fillStyle = "#00ffff"; context.fillRect(120, 50, 80, 80);
});
const overlay = makeImage((context, canvas) => {
context.fillStyle = "#246bff"; context.fillRect(0, 0, canvas.width, canvas.height);
});
const sampleRate = 48_000;
const frames = sampleRate;
const wav = new ArrayBuffer(44 + frames * 2);
@@ -41,6 +44,7 @@ test("offline export preserves stickers, captions, voice audio, dimensions and d
captionReferenceSize: { width: 320, height: 180 },
sticker: null,
stickerSegments: [{ id: "sticker", src: sticker, start: 0, duration: 1, x: 50, y: 50, scale: 2, opacity: 1 }],
visualOverlaySegments: [{ id: "overlay", src: overlay, type: "image", start: 0, duration: 1, layer: 1, keyframes: [{ time: 0, x: 30, y: -25, scale: 0.3, rotation: 0, opacity: 1 }] }],
exportSettings: { codec: "vp9", width: 320, height: 180, frameRate: 30, videoBitsPerSecond: 3_000_000 },
});
const audioContext = new AudioContext();
@@ -56,10 +60,11 @@ test("offline export preserves stickers, captions, voice audio, dimensions and d
const context = sample.getContext("2d"); context.drawImage(video, 0, 0);
const center = [...context.getImageData(160, 90, 1, 1).data];
const lower = [...context.getImageData(160, 156, 1, 1).data];
const overlayPixel = [...context.getImageData(256, 45, 1, 1).data];
const metadata = {
width: video.videoWidth, height: video.videoHeight,
duration: decodedAudio.duration, hasAudio: decodedAudio.length > 0,
mediaDuration: video.duration, center, lower, size: exported.blob.size,
mediaDuration: video.duration, center, lower, overlayPixel, size: exported.blob.size,
diagnostics: exported.diagnostics,
};
URL.revokeObjectURL(url);
@@ -74,6 +79,7 @@ test("offline export preserves stickers, captions, voice audio, dimensions and d
expect(result.center[1]).toBeGreaterThan(result.center[0]);
expect(result.center[2]).toBeGreaterThan(result.center[0]);
expect(result.lower[0] + result.lower[1] + result.lower[2]).toBeGreaterThan(40);
expect(result.overlayPixel[2]).toBeGreaterThan(result.overlayPixel[0]);
expect(result.diagnostics.frameCount).toBe(30);
});
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "web-player",
"version": "0.3.4",
"version": "0.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "web-player",
"version": "0.3.4",
"version": "0.4.0",
"license": "MIT",
"dependencies": {
"@diffusionstudio/vits-web": "^1.0.3",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "web-player",
"version": "0.3.4",
"version": "0.4.0",
"private": true,
"description": "A local-first browser AI video editor for voiceovers, captions, talking avatars, and multi-track timeline export.",
"license": "MIT",
+62
View File
@@ -0,0 +1,62 @@
---
name: edit-timeline-studio
description: Plan, execute, and verify editable video timelines in the Timeline Studio browser editor at https://video-editor.ai-creator.top/ or in its local repository. Use when the user asks an agent to assemble, trim, reorder, caption, voice, overlay, restyle, or export a video through the website, this repository, or a .timeline project archive.
---
# Edit Timeline Studio
Turn the user's exact editorial request and media into reversible Timeline Studio edits. Keep the editable timeline as the source of truth; never replace it with an opaque one-shot render.
## Choose the execution path
1. Treat `https://video-editor.ai-creator.top/` as the canonical hosted editor. When the user asks to use the website, provides no repository, or expects Browser Use, proactively open this URL and inspect the live editor before planning the edit.
2. When this repository is available and the task concerns local development or unpublished changes, start the local editor and use it instead of the hosted release.
3. Look for a Timeline Studio command runner with `npm run agent:help` or the documented equivalent.
4. If it exists, use the command plan in [references/command-contract.md](references/command-contract.md). Validate the plan before applying it.
5. If it does not exist, use the selected editor UI in a browser as a compatibility path. Import media, perform the edits, and visually verify the preview and timeline.
6. Do not claim deterministic Agent execution when only UI automation was available. Report that limitation and preserve the project archive.
## Workflow
### 1. Inspect before editing
- Preserve the user's prompt verbatim as the creative brief.
- Resolve every referenced asset to an explicit path or URL. Never sweep a directory without approval.
- Inspect duration, dimensions, audio presence, and media type.
- Read the current project summary before changing an existing project.
- Ask only when an unresolved choice materially changes the edit, such as the desired output duration or aspect ratio.
### 2. Build a plan
- Express edits as declarative operations with stable IDs, explicit times in seconds, and expected preconditions.
- Prefer semantic operations such as `trim`, `split`, `move`, `add_caption`, and `set_property`; avoid pointer coordinates.
- Keep main Visuals contiguous. Treat captions, stickers, source audio, voiceover, music, and overlays as timed clips.
- Preserve media identity and source-time mapping when moving or trimming clips.
- Include project revision and operation IDs so retries are idempotent.
- Validate JSON plans with `scripts/validate_edit_plan.mjs <plan.json>`.
### 3. Apply safely
- Save a project version or export a `.timeline` archive before a destructive batch.
- Apply one transaction per user-visible intent. Fail the whole transaction when a precondition fails.
- Never silently substitute missing media, voices, models, fonts, or effects.
- Keep every result undoable and editable in the normal UI.
- Do not start a paid or remote generation job without a clear user request.
### 4. Verify the result
- Re-read the timeline summary and compare it with the requested duration, ordering, track placement, and enabled states.
- Preview the opening, every cut or transition, caption boundaries, overlays, and the final frame.
- Check that audible tracks exist and mute/link state matches the request.
- For final export, verify container, dimensions, duration, decoded frames, visible overlays/captions, and a real audio track.
- Return the editable project path and final render path when created.
## UI compatibility path
Open `https://video-editor.ai-creator.top/` proactively when the hosted editor is the selected execution path. Do not search for unofficial mirrors or substitute another editor. Use browser control only until the command runner exists. Operate named controls and visible clip labels, not brittle screen coordinates. After each meaningful edit, confirm the timeline changed as intended. Export a `.timeline` project archive before handing off.
## Capability boundaries
Read [references/current-capabilities.md](references/current-capabilities.md) when deciding whether a request can be executed now. Read [references/command-contract.md](references/command-contract.md) when implementing or invoking the Agent command layer.
If a requested operation is unsupported, keep the valid partial timeline unchanged and state the exact missing command or runtime capability.
@@ -0,0 +1,4 @@
interface:
display_name: "Timeline Studio Agent Editor"
short_description: "Plan, execute, and verify editable timeline video projects"
default_prompt: "Use $edit-timeline-studio to edit these media assets into a polished timeline project."
@@ -0,0 +1,69 @@
# Agent command contract
Use JSON as a transport-neutral plan. The CLI and a future MCP server should call the same application service.
## Plan envelope
```json
{
"schemaVersion": 1,
"project": "/absolute/path/project.timeline",
"baseRevision": 12,
"dryRun": false,
"operations": [
{
"id": "op-001",
"type": "visual.trim",
"clipId": "visual-123",
"sourceIn": 1.2,
"sourceOut": 8.4
}
],
"output": {
"project": "/absolute/path/project-edited.timeline",
"render": "/absolute/path/project-edited.mp4"
}
}
```
All times are finite seconds. IDs are stable across reads and writes. A repeated operation ID must return its prior result without applying twice.
## Minimum read commands
- `project.inspect`: format version, revision, duration, ratio, tracks, media inventory, warnings
- `track.inspect`: ordered or timed clip summaries for one track
- `clip.inspect`: source mapping, timing, transforms, effects, links, analysis records
- `transcript.inspect`: timestamped words/segments and speakers
- `project.diff`: predicted state changes, duration changes, and validation warnings
## Minimum write operations
- `asset.import`
- `visual.append`, `visual.insert`, `visual.trim`, `visual.split`, `visual.reorder`
- `overlay.add`, `timed.move`, `timed.resize`
- `clip.delete`, `clip.set_property`, `clip.set_speed`, `clip.set_muted`
- `caption.add`, `caption.update`, `caption.generate`
- `audio.separate`, `voice.generate`, `music.add`
- `transition.set`, `track.set_visibility`, `track.set_locked`
- `project.set_ratio`, `project.save`, `project.render`
## Result envelope
```json
{
"ok": true,
"revision": 13,
"appliedOperationIds": ["op-001"],
"warnings": [],
"artifacts": {
"project": "/absolute/path/project-edited.timeline",
"render": "/absolute/path/project-edited.mp4"
}
}
```
On failure, return `ok: false`, a stable error `code`, a human-readable `message`, the failing `operationId`, and no partial state unless the operation explicitly permits partial output.
## Architectural rule
Do not implement CLI and MCP editing separately. Both must call a single command registry backed by pure project-state reducers and shared validation. The React UI should eventually dispatch those same commands so manual and Agent edits cannot diverge.
@@ -0,0 +1,41 @@
# Current capability map
## Available in the editor
- Editable main Visuals sequence plus timed picture-in-picture overlays
- Captions, stickers, voiceover, separated source audio, and music tracks
- Visual transforms, property keyframes, masks, filters, effects, speed, and animations
- Automatic captions, multilingual browser TTS, vocal separation, vision analysis, and digital-human generation
- Portable `.timeline` ZIP archives containing `project.json` and media binaries
- Offline WebCodecs composition/export with a recorder fallback
- Undo/redo through the editor history layer
## Available to an Agent today
- Repository inspection and code changes
- Browser-driven operation of the running editor
- Import and export through visible file controls
- Pure timeline helper functions in `src/lib/`
Browser-driven editing is a compatibility mechanism, not a stable public API. UI labels, selection state, drag thresholds, and file pickers make it unsuitable for unattended or idempotent jobs.
## Missing for reliable Agent editing
1. A headless command runner that owns project load, media probing, command application, save, and render.
2. A versioned command schema with stable asset/clip/track IDs and explicit time units.
3. A serializable editor core independent of React setters, DOM nodes, Blob URLs, and browser-only refs.
4. Transactional validation, revision preconditions, idempotency keys, structured errors, undo checkpoints, and dry-run diffs.
5. Read tools at three levels: project summary, track/clip detail, and transcript/analysis detail.
6. Progress events and cancellation for ASR, TTS, vision, avatar generation, and export.
7. Deterministic media ingestion with content hashes and portable asset references.
8. Agent-focused integration tests that apply a command plan, reopen the project, render, decode, and verify the result.
## Recommended delivery order
1. Extract `EditorProjectState` and pure reducers from the existing timeline action modules.
2. Add read-only `project.inspect` and `project.diff` commands.
3. Add core edit commands: import, append, trim, split, move, delete, caption, overlay, property, and track mute/visibility.
4. Wrap command batches in history transactions and persist revision numbers.
5. Add `project.open/save/render` to a local Node/browser-worker runner.
6. Expose the same runner through CLI first; add MCP later as a thin transport adapter.
7. Replace the Skill's UI compatibility path with the CLI while keeping the command contract unchanged.
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env node
import { readFile } from "node:fs/promises";
const path = process.argv[2];
if (!path) {
console.error("Usage: validate_edit_plan.mjs <plan.json>");
process.exit(2);
}
const fail = (message) => {
console.error(`Invalid edit plan: ${message}`);
process.exit(1);
};
let plan;
try {
plan = JSON.parse(await readFile(path, "utf8"));
} catch (error) {
fail(error instanceof Error ? error.message : "cannot read JSON");
}
if (plan?.schemaVersion !== 1) fail("schemaVersion must be 1");
if (typeof plan.project !== "string" || !plan.project.trim()) fail("project must be a non-empty path");
if (!Number.isInteger(plan.baseRevision) || plan.baseRevision < 0) fail("baseRevision must be a non-negative integer");
if (!Array.isArray(plan.operations) || plan.operations.length === 0) fail("operations must be a non-empty array");
const ids = new Set();
for (const [index, operation] of plan.operations.entries()) {
if (!operation || typeof operation !== "object" || Array.isArray(operation)) fail(`operations[${index}] must be an object`);
if (typeof operation.id !== "string" || !operation.id.trim()) fail(`operations[${index}].id is required`);
if (ids.has(operation.id)) fail(`duplicate operation id: ${operation.id}`);
ids.add(operation.id);
if (typeof operation.type !== "string" || !/^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/.test(operation.type)) {
fail(`operations[${index}].type must use namespace.action format`);
}
for (const [key, value] of Object.entries(operation)) {
if (/(?:time|start|end|duration|sourceIn|sourceOut)$/i.test(key) && (typeof value !== "number" || !Number.isFinite(value) || value < 0)) {
fail(`operations[${index}].${key} must be a finite non-negative number`);
}
}
}
console.log(`Valid edit plan: ${plan.operations.length} operation(s), base revision ${plan.baseRevision}`);
+104 -13
View File
@@ -34,7 +34,7 @@ import { useEditorRefs } from "./hooks/useEditorRefs.js";
import { useEditorLifecycle } from "./hooks/useEditorLifecycle.js";
import { useEditorHistory } from "./hooks/useEditorHistory.js";
import { createVisionControls } from "./lib/visionControls.js";
import { createAssetDragControls } from "./lib/assetDragControls.js";
import { createAssetDragControls, resolveVisualDropIntent } from "./lib/assetDragControls.js";
import { createAssetLibraryActions } from "./lib/assetLibraryActions.js";
import { createPlaybackControls } from "./lib/playbackControls.js";
import { createTimelineReorderControls } from "./lib/timelineReorderControls.js";
@@ -55,10 +55,11 @@ import { createTimelineViewModel } from "./lib/timelineViewModel.js";
import { createTranslator, getStoredLanguage, translateOptionName } from "./i18n.js";
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 { normalizeVisualTransform, removeVisualPropertyKeyframe, updateVisualSegmentPlaybackRate, upsertVisualKeyframe, upsertVisualPropertyKeyframe } from "./lib/visualEffects.js";
import { getLinkedSourceAudioEnd, getLinkedSourceAudioSegments, shouldMuteEmbeddedVideoAudio } from "./lib/sourceAudioSync.js";
import { getTimelineInitialContentZoom } from "./lib/timelineScale.js";
import { getExportBitrate, getExportDimensions } from "./lib/exportSettings.js";
import { createVisualOverlaySegment, getVisualOverlayPreset, updateVisualOverlayTransform } from "./lib/visualOverlayTimeline.js";
export function App() {
const [uiLanguage, setUiLanguage] = useState(() => getStoredLanguage());
@@ -66,6 +67,7 @@ export function App() {
const [exportSettings, setExportSettings] = useState({ resolution: "1080", frameRate: 30, codec: "h264", quality: "high" });
const [captionVoiceFocusRequest, setCaptionVoiceFocusRequest] = useState(0);
const [selectedSourceAudioSegmentId, setSelectedSourceAudioSegmentId] = useState("");
const [canvasVisualTarget, setCanvasVisualTarget] = useState("");
const timelineImportRestoreRef = useRef(false);
const [introClosing, setIntroClosing] = useState(false);
const {
@@ -93,7 +95,8 @@ export function App() {
setImageName, setImageSrc, setSelectedFilterId, setSelectedStickerId,
setSelectedStickerSegmentId, setSelectedTransitionId, setSelectedVisualSegmentId,
setStickerSegments, setVisualSegments, setVisualType, stickerSegments, visualSegments,
visualType,
visualType, visualOverlaySegments, selectedVisualOverlayId,
setVisualOverlaySegments, setSelectedVisualOverlayId,
} = useVisualTrackState();
const {
activeTool, assetDragPreview, assetDropPosition, assetDropPulseTrack,
@@ -127,7 +130,7 @@ export function App() {
script, imageSrc, visualType, imageDuration, captionPlacement, selectedVoiceId, speed,
volume, musicName, musicDuration, musicStart, musicVolume, sourceAudioName, sourceAudioDuration,
sourceAudioStart, sourceAudioVolume, ratioId, fitMode, selectedFilterId, selectedStickerId,
captionSegments, visualSegments, visionRecords, timelineZoom,
captionSegments, visualSegments, visualOverlaySegments, visionRecords, timelineZoom,
]);
const {
@@ -163,6 +166,7 @@ export function App() {
sourceAudioAssetId, sourceAudioBlob, sourceAudioDuration, sourceAudioLinked, sourceAudioName, sourceAudioPeaks,
sourceAudioStart, sourceAudioUrl, sourceAudioUrlRef, sourceAudioVolume, stickerSegments,
timelineHorizon, trackLocks, trackVisibility, userAssets, visualSegments, visualType,
visualOverlaySegments, selectedVisualOverlayId, setVisualOverlaySegments, setSelectedVisualOverlayId,
});
const activeLanguage = uiLanguage || "zh";
const t = useMemo(() => createTranslator(activeLanguage), [activeLanguage]);
@@ -190,7 +194,7 @@ export function App() {
captionTargetDuration, captionTimeline, currentCaption, currentCaptions, currentCaptionSegment,
currentSegmentIndex, currentStickerSegment, currentStickerSegmentIndex,
currentVisualRange, currentVisualSegment, currentVisualSegmentIndex, estimatedDuration,
focusedSegmentIndex, getStickerDragAsset, peaks, previewSticker, previewStickers, previewTransition,
focusedSegmentIndex, getStickerDragAsset, peaks, previewSticker, previewStickers, previewVisualOverlays, previewTransition,
previewVisionBaseAnalysis, previewVisionKey, previewVisionRecord, previewVisualLocalTime,
previewVisualRange, previewVisualSegment, previewVisualSegmentIndex,
previewVisualSourceTime, previewVisualSrc, previewVisualType, ratio, segments,
@@ -204,7 +208,7 @@ export function App() {
selectedVisualSegmentId, selectedVoiceId, sourceAudioBlob, sourceAudioDuration,
sourceAudioTimelineEnd,
sourceAudioStart, sourceAudioUrl, stickerSegments, timelineDurationRef, timelineHorizon,
trackVisibility, visionRecords, visualSegments, visualType,
trackVisibility, visionRecords, visualSegments, visualType, visualOverlaySegments,
});
const previousTimelineContentDurationRef = useRef(estimatedDuration);
useEffect(() => {
@@ -228,8 +232,17 @@ export function App() {
}, [estimatedDuration, setCurrentTime, setTimelineHorizon, setTimelineZoom, trackScrollRef]);
const previewFrameSize = usePreviewFrameSize(previewShellRef, ratio, compactRail);
const selectedVisualSegment = visualSegments[selectedVisualSegmentIndex] ?? previewVisualSegment ?? null;
const selectedVisualOverlay = visualOverlaySegments.find((item) => item.id === selectedVisualOverlayId) ?? null;
const selectedVisualRange = visualTimeline[selectedVisualSegmentIndex] ?? previewVisualRange;
const [visualAnimationPreview, setVisualAnimationPreview] = useState(null);
useEffect(() => {
const clearCanvasVisualTarget = (event) => {
if (event.target instanceof Element && event.target.closest(".preview-frame")) return;
setCanvasVisualTarget("");
};
document.addEventListener("pointerdown", clearCanvasVisualTarget);
return () => document.removeEventListener("pointerdown", clearCanvasVisualTarget);
}, []);
const visualLocalTime = Math.max(0, Math.min(
selectedVisualSegment?.duration ?? 0,
currentTime - (selectedVisualRange?.start ?? 0),
@@ -240,6 +253,10 @@ export function App() {
const nextItems = items.map((item) => {
if (item.id !== selectedVisualSegment.id) return item;
if (Number.isFinite(change.playbackRate) && item.type === "video") return updateVisualSegmentPlaybackRate(item, change.playbackRate);
if (change.baseTransform) return {
...item,
baseTransform: normalizeVisualTransform({ ...item.baseTransform, ...change.baseTransform }),
};
if (change.keyframe) return { ...item, keyframes: upsertVisualKeyframe(item.keyframes, change.keyframe.time, change.keyframe) };
if (change.propertyKeyframe) return { ...item, keyframes: upsertVisualPropertyKeyframe(item.keyframes, change.propertyKeyframe.time, change.propertyKeyframe.key, change.propertyKeyframe.value) };
if (change.removePropertyKeyframe) return { ...item, keyframes: removeVisualPropertyKeyframe(item.keyframes, change.removePropertyKeyframe.time, change.removePropertyKeyframe.key) };
@@ -471,6 +488,7 @@ export function App() {
setCaptionSegments, setSelectedAudioSegmentId, setUserAssets, sourceAudioBlob,
sourceAudioLinked, sourceAudioName, selectedSourceAudioSegmentId,
setSelectedSourceAudioSegmentId, stickerSegments, t, trackLocks, visualSegments, visualType,
visualOverlaySegments, selectedVisualOverlayId, setVisualOverlaySegments, setSelectedVisualOverlayId,
});
useEditorLifecycle({
@@ -480,8 +498,10 @@ export function App() {
imageUrlRefs, musicBlob, musicUrlRef, notify, ratioId, replaceAudio,
replaceVisualTimeline, selectedAudioSegmentId, selectedSegmentId,
selectedStickerSegmentId, selectedTrack, selectedVisualSegmentId, setCurrentVisualAsset,
selectedVisualOverlayId, visualOverlaySegments,
setFitMode, setRatioId, setSelectedSegmentId, setSelectedVisualSegmentId,
setUserAssets, sourceAudioBlob, sourceAudioUrlRef, stickerSegments,
setSelectedVisualOverlayId,
visionAbortControllerRef, visionObjectUrlsRef, visualSegments,
voiceRecorderStreamRef, voiceRecorderTimerRef,
});
@@ -551,7 +571,7 @@ export function App() {
const handleFiles = useFileUpload({
appendVisualAssetToTimeline, imageUrlRefs, notify, setSelectedLibraryAssetId, setSelectedTrack, setUserAssets,
updateVisualAssetInTimeline,
updateVisualAssetInTimeline, visualSegments,
});
const { deleteUserAsset, selectAsset } = createAssetLibraryActions({
@@ -563,14 +583,36 @@ export function App() {
});
const { applyAssetToTrack, handleTrackAssetDrop, handleVisualStyleDrop } = createAssetDropActions({
addStickerAssetToTimeline, appendVisualAssetToTimeline, canDropAssetOnTrack,
addStickerAssetToTimeline, addVisualOverlay: (...args) => addVisualOverlay(...args), appendVisualAssetToTimeline, canDropAssetOnTrack,
draggedAssetIdRef, extractVideoSourceAudio, getDraggedAsset, getTimelineDropPercent,
notify, replaceAudio, selectAsset, setActiveTool, setAssetDropPosition,
setAssetDropTargetTrack, setDraggedAssetId, setSelectedFilterId,
setSelectedLibraryAssetId, setSelectedTrack, setSelectedTransitionId,
setSelectedVisualSegmentId, setVisualSegments, trackScrollRef,
setSelectedVisualSegmentId, setVisualSegments, trackScrollRef, resolveVisualDropIntent,
triggerAssetDropPulse,
});
const addVisualOverlay = (asset, options = {}) => {
if (!asset?.src || (asset.type !== "image" && asset.type !== "video")) return;
const startTime = Number.isFinite(options.startTime)
? options.startTime
: Number.isFinite(options.percent)
? options.percent / 100 * timelineDuration
: currentTime;
const overlay = createVisualOverlaySegment(asset, startTime, { layer: options.layer ?? visualOverlaySegments.length + 1 });
setVisualOverlaySegments((items) => [...items, overlay]);
setSelectedVisualOverlayId(overlay.id);
setSelectedVisualSegmentId("");
setSelectedTrack("overlay");
notify("已添加为画中画,可在预览中拖动、缩放和旋转");
};
const updateSelectedVisualOverlay = (transform) => {
const overlay = visualOverlaySegments.find((item) => item.id === selectedVisualOverlayId);
if (!overlay || trackLocks.overlay) return;
const localTime = Math.max(0, currentTime - overlay.start);
setVisualOverlaySegments((items) => items.map((item) => item.id === overlay.id
? updateVisualOverlayTransform(item, localTime, transform)
: item));
};
const { handleExportProject, handleImportProject, handleNewProject } = useProjectFiles({
audioBlob, audioDuration, captionPlacement, captionPosition, captionSegments, captionSize,
@@ -585,10 +627,10 @@ export function App() {
setSelectedStickerSegmentId, setSelectedTransitionId, setSelectedVoiceId, setShowFileMenu,
setSourceAudioAssetId, setSourceAudioLinked, setSourceAudioVolume, setSpeed, setStickerSegments, setTimelineZoom, setTrackVisibility,
setTimelineHorizon,
setVisualSegments, setVolume, setCurrentVisualAsset, sourceAudioBlob, sourceAudioDuration,
setVisualSegments, setVisualOverlaySegments, setSelectedVisualOverlayId, setVolume, setCurrentVisualAsset, sourceAudioBlob, sourceAudioDuration,
markTimelineViewRestored: (hasContent) => { timelineImportRestoreRef.current = hasContent; },
sourceAudioAssetId, sourceAudioLinked, sourceAudioName, sourceAudioStart, sourceAudioVolume, speed, stickerSegments,
timelineZoom, trackVisibility, visualSegments, volume,
timelineZoom, trackVisibility, visualSegments, visualOverlaySegments, volume,
});
const {
@@ -618,6 +660,7 @@ export function App() {
...getExportDimensions(ratio, Number(exportSettings.resolution)),
videoBitsPerSecond: getExportBitrate(Number(exportSettings.resolution), exportSettings.quality, exportSettings.frameRate),
},
visualOverlaySegments, t,
});
const { startCaptionResize, startTimelineClipDrag } = createTimelineReorderControls({
audioSegments, captionSegments, captionTargetDuration, commitCaptionSegments, commitVisualSegments,
@@ -625,6 +668,7 @@ export function App() {
setSelectedVisualSegmentId, setTimelineClipDrag, suppressTimelineClipClickRef,
timelineClipDragRef, timelineDuration, trackLocks, visualSegments, pauseForTimelineEdit,
stickerSegments, sourceAudioDuration, sourceAudioStart, musicDuration, musicStart, setSnapGuide,
visualOverlaySegments, setVisualOverlaySegments, setSelectedVisualOverlayId,
});
return (
@@ -717,11 +761,16 @@ export function App() {
previewShellRef={previewShellRef}
previewCanvasRef={previewCanvasRef}
previewVideoRef={previewVideoRef}
onPreviewVideoTimeUpdate={setPreviewVideoMediaTime}
onPreviewVideoTimeUpdate={previewVisionBaseAnalysis?.kind === "video-timeline" ? setPreviewVideoMediaTime : undefined}
previewVisualSrc={previewVisualSrc}
previewVisualRenderSrc={previewVisualRenderSrc}
previewVisionMaskUrl={previewVisionMaskUrl}
previewVisualType={previewVisualType}
previewVisualMuted={shouldMuteEmbeddedVideoAudio(previewVisualSegment, {
sourceAudioBlob,
sourceAudioAssetId,
linkedSegments: linkedSourceAudioSegments,
})}
previewTransition={previewTransition}
visualEffects={visualAnimationPreview?.segmentId && visualAnimationPreview.segmentId === previewVisualSegment?.id
? { ...previewVisualSegment, animation: visualAnimationPreview.animation }
@@ -731,6 +780,17 @@ export function App() {
: previewVisualLocalTime}
visualMaskEditable={selectedTrack === "image" && Boolean(selectedVisualSegment)}
onUpdateVisualMask={(mask) => updateSelectedVisualEffects({ mask })}
visualTransformEditable={canvasVisualTarget === `visual:${previewVisualSegment?.id ?? ""}` && !isPlaying}
onSelectVisual={() => {
if (!previewVisualSegment?.id) return;
setSelectedVisualSegmentId(previewVisualSegment.id);
setSelectedTrack("image");
setCanvasVisualTarget(`visual:${previewVisualSegment.id}`);
}}
onDeselectVisuals={() => {
setCanvasVisualTarget("");
}}
onUpdateVisualTransform={(transform) => updateSelectedVisualEffects({ baseTransform: transform })}
previewRatio={previewRatio}
previewFrameStyle={previewFrameStyle}
previewFrameSize={previewFrameSize}
@@ -774,6 +834,24 @@ export function App() {
notify={notify}
getDraggedAsset={getDraggedAsset}
applyAssetToTrack={applyAssetToTrack}
addVisualOverlay={addVisualOverlay}
visualOverlays={previewVisualOverlays}
selectedVisualOverlayId={canvasVisualTarget === `overlay:${selectedVisualOverlayId}` ? selectedVisualOverlayId : ""}
onSelectVisualOverlay={(id) => {
setSelectedVisualOverlayId(id);
setSelectedVisualSegmentId("");
setSelectedTrack("overlay");
setCanvasVisualTarget(`overlay:${id}`);
}}
onUpdateVisualOverlay={updateSelectedVisualOverlay}
onReorderVisualOverlay={(id, direction) => setVisualOverlaySegments((items) => {
const ordered = [...items].sort((a, b) => (a.layer || 1) - (b.layer || 1));
const index = ordered.findIndex((item) => item.id === id);
const target = Math.max(0, Math.min(ordered.length - 1, index + direction));
if (index < 0 || index === target) return items;
[ordered[index], ordered[target]] = [ordered[target], ordered[index]];
return ordered.map((item, layer) => ({ ...item, layer: layer + 1 }));
})}
/>
<VoicePanel
@@ -871,6 +949,13 @@ export function App() {
selectedFilterId={selectedFilterId}
setSelectedFilterId={setSelectedFilterId}
trOption={trOption}
selectedVisualOverlay={selectedVisualOverlay}
updateVisualOverlaySegment={(patch) => setVisualOverlaySegments((items) => items.map((item) => item.id === selectedVisualOverlayId ? { ...item, ...patch } : item))}
deleteVisualOverlay={() => handleDeleteTrack()}
applyVisualOverlayPreset={(id) => {
const preset = getVisualOverlayPreset(id);
if (preset) updateSelectedVisualOverlay(preset);
}}
/>
</section>
@@ -910,6 +995,7 @@ export function App() {
assetDropPosition={assetDropPosition}
assetDropPulseTrack={assetDropPulseTrack}
assetDragPreview={assetDragPreview}
draggedAssetType={getActiveDraggedAsset()?.type || assetDragPreview?.type || ""}
handleTrackAssetDragOver={handleTrackAssetDragOver}
handleTrackAssetDragLeave={handleTrackAssetDragLeave}
handleTrackAssetDrop={handleTrackAssetDrop}
@@ -928,8 +1014,13 @@ export function App() {
currentVisualSegment={currentVisualSegment}
selectedVisualSegmentId={selectedVisualSegmentId}
currentVisualSegmentIndex={currentVisualSegmentIndex}
visualOverlaySegments={visualOverlaySegments}
selectedVisualOverlayId={selectedVisualOverlayId}
setSelectedVisualOverlayId={setSelectedVisualOverlayId}
setVisualOverlaySegments={setVisualOverlaySegments}
builtInImageCaptionAvailable={autoEdit.support.availability === "available"}
generateImageCaption={autoEdit.generateImageCaption}
extractVideoSourceAudio={extractVideoSourceAudio}
setSelectedVisualSegmentId={setSelectedVisualSegmentId}
seekTo={seekTo}
suppressTimelineClipClickRef={suppressTimelineClipClickRef}
+228 -19
View File
@@ -1,6 +1,9 @@
import { useEffect } from "react";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import {
CaretDown,
ArrowDown,
ArrowUp,
CloudArrowUp,
FrameCorners,
Pause,
@@ -8,14 +11,16 @@ import {
Resize,
SkipBack,
SkipForward,
X,
} from "@phosphor-icons/react";
import { formatTime } from "../lib/timeline.js";
import { getVisualMaskInsets, getVisualMaskSvgDataUrl, resolveVisualTransform } from "../lib/visualEffects.js";
import { getVisualMaskInsets, getVisualMaskSvgDataUrl, resolveVisualTransform, snapVisualScaleToFrameEdges } from "../lib/visualEffects.js";
import { resolveVisualClipAnimation } from "../lib/visualClipAnimations.js";
import { getStickerBaseSize } from "../lib/stickerGeometry.js";
import { CaptionOverlay } from "./CaptionOverlay.jsx";
import { IconButton } from "./ui.jsx";
import { getVisualOverlayPixelBox, snapVisualOverlayTransform } from "../lib/visualOverlayTimeline.js";
export function PreviewStage({
t,
@@ -27,6 +32,7 @@ export function PreviewStage({
previewVisualRenderSrc,
previewVisionMaskUrl = "",
previewVisualType,
previewVisualMuted = true,
previewTransition = null,
previewRatio,
previewFrameStyle,
@@ -68,16 +74,30 @@ export function PreviewStage({
visualLocalTime = 0,
visualMaskEditable = false,
onUpdateVisualMask,
visualTransformEditable = false,
onSelectVisual,
onDeselectVisuals,
onUpdateVisualTransform,
getDraggedAsset,
applyAssetToTrack,
addVisualOverlay,
visualOverlays = [],
selectedVisualOverlayId = "",
onSelectVisualOverlay,
onUpdateVisualOverlay,
onReorderVisualOverlay,
}) {
const [overlaySnapGuides, setOverlaySnapGuides] = useState([]);
const lastReportedVideoTimeRef = useRef(-Infinity);
const [isFocusPreviewOpen, setIsFocusPreviewOpen] = useState(false);
const [focusPreviewFrameSize, setFocusPreviewFrameSize] = useState({ width: 0, height: 0 });
const visibleStickers = stickers;
const hasStickerOverlay = visibleStickers.some((sticker) => sticker?.src || sticker?.text);
const hasPreviewContent = Boolean(previewVisualSrc || hasStickerOverlay);
const renderedVisualSrc = previewVisualRenderSrc || previewVisualSrc;
const activeObjectFit = visualObjectFit || fitMode;
const activeObjectPosition = visualObjectPosition || "50% 50%";
const visualTransform = resolveVisualTransform(visualEffects?.keyframes, visualLocalTime);
const visualTransform = resolveVisualTransform(visualEffects?.keyframes, visualLocalTime, visualEffects?.baseTransform);
const visualAnimation = resolveVisualClipAnimation(visualEffects?.animation, visualLocalTime, visualEffects?.duration);
const visualMask = visualEffects?.mask ?? {};
const enhancement = visualEffects?.enhancement ?? null;
@@ -87,8 +107,12 @@ export function PreviewStage({
);
const maskCenterX = Number.isFinite(visualMask.centerX) ? visualMask.centerX : 50;
const maskCenterY = Number.isFinite(visualMask.centerY) ? visualMask.centerY : 50;
const frameWidth = Math.max(1, previewFrameSize.width || 1);
const frameHeight = Math.max(1, previewFrameSize.height || 1);
const activePreviewFrameSize = isFocusPreviewOpen && focusPreviewFrameSize.width > 0 ? focusPreviewFrameSize : previewFrameSize;
const activePreviewFrameStyle = isFocusPreviewOpen && focusPreviewFrameSize.width > 0
? { ...previewFrameStyle, width: `${focusPreviewFrameSize.width}px`, height: `${focusPreviewFrameSize.height}px` }
: previewFrameStyle;
const frameWidth = Math.max(1, activePreviewFrameSize.width || 1);
const frameHeight = Math.max(1, activePreviewFrameSize.height || 1);
const frameMinDimension = Math.min(frameWidth, frameHeight);
const stickerBaseSize = getStickerBaseSize({ width: frameWidth, height: frameHeight });
const circleSize = Number.isFinite(visualMask.size) ? visualMask.size : 72;
@@ -181,6 +205,79 @@ export function PreviewStage({
const end = () => { window.removeEventListener("pointermove", move); window.removeEventListener("pointerup", end); };
window.addEventListener("pointermove", move); window.addEventListener("pointerup", end, { once: true });
};
const startVisualTransform = (event, mode) => {
if (!visualTransformEditable || !onUpdateVisualTransform) return;
const frame = previewCanvasRef.current;
if (!frame) return;
event.preventDefault(); event.stopPropagation();
onSelectVisual?.();
const rect = frame.getBoundingClientRect();
const startX = event.clientX; const startY = event.clientY;
const initial = { ...visualTransform };
const centerX = rect.left + rect.width * (0.5 + initial.x / 100);
const centerY = rect.top + rect.height * (0.5 + initial.y / 100);
const startDistance = Math.max(1, Math.hypot(startX - centerX, startY - centerY));
const startAngle = Math.atan2(startY - centerY, startX - centerX) * 180 / Math.PI;
const round = (value) => Math.round(value * 100) / 100;
const move = (moveEvent) => {
if (mode === "move") onUpdateVisualTransform({
...initial,
x: round(initial.x + (moveEvent.clientX - startX) / Math.max(1, rect.width) * 100),
y: round(initial.y + (moveEvent.clientY - startY) / Math.max(1, rect.height) * 100),
});
if (mode === "scale") {
const candidate = {
...initial,
scale: round(Math.max(0.1, Math.min(4, initial.scale * Math.hypot(moveEvent.clientX - centerX, moveEvent.clientY - centerY) / startDistance))),
};
const snapped = snapVisualScaleToFrameEdges(candidate, { width: rect.width, height: rect.height });
setOverlaySnapGuides(snapped.guides);
onUpdateVisualTransform({ ...snapped.transform, scale: round(snapped.transform.scale) });
}
if (mode === "rotate") {
const angle = Math.atan2(moveEvent.clientY - centerY, moveEvent.clientX - centerX) * 180 / Math.PI;
onUpdateVisualTransform({ ...initial, rotation: round(initial.rotation + angle - startAngle) });
}
};
const end = () => { setOverlaySnapGuides([]); window.removeEventListener("pointermove", move); window.removeEventListener("pointerup", end); };
window.addEventListener("pointermove", move); window.addEventListener("pointerup", end, { once: true });
};
const startOverlayTransform = (event, mode, overlay) => {
if (!overlay || !onUpdateVisualOverlay) return;
const frame = previewCanvasRef.current;
if (!frame) return;
event.preventDefault(); event.stopPropagation();
onSelectVisualOverlay?.(overlay.id);
const rect = frame.getBoundingClientRect();
const localTime = Math.max(0, currentTime - (overlay.start || 0));
const initial = resolveVisualTransform(overlay.keyframes, localTime);
const startX = event.clientX; const startY = event.clientY;
const centerX = rect.left + rect.width * (0.5 + initial.x / 100);
const centerY = rect.top + rect.height * (0.5 + initial.y / 100);
const startDistance = Math.max(1, Math.hypot(startX - centerX, startY - centerY));
const startAngle = Math.atan2(startY - centerY, startX - centerX) * 180 / Math.PI;
const round = (value) => Math.round(value * 100) / 100;
const move = (moveEvent) => {
if (mode === "move") {
const candidate = { ...initial, x: round(initial.x + (moveEvent.clientX - startX) / Math.max(1, rect.width) * 100), y: round(initial.y + (moveEvent.clientY - startY) / Math.max(1, rect.height) * 100) };
const snapped = snapVisualOverlayTransform(candidate);
setOverlaySnapGuides(snapped.guides);
onUpdateVisualOverlay(snapped.transform);
}
if (mode.startsWith("scale")) {
const horizontal = Math.abs(moveEvent.clientX - centerX) / Math.max(1, Math.abs(startX - centerX));
const vertical = Math.abs(moveEvent.clientY - centerY) / Math.max(1, Math.abs(startY - centerY));
const ratio = mode === "scale-e" || mode === "scale-w" ? horizontal : mode === "scale-n" || mode === "scale-s" ? vertical : Math.hypot(moveEvent.clientX - centerX, moveEvent.clientY - centerY) / startDistance;
onUpdateVisualOverlay({ ...initial, scale: round(Math.max(0.08, Math.min(4, initial.scale * ratio))) });
}
if (mode === "rotate") {
const angle = Math.atan2(moveEvent.clientY - centerY, moveEvent.clientX - centerX) * 180 / Math.PI;
onUpdateVisualOverlay({ ...initial, rotation: round(initial.rotation + angle - startAngle) });
}
};
const end = () => { setOverlaySnapGuides([]); window.removeEventListener("pointermove", move); window.removeEventListener("pointerup", end); };
window.addEventListener("pointermove", move); window.addEventListener("pointerup", end, { once: true });
};
useEffect(() => {
const video = previewVideoRef.current;
@@ -194,9 +291,11 @@ export function PreviewStage({
let callbackId = 0;
const handleVideoFrame = (_now, metadata) => {
onPreviewVideoTimeUpdate?.(
Number.isFinite(metadata?.mediaTime) ? metadata.mediaTime : video.currentTime,
);
const mediaTime = Number.isFinite(metadata?.mediaTime) ? metadata.mediaTime : video.currentTime;
if (Math.abs(mediaTime - lastReportedVideoTimeRef.current) >= 1 / 12) {
lastReportedVideoTimeRef.current = mediaTime;
onPreviewVideoTimeUpdate?.(mediaTime);
}
callbackId = video.requestVideoFrameCallback(handleVideoFrame);
};
callbackId = video.requestVideoFrameCallback(handleVideoFrame);
@@ -208,15 +307,75 @@ export function PreviewStage({
previewVisualType,
]);
return (
<section className="preview-stage">
useEffect(() => {
if (!isFocusPreviewOpen) return undefined;
const shell = previewShellRef.current;
if (!shell) return undefined;
const updateFocusFrameSize = () => {
const style = getComputedStyle(shell);
const availableWidth = Math.max(1, shell.clientWidth - parseFloat(style.paddingLeft || 0) - parseFloat(style.paddingRight || 0));
const availableHeight = Math.max(1, shell.clientHeight - parseFloat(style.paddingTop || 0) - parseFloat(style.paddingBottom || 0));
const [ratioWidth, ratioHeight] = String(previewRatio).split("/").map((value) => Number(value.trim()));
const ratio = Math.max(0.01, ratioWidth > 0 && ratioHeight > 0 ? ratioWidth / ratioHeight : 16 / 9);
const width = Math.max(1, Math.floor(Math.min(availableWidth, availableHeight * ratio)));
const height = Math.max(1, Math.floor(width / ratio));
setFocusPreviewFrameSize((current) => current.width === width && current.height === height ? current : { width, height });
};
updateFocusFrameSize();
const observer = window.ResizeObserver ? new ResizeObserver(updateFocusFrameSize) : null;
observer?.observe(shell);
window.addEventListener("resize", updateFocusFrameSize);
return () => {
observer?.disconnect();
window.removeEventListener("resize", updateFocusFrameSize);
};
}, [isFocusPreviewOpen, previewRatio, previewShellRef]);
useEffect(() => {
if (!isFocusPreviewOpen) return undefined;
const handleKeyDown = (event) => {
if (event.key === "Escape") setIsFocusPreviewOpen(false);
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [isFocusPreviewOpen]);
useEffect(() => {
if (!isFocusPreviewOpen) return undefined;
const shell = previewShellRef.current;
if (!shell) return undefined;
const [ratioWidth, ratioHeight] = String(previewRatio).split("/").map(Number);
const ratio = ratioWidth > 0 && ratioHeight > 0 ? ratioWidth / ratioHeight : 16 / 9;
const update = () => {
const style = getComputedStyle(shell);
const availableWidth = Math.max(1, shell.clientWidth - parseFloat(style.paddingLeft || 0) - parseFloat(style.paddingRight || 0));
const availableHeight = Math.max(1, shell.clientHeight - parseFloat(style.paddingTop || 0) - parseFloat(style.paddingBottom || 0));
const width = Math.max(1, Math.floor(Math.min(availableWidth, availableHeight * ratio)));
const height = Math.max(1, Math.floor(width / ratio));
setFocusPreviewFrameSize((old) => old.width === width && old.height === height ? old : { width, height });
};
update();
const observer = new ResizeObserver(update);
observer.observe(shell);
return () => observer.disconnect();
}, [isFocusPreviewOpen, previewRatio, previewShellRef]);
const previewStage = (
<section className={`preview-stage ${isFocusPreviewOpen ? "is-focus-preview" : ""}`} role={isFocusPreviewOpen ? "dialog" : undefined} aria-modal={isFocusPreviewOpen ? "true" : undefined} aria-label={isFocusPreviewOpen ? t("focusPreviewTitle", "大画布编辑") : undefined}>
{isFocusPreviewOpen ? <header className="focus-preview-header">
<div><strong>{t("focusPreviewTitle", "大画布编辑")}</strong><span>{t("focusPreviewHint", "点击画面元素进行移动、缩放和旋转")}</span></div>
<IconButton label={t("closeFocusPreview", "关闭大画布预览")} onClick={() => setIsFocusPreviewOpen(false)}><X size={20} /></IconButton>
</header> : null}
<div
ref={previewShellRef}
className={`preview-canvas fit-${fitMode} ${hasPreviewContent ? "" : "is-empty"} ${
previewVisualSrc && !trackVisibility.image ? "is-image-hidden" : ""
}`}
style={{ "--preview-ratio": previewRatio }}
data-asset-drop-track="image"
data-asset-drop-track={previewVisualSrc ? "overlay" : "image"}
onPointerDown={(event) => {
if (event.target === event.currentTarget) onDeselectVisuals?.();
}}
onDragOver={(event) => {
const asset = getDraggedAsset?.(event);
if (asset?.type === "image" || asset?.type === "video") event.preventDefault();
@@ -225,11 +384,12 @@ export function PreviewStage({
const asset = getDraggedAsset?.(event);
if (asset?.type !== "image" && asset?.type !== "video") return;
event.preventDefault(); event.stopPropagation();
void applyAssetToTrack?.(asset, "image");
if (previewVisualSrc) addVisualOverlay?.(asset);
else void applyAssetToTrack?.(asset, "image");
}}
>
{!hasPreviewContent ? (
<button className="preview-empty" type="button" style={previewFrameStyle} onClick={() => fileInputRef.current?.click()}>
<button className="preview-empty" type="button" style={activePreviewFrameStyle} onClick={() => fileInputRef.current?.click()}>
<CloudArrowUp size={38} />
<strong>{t("previewEmptyTitle")}</strong>
<span>{t("previewEmptySubtitle")}</span>
@@ -241,10 +401,15 @@ export function PreviewStage({
backgroundRemoved ? "has-background-removed" : ""
} ${smartCropActive ? "has-smart-crop" : ""}`}
data-hidden-label={t("imageHidden")}
style={previewFrameStyle}
style={activePreviewFrameStyle}
onPointerDown={(event) => {
if (event.target === event.currentTarget) onDeselectVisuals?.();
}}
>
<div className="caption-canvas-guide is-vertical" aria-hidden="true" />
<div className="caption-canvas-guide is-horizontal" aria-hidden="true" />
{renderedVisualSrc && trackVisibility.image ? (
<div className="visual-media-layer" style={visualMaskStyle}>
<div className={`visual-media-layer ${visualTransformEditable ? "is-transform-editable" : ""}`} style={visualMaskStyle} onPointerDown={(event) => { event.stopPropagation(); onSelectVisual?.(); if (visualTransformEditable) startVisualTransform(event, "move"); }}>
{previewVisualType === "image" ? <img
src={renderedVisualSrc}
alt={t("currentMediaAlt")}
@@ -255,11 +420,14 @@ export function PreviewStage({
ref={previewVideoRef}
className="preview-video"
src={previewVisualSrc}
muted
muted={previewVisualMuted}
playsInline
preload="metadata"
onTimeUpdate={(event) => onPreviewVideoTimeUpdate?.(event.currentTarget.currentTime)}
onSeeked={(event) => onPreviewVideoTimeUpdate?.(event.currentTarget.currentTime)}
onSeeked={(event) => {
lastReportedVideoTimeRef.current = event.currentTarget.currentTime;
onPreviewVideoTimeUpdate?.(event.currentTarget.currentTime);
}}
style={{
...visualTransformStyle, filter: selectedFilter.css, objectFit: activeObjectFit, objectPosition: activeObjectPosition,
WebkitMaskImage: previewVisionMaskUrl ? `url("${previewVisionMaskUrl}")` : undefined,
@@ -280,6 +448,13 @@ export function PreviewStage({
/> : null}
</div>
) : null}
{renderedVisualSrc && trackVisibility.image && visualTransformEditable && (!visualMask.type || visualMask.type === "none") ? (
<div className="visual-transform-box" style={visualTransformStyle} onPointerDown={(event) => startVisualTransform(event, "move")}>
<span className="visual-transform-label">{t("visualBasic", "画面")}</span>
<button className="visual-transform-rotate" type="button" aria-label={t("visualRotation", "旋转")} onPointerDown={(event) => startVisualTransform(event, "rotate")} />
{['nw', 'ne', 'sw', 'se'].map((corner) => <button key={corner} className={`visual-transform-handle is-${corner}`} type="button" aria-label={t("visualScale", "缩放")} onPointerDown={(event) => startVisualTransform(event, "scale")} />)}
</div>
) : null}
{previewTransition?.next?.src && trackVisibility.image ? (
<div className={`preview-transition-layer type-${previewTransition.id}`} style={{ "--transition-progress": previewTransition.progress }}>
{previewTransition.next.type === "video" ? (
@@ -290,6 +465,33 @@ export function PreviewStage({
{previewTransition.id === "flash" ? <i /> : null}
</div>
) : null}
{visualOverlays.map((overlay) => {
const localTime = Math.max(0, currentTime - (overlay.start || 0));
const transform = resolveVisualTransform(overlay.keyframes, localTime);
const containBox = getVisualOverlayPixelBox(overlay, activePreviewFrameSize);
const style = {
left: `${50 + transform.x}%`,
top: `${50 + transform.y}%`,
width: `${containBox.width * transform.scale}px`,
height: `${containBox.height * transform.scale}px`,
transform: `translate(-50%, -50%) rotate(${transform.rotation}deg)`,
opacity: transform.opacity,
};
const selected = overlay.id === selectedVisualOverlayId;
return <div className={`visual-overlay-layer ${selected ? "is-selected" : ""}`} key={overlay.id} style={{ ...style, zIndex: 3 + (overlay.layer || 1) }} onPointerDown={(event) => startOverlayTransform(event, "move", overlay)}>
{overlay.type === "video" ? <video src={overlay.src} muted={overlay.muted === true} playsInline autoPlay={isPlaying} preload="metadata" /> : <img src={overlay.src} alt="" draggable={false} />}
{selected && !isPlaying ? <>
<span className="visual-transform-label">{overlay.name || t("pictureInPicture", "画中画")}</span>
<div className="visual-overlay-order-actions">
<button type="button" aria-label={t("moveLayerUp", "上移一层")} onPointerDown={(event) => event.stopPropagation()} onClick={(event) => { event.stopPropagation(); onReorderVisualOverlay?.(overlay.id, 1); }}><ArrowUp size={12} /></button>
<button type="button" aria-label={t("moveLayerDown", "下移一层")} onPointerDown={(event) => event.stopPropagation()} onClick={(event) => { event.stopPropagation(); onReorderVisualOverlay?.(overlay.id, -1); }}><ArrowDown size={12} /></button>
</div>
<button className="visual-transform-rotate" type="button" aria-label={t("visualRotation", "旋转")} onPointerDown={(event) => startOverlayTransform(event, "rotate", overlay)} />
{['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'].map((handle) => <button key={handle} className={`visual-transform-handle is-${handle}`} type="button" aria-label={t("visualScale", "缩放")} onPointerDown={(event) => startOverlayTransform(event, `scale-${handle}`, overlay)} />)}
</> : null}
</div>;
})}
{overlaySnapGuides.map((guide) => <div className={`visual-snap-guide is-${guide}`} key={guide} />)}
{showVisionOverlays
? visionOverlayBoxes.map((detection, index) => (
<div
@@ -335,7 +537,7 @@ export function PreviewStage({
...basePlacement,
y: basePlacement.y + (caption.placement ? 0 : (index - (visibleCaptions.length - 1) / 2) * 12),
}}
frameSize={previewFrameSize}
frameSize={activePreviewFrameSize}
onPointerDown={(event) => startCaptionDrag(event, caption.id)}
onDoubleClick={() => setActiveTool("caption")}
/>
@@ -408,11 +610,18 @@ export function PreviewStage({
>
{fitMode === "contain" ? t("fit") : t("cover")} <CaretDown size={14} />
</button>
<IconButton label={t("fullscreenPreview")} onClick={() => document.documentElement.requestFullscreen?.()}>
<IconButton label={isFocusPreviewOpen ? t("closeFocusPreview", "关闭大画布预览") : t("fullscreenPreview")} onClick={() => setIsFocusPreviewOpen((open) => !open)}>
<FrameCorners size={19} />
</IconButton>
</div>
</div>
</section>
);
if (isFocusPreviewOpen && typeof document !== "undefined") {
return createPortal(<>
<button className="focus-preview-backdrop" type="button" aria-label={t("closeFocusPreview", "关闭大画布预览")} onClick={() => setIsFocusPreviewOpen(false)} />
{previewStage}
</>, document.body);
}
return previewStage;
}
+281 -33
View File
@@ -19,17 +19,21 @@ import {
MonitorPlay,
Pause,
Play,
PictureInPicture,
PlusCircle,
Scissors,
Sparkle,
SpeakerHigh,
SpeakerSlash,
SlidersHorizontal,
Trash,
Waveform,
} from "@phosphor-icons/react";
import { IMAGE_SEGMENT_SECONDS, MAX_IMAGE_THUMBNAILS, TRANSITIONS } from "../config/editor.js";
import { formatClock, formatTime, getSegmentStartTime, packCaptionSegmentsIntoLanes, packTimedSegmentsIntoLanes } from "../lib/timeline.js";
import { formatClock, formatTime, getSegmentStartTime, getVisualSegmentStartTime, packCaptionSegmentsIntoLanes, packTimedSegmentsIntoLanes } from "../lib/timeline.js";
import { sliceSourceAudioPeaks } from "../lib/sourceAudioSync.js";
import { createMainVisualFromOverlay } from "../lib/visualOverlayTimeline.js";
import {
clampTimelineZoom,
getTimelineRulerTicks,
@@ -48,6 +52,7 @@ const IMAGE_THUMBNAIL_TARGET_WIDTH = 84;
const IMAGE_THUMBNAIL_MAX_COUNT = 240;
const TIMELINE_WHEEL_ZOOM_CONTENT_SELECTOR = [
".image-clip",
".visual-overlay-clip",
".caption-segment",
".sticker-segment",
".audio-clip",
@@ -138,6 +143,7 @@ export function Timeline({
assetDropPosition,
assetDropPulseTrack,
assetDragPreview,
draggedAssetType = "",
handleTrackAssetDragOver,
handleTrackAssetDragLeave,
handleTrackAssetDrop,
@@ -156,8 +162,13 @@ export function Timeline({
currentVisualSegment,
selectedVisualSegmentId,
currentVisualSegmentIndex,
visualOverlaySegments = [],
selectedVisualOverlayId = "",
setSelectedVisualOverlayId,
setVisualOverlaySegments,
builtInImageCaptionAvailable = false,
generateImageCaption,
extractVideoSourceAudio,
setSelectedVisualSegmentId,
seekTo,
suppressTimelineClipClickRef,
@@ -199,8 +210,11 @@ export function Timeline({
}) {
const [transitionEditor, setTransitionEditor] = useState(null);
const [musicClipSelected, setMusicClipSelected] = useState(false);
const [overlayPromotionTarget, setOverlayPromotionTarget] = useState(null);
const [sourceAudioExtractionPendingId, setSourceAudioExtractionPendingId] = useState("");
const clearClipSelections = (except = "") => {
if (except !== "overlay") setSelectedVisualOverlayId?.("");
if (except !== "visual") setSelectedVisualSegmentId("");
if (except !== "sticker") setSelectedStickerSegmentId("");
if (except !== "caption") setSelectedSegmentId("");
@@ -222,29 +236,44 @@ export function Timeline({
activeTimelineClipDrag?.track === "caption"
? displayedCaptionSegments.find((segment) => segment.id === activeTimelineClipDrag.segmentId)
: null;
const audioLanes = useMemo(() => packTimedSegmentsIntoLanes(audioSegments), [audioSegments]);
const packedAudioLanes = useMemo(() => packTimedSegmentsIntoLanes(audioSegments), [audioSegments]);
const showVoiceTrack = audioSegments.length > 0 || draggedAssetType === "audio";
const audioLanes = showVoiceTrack ? (audioSegments.length ? packedAudioLanes : [[]]) : [];
const stickerLanes = useMemo(() => packTimedSegmentsIntoLanes(stickerSegments), [stickerSegments]);
const showEmptyOverlayDropLane = !visualOverlaySegments.length && (
draggedAssetType === "image" ||
draggedAssetType === "video" ||
(activeTimelineClipDrag?.track === "image" && activeTimelineClipDrag.mode === "overlay")
);
const overlayLanes = useMemo(
() => visualOverlaySegments.length ? packTimedSegmentsIntoLanes(visualOverlaySegments) : showEmptyOverlayDropLane ? [[]] : [],
[showEmptyOverlayDropLane, visualOverlaySegments],
);
const showSourceTrack = Boolean(sourceAudioBlob || sourceAudioExtractionPendingId);
const showMusicTrack = Boolean(musicBlob) || draggedAssetType === "audio";
const captionLanes = useMemo(
() => packCaptionSegmentsIntoLanes(displayedCaptionSegments, displayedCaptionTimeline),
[displayedCaptionSegments, displayedCaptionTimeline],
);
const contentRows = [
TIMELINE_TRACK_ROW_HEIGHT,
...overlayLanes.map(() => TIMELINE_TRACK_ROW_HEIGHT),
...(showStickerTrack ? stickerLanes.map(() => TIMELINE_TRACK_ROW_HEIGHT) : []),
...captionLanes.map(() => TIMELINE_TRACK_ROW_HEIGHT),
TIMELINE_TRACK_ROW_HEIGHT,
...(showSourceTrack ? [TIMELINE_TRACK_ROW_HEIGHT] : []),
...audioLanes.map(() => TIMELINE_TRACK_ROW_HEIGHT),
TIMELINE_TRACK_ROW_HEIGHT,
...(showMusicTrack ? [TIMELINE_TRACK_ROW_HEIGHT] : []),
];
const timelineTrackRows = ["28px", ...contentRows].join(" ");
const timelineTrackRows = contentRows.join(" ");
const timelineLabelRows = contentRows.join(" ");
const timelineTrackLabels = [
["image", t("imageTrack")],
...overlayLanes.map((_, index) => ["overlay", `${t("overlayTrack", "Overlay")} ${index + 1}`, `overlay-${index}`]),
...(showStickerTrack ? stickerLanes.map((_, index) => ["sticker", `${t("stickerTrack")} ${index + 1}`, `sticker-${index}`]) : []),
...captionLanes.map((_, index) => ["caption", `${t("caption")} ${index + 1}`, `caption-${index}`, `caption-${index}`]),
["source", t("sourceTrack")],
...(showSourceTrack ? [["source", t("sourceTrack")]] : []),
...audioLanes.map((_, index) => ["audio", `${t("voiceTrack")} ${index + 1}`, `audio-${index}`]),
["music", t("musicTrack")],
...(showMusicTrack ? [["music", t("musicTrack")]] : []),
];
// Visibility is track-scoped even when overlapping clips are packed into
// multiple visual rows. Preview, playback and export all read the track key.
@@ -259,16 +288,20 @@ export function Timeline({
const contextImageSegment = contextMenu?.track === "image" && contextMenu.segmentId
? displayedVisualSegments.find((segment) => segment.id === contextMenu.segmentId)
: null;
const trackTool = (track) => ({ image: "media", sticker: "stickers", caption: "caption", source: "audio", audio: "audio", music: "audio" })[track] || "media";
const contextOverlaySegment = contextMenu?.track === "overlay" && contextMenu.segmentId
? visualOverlaySegments.find((segment) => segment.id === contextMenu.segmentId)
: null;
const trackTool = (track) => ({ image: "media", overlay: "media", sticker: "stickers", caption: "caption", source: "audio", audio: "audio", music: "audio" })[track] || "media";
const openTrackPanel = (track) => {
setSelectedTrack(track);
setActiveTool(trackTool(track));
};
const selectContextTarget = (track, segmentId = "") => {
openTrackPanel(track);
const selectionType = { image: "visual", sticker: "sticker", caption: "caption", audio: "voice", source: "source", music: "music" }[track];
const selectionType = { image: "visual", overlay: "overlay", sticker: "sticker", caption: "caption", audio: "voice", source: "source", music: "music" }[track];
clearClipSelections(selectionType);
if (track === "image" && segmentId) setSelectedVisualSegmentId(segmentId);
if (track === "overlay" && segmentId) setSelectedVisualOverlayId?.(segmentId);
if (track === "sticker" && segmentId) setSelectedStickerSegmentId(segmentId);
if (track === "caption" && segmentId) setSelectedSegmentId(segmentId);
if (track === "audio" && segmentId) setSelectedAudioSegmentId(segmentId);
@@ -302,6 +335,18 @@ export function Timeline({
setImageCaptionPendingId("");
}
};
const runSourceAudioExtraction = async (segment) => {
if (!segment || sourceAudioExtractionPendingId) return;
const index = displayedVisualSegments.findIndex((item) => item.id === segment.id);
const start = getVisualSegmentStartTime(displayedVisualSegments, index);
setSourceAudioExtractionPendingId(segment.id);
setContextMenu(null);
try {
await extractVideoSourceAudio?.(segment, start, { append: Boolean(sourceAudioBlob) });
} finally {
setSourceAudioExtractionPendingId("");
}
};
useEffect(() => {
if (!contextMenu) return undefined;
const close = () => setContextMenu(null);
@@ -326,6 +371,7 @@ export function Timeline({
const rulerViewportFrameRef = useRef(0);
const wheelZoomActiveRef = useRef(false);
const rulerViewportSyncRef = useRef(null);
const rulerCanvasRef = useRef(null);
const zoomReadoutRef = useRef(null);
const pendingWheelDeltaRef = useRef(0);
const pendingWheelAnchorRef = useRef(null);
@@ -337,8 +383,14 @@ export function Timeline({
return undefined;
}
const syncRulerPosition = () => {
if (rulerCanvasRef.current) {
rulerCanvasRef.current.style.transform = `translateX(${-scrollElement.scrollLeft}px)`;
}
};
const applyRulerViewportUpdate = () => {
rulerViewportFrameRef.current = 0;
syncRulerPosition();
const nextViewport = {
scrollLeft: scrollElement.scrollLeft,
viewportWidth: scrollElement.clientWidth,
@@ -353,6 +405,7 @@ export function Timeline({
);
};
const scheduleRulerViewportUpdate = () => {
syncRulerPosition();
if (wheelZoomActiveRef.current) {
return;
}
@@ -567,7 +620,7 @@ export function Timeline({
const renderAssetDropSlot = (track) =>
assetDropTargetTrack === track ? (
<div
className={`asset-drop-slot type-${assetDragPreview?.type || "asset"} ${
className={`asset-drop-slot type-${assetDragPreview?.type || "asset"} mode-${track} ${
assetDragPreview?.src ? "has-thumb" : ""
}`}
style={{ "--drop-x": `${assetDropPosition?.track === track ? assetDropPosition.percent : 50}%` }}
@@ -583,9 +636,11 @@ export function Timeline({
)}
</div>
) : null}
<span>{t("dropSlot", "释放到这里")}</span>
<span>{track === "overlay" ? <><PictureInPicture size={12} />{t("dropAsOverlay", "作为画中画")}</> : track === "image" ? <><PlusCircle size={12} />{t("appendAfter", "添加到后面")}</> : t("dropSlot", "释放到这里")}</span>
<strong>
{assetDragPreview?.type === "audio"
{track === "overlay" || track === "image"
? assetDragPreview?.name || (assetDragPreview?.type === "video" ? t("assetVideo") : t("assetImage"))
: assetDragPreview?.type === "audio"
? t("assetAudio")
: assetDragPreview?.type === "video"
? t("assetVideo")
@@ -659,6 +714,120 @@ export function Timeline({
{renderAssetDropSlot("sticker")}
</div>
) : null;
const renderOverlayTrack = (lane, laneIndex) => {
const laneEnd = lane.reduce((end, segment) => Math.max(end, segment.start + segment.duration), 0);
return (
<div
className={`visual-overlay-track ${selectedTrack === "overlay" ? "is-selected" : ""} ${!isRowVisible("overlay") ? "is-track-disabled" : ""} ${assetDropTargetTrack === "overlay" ? "is-drop-target" : ""}`}
key={`overlay-lane-${laneIndex}`}
onClick={() => setSelectedTrack("overlay")}
data-asset-drop-track="overlay"
data-drop-start-time={laneEnd}
data-drop-layer={laneIndex + 1}
onDragLeave={(event) => handleTrackAssetDragLeave(event, "overlay")}
onDragOver={(event) => handleTrackAssetDragOver(event, "overlay")}
onDrop={(event) => handleTrackAssetDrop(event, "overlay")}
>
{lane.map((segment) => {
const left = timelineDuration > 0 ? Math.max(0, Math.min(100, segment.start / timelineDuration * 100)) : 0;
const width = timelineDuration > 0 ? Math.max(0.01, Math.min(100 - left, segment.duration / timelineDuration * 100)) : 0;
const active = currentTime >= segment.start && currentTime < segment.start + segment.duration;
const overlayFrames = segment.type === "video" && segment.trackFrames?.length
? getSampledVideoFrames(segment.trackFrames, getTimelineThumbnailCount({ duration: segment.duration, timelineDuration, contentWidth: rulerViewport.contentWidth, timelineZoom: localTimelineZoom, availableFrames: MAX_IMAGE_THUMBNAILS }))
: [];
const overlayImageCount = segment.type !== "video"
? getImageTimelineThumbnailCount({ duration: segment.duration, timelineDuration, contentWidth: rulerViewport.contentWidth })
: 1;
const startOverlayEdit = (event, mode) => {
if (trackLocks.overlay || !setVisualOverlaySegments) return;
event.preventDefault(); event.stopPropagation();
clearClipSelections("overlay"); setSelectedVisualOverlayId?.(segment.id); setSelectedTrack("overlay");
const track = event.currentTarget.closest(".visual-overlay-track");
if (!track) return;
const rect = track.getBoundingClientRect();
const startX = event.clientX; const initialStart = segment.start; const initialDuration = segment.duration;
let dragging = false; let promoteToMain = false; let mainInsertIndex = displayedVisualSegments.length;
const move = (moveEvent) => {
if (!dragging && Math.abs(moveEvent.clientX - startX) < 4) return;
if (!dragging) { dragging = true; if (isPlaying) handlePlayToggle(); }
const mainTrack = mode === "move" ? document.elementFromPoint(moveEvent.clientX, moveEvent.clientY)?.closest?.('[data-asset-drop-track="image"]') : null;
promoteToMain = Boolean(mainTrack);
if (promoteToMain) {
const clips = Array.from(mainTrack.querySelectorAll('[data-timeline-segment-track="image"]'));
mainInsertIndex = clips.findIndex((clip) => {
const clipRect = clip.getBoundingClientRect();
return moveEvent.clientX < clipRect.left + clipRect.width / 2;
});
if (mainInsertIndex < 0) mainInsertIndex = clips.length;
setOverlayPromotionTarget({ segmentId: segment.id, insertIndex: mainInsertIndex });
} else {
setOverlayPromotionTarget(null);
}
if (promoteToMain) return;
const delta = (moveEvent.clientX - startX) / Math.max(1, rect.width) * timelineDuration;
setVisualOverlaySegments((items) => items.map((item) => {
if (item.id !== segment.id) return item;
if (mode === "move") return { ...item, start: Math.max(0, Math.min(timelineDuration - initialDuration, initialStart + delta)) };
if (mode === "resize-start") {
const start = Math.max(0, Math.min(initialStart + initialDuration - 0.1, initialStart + delta));
return { ...item, start, duration: initialDuration + initialStart - start };
}
return { ...item, duration: Math.max(0.1, Math.min(timelineDuration - initialStart, initialDuration + delta)) };
}));
};
const end = () => {
window.removeEventListener("pointermove", move); window.removeEventListener("pointerup", end);
setOverlayPromotionTarget(null);
if (!dragging || !promoteToMain) return;
const promoted = createMainVisualFromOverlay(segment);
if (!promoted) return;
setVisualOverlaySegments((items) => items.filter((item) => item.id !== segment.id));
setVisualSegments((items) => {
const next = [...items];
next.splice(Math.max(0, Math.min(next.length, mainInsertIndex)), 0, promoted);
return next;
});
clearClipSelections("visual");
setSelectedVisualSegmentId(promoted.id);
setSelectedTrack("image");
};
window.addEventListener("pointermove", move); window.addEventListener("pointerup", end, { once: true });
};
return <div className={`visual-overlay-clip ${segment.type === "video" ? "is-video" : "is-image"} ${active ? "is-current" : ""} ${segment.id === selectedVisualOverlayId ? "is-selected-segment" : ""}`} role="button" tabIndex={0} key={segment.id} style={{ "--overlay-left": `${left}%`, "--overlay-width": `${width}%` }} onPointerDown={(event) => startOverlayEdit(event, "move")} onContextMenu={(event) => showTrackContextMenu(event, "overlay", segment.id)} onClick={(event) => {
event.stopPropagation();
clearClipSelections("overlay");
setSelectedVisualOverlayId?.(segment.id);
setSelectedTrack("overlay");
}}>
<div className="visual-overlay-thumbnails">
{segment.type === "video"
? overlayFrames.length
? overlayFrames.map((frame, frameIndex) => <img src={frame} alt="" draggable={false} key={`${segment.id}-overlay-frame-${frameIndex}`} />)
: <video src={segment.src} muted playsInline preload="metadata" />
: Array.from({ length: overlayImageCount }, (_, thumbnailIndex) => <img src={segment.src} alt="" draggable={false} key={`${segment.id}-overlay-image-${thumbnailIndex}`} />)}
</div>
{segment.type === "video" ? <button className="clip-mute-toggle" type="button" aria-label={t(segment.muted ? "unmuteClip" : "muteClip", segment.muted ? "取消静音" : "静音")} title={t(segment.muted ? "unmuteClip" : "muteClip", segment.muted ? "取消静音" : "静音")} onPointerDown={(event) => event.stopPropagation()} onClick={(event) => { event.stopPropagation(); setVisualOverlaySegments((items) => items.map((item) => item.id === segment.id ? { ...item, muted: !item.muted } : item)); }}>{segment.muted ? <SpeakerSlash size={13} /> : <SpeakerHigh size={13} />}</button> : null}
<span>{segment.name || t("overlayTrack", "Overlay")}</span>
<i className="visual-overlay-resize is-start" onPointerDown={(event) => startOverlayEdit(event, "resize-start")} />
<i className="visual-overlay-resize is-end" onPointerDown={(event) => startOverlayEdit(event, "resize-end")} />
</div>;
})}
{laneIndex === 0 && activeTimelineClipDrag?.track === "image" && activeTimelineClipDrag.mode === "overlay" && draggingVisualSegment ? (
<div
className="visual-overlay-drop-preview"
style={{
"--overlay-left": `${timelineDuration > 0 ? Math.max(0, Math.min(100, (activeTimelineClipDrag.overlayStart / timelineDuration) * 100)) : 0}%`,
"--overlay-width": `${timelineDuration > 0 ? Math.max(0.01, Math.min(100, (draggingVisualSegment.duration / timelineDuration) * 100)) : 0}%`,
}}
>
<span>{t("dropAsOverlay", "作为画中画")}</span>
</div>
) : null}
{!lane.length ? <div className="track-drop-hint">{t("dropAsOverlay", "作为画中画")}</div> : null}
{renderAssetDropSlot("overlay")}
</div>
);
};
return (
<section className="timeline">
@@ -737,6 +906,31 @@ export function Timeline({
</div>
<div className="timeline-board">
<div className="track-labels-ruler-spacer" aria-hidden="true" />
<div className="timeline-ruler-viewport">
<div
ref={rulerCanvasRef}
className="timeline-ruler-canvas"
style={{ width: localTrackWidth, transform: `translateX(${-rulerViewport.scrollLeft}px)` }}
>
<div className="ruler" onPointerDown={startTimelineSeek}>
{rulerTicks.map((tick) => (
<span
className={`ruler-tick ${tick.isMajor ? "is-major" : "is-minor"}`}
key={tick.id}
style={{ left: `${tick.left}%` }}
>
{tick.label}
</span>
))}
</div>
<div
className="playhead-ruler"
style={{ left: `${playheadPercent}%` }}
onPointerDown={startTimelineSeek}
/>
</div>
</div>
<div className="track-labels" style={{ gridTemplateRows: timelineLabelRows }}>
{timelineTrackLabels.map(([track, label, rowId = track, visibilityKey = track]) => (
<div
@@ -789,17 +983,6 @@ export function Timeline({
startTimelineSeek(event);
}}
>
<div className="ruler" onPointerDown={startTimelineSeek}>
{rulerTicks.map((tick) => (
<span
className={`ruler-tick ${tick.isMajor ? "is-major" : "is-minor"}`}
key={tick.id}
style={{ left: `${tick.left}%` }}
>
{tick.label}
</span>
))}
</div>
<div
className="playhead"
role="slider"
@@ -824,7 +1007,7 @@ export function Timeline({
className={`image-track ${selectedTrack === "image" ? "is-selected" : ""} ${
!trackVisibility.image ? "is-track-disabled" : ""
} ${
assetDropTargetTrack === "image" ? "is-drop-target" : ""
assetDropTargetTrack === "image" || assetDropTargetTrack === "overlay" || overlayPromotionTarget ? `is-drop-target is-drop-${overlayPromotionTarget ? "image" : assetDropTargetTrack}` : ""
} ${assetDropPulseTrack === "image" ? "is-drop-landing" : ""} ${
activeTimelineClipDrag?.track === "image" ? "is-reordering" : ""
}`}
@@ -839,8 +1022,8 @@ export function Timeline({
data-timeline-reorder-track="image"
onContextMenu={(event) => showTrackContextMenu(event, "image")}
>
{assetDropTargetTrack === "image" ? (
<div className="track-drop-hint">{t("dropVisualHere")}</div>
{assetDropTargetTrack === "image" || assetDropTargetTrack === "overlay" ? (
<div className="track-drop-hint">{assetDropTargetTrack === "overlay" ? t("dropAsOverlay", "作为画中画") : t("appendAfter", "添加到后面")}</div>
) : null}
{imageSrc
? displayedVisualSegments.map((segment, index) => {
@@ -864,6 +1047,15 @@ export function Timeline({
activeTimelineClipDrag?.track === "image" &&
activeTimelineClipDrag.overIndex === index &&
!isDraggingVisualSegment;
const isOverlayPromotionInsertTarget = Boolean(
overlayPromotionTarget && overlayPromotionTarget.insertIndex === index,
);
const promotionOverlay = isOverlayPromotionInsertTarget
? visualOverlaySegments.find((item) => item.id === overlayPromotionTarget.segmentId)
: null;
const promotionGapWidth = timelineDuration > 0
? Math.max(0.01, Math.min(100, ((promotionOverlay?.duration || 0.5) / timelineDuration) * 100))
: 0;
const videoTrackFrames = Array.isArray(segment.trackFrames) ? segment.trackFrames : [];
const visibleVideoFrames =
segmentType === "video" && videoTrackFrames.length
@@ -889,12 +1081,17 @@ export function Timeline({
data-timeline-segment-index={index}
data-timeline-segment-id={segment.id}
data-placeholder={t("dropSlot", "放置位置")}
style={{ "--image-clip-width": `${segmentWidth}%` }}
style={{
"--image-clip-width": `${segmentWidth}%`,
"--promotion-gap-width": `${promotionGapWidth}%`,
}}
className={`image-clip ${segmentType === "video" ? "is-video" : ""} ${
isCurrentVisualSegment ? "is-current" : ""
} ${isSelectedVisualSegment ? "is-selected-segment" : ""} ${
isDraggingVisualSegment ? "is-reorder-dragging" : ""
} ${isReorderTarget ? "is-reorder-target" : ""}`}
} ${isReorderTarget ? "is-reorder-target" : ""} ${
isOverlayPromotionInsertTarget ? "is-overlay-promotion-insert-target" : ""
}`}
onPointerDown={(event) => startTimelineClipDrag(event, "image", segment.id, index)}
onContextMenu={(event) => showTrackContextMenu(event, "image", segment.id)}
onClick={(event) => {
@@ -915,6 +1112,21 @@ export function Timeline({
}
}}
>
{segmentType === "video" ? (
<button
className="clip-mute-toggle"
type="button"
aria-label={t(segment.sourceAudioDisabled ? "unmuteClip" : "muteClip", segment.sourceAudioDisabled ? "取消静音" : "静音")}
title={t(segment.sourceAudioDisabled ? "unmuteClip" : "muteClip", segment.sourceAudioDisabled ? "取消静音" : "静音")}
onPointerDown={(event) => event.stopPropagation()}
onClick={(event) => {
event.stopPropagation();
setVisualSegments((items) => items.map((item) => item.id === segment.id ? { ...item, sourceAudioDisabled: !item.sourceAudioDisabled } : item));
}}
>
{segment.sourceAudioDisabled ? <SpeakerSlash size={13} /> : <SpeakerHigh size={13} />}
</button>
) : null}
<div
className={`image-thumbnails ${segmentType === "video" ? "is-video" : ""} ${
isPortraitVideo ? "is-portrait-video" : ""
@@ -968,6 +1180,24 @@ export function Timeline({
);
})
: null}
{overlayPromotionTarget ? (() => {
const insertIndex = Math.max(0, Math.min(displayedVisualSegments.length, overlayPromotionTarget.insertIndex));
const insertTime = insertIndex < renderedVisualTimeline.length
? renderedVisualTimeline[insertIndex]?.start || 0
: renderedVisualTimeline.at(-1)?.end || 0;
const overlay = visualOverlaySegments.find((item) => item.id === overlayPromotionTarget.segmentId);
return (
<div
className="main-track-drop-preview"
style={{
"--main-drop-left": `${timelineDuration > 0 ? Math.max(0, Math.min(100, insertTime / timelineDuration * 100)) : 0}%`,
"--main-drop-width": `${timelineDuration > 0 ? Math.max(0.01, Math.min(100, (overlay?.duration || 0.5) / timelineDuration * 100)) : 0}%`,
}}
>
<span>{t("dropSlot", "放置位置")}</span>
</div>
);
})() : null}
{displayedVisualSegments.slice(0, -1).map((segment, index) => {
const range = renderedVisualTimeline[index];
const transition = segment.transition || { id: "none", duration: 0.5 };
@@ -989,7 +1219,9 @@ export function Timeline({
);
})}
{renderAssetDropSlot("image")}
{renderAssetDropSlot("overlay")}
</div>
{overlayLanes.map((lane, laneIndex) => renderOverlayTrack(lane, laneIndex))}
{showStickerTrack ? stickerLanes.map((lane, laneIndex) => renderStickerTrack(lane, laneIndex)) : null}
{captionLanes.map((lane, laneIndex) => (
<div
@@ -1072,7 +1304,7 @@ export function Timeline({
})}
</div>
))}
<button
{showSourceTrack ? <button
className={`audio-track source-track ${selectedTrack === "source" ? "is-selected" : ""} ${
!trackVisibility.source ? "is-track-disabled" : ""
} ${
@@ -1093,6 +1325,12 @@ export function Timeline({
<div className="track-drop-hint">{t("dropSourceHere")}</div>
) : null}
{renderAssetDropSlot("source")}
{sourceAudioExtractionPendingId && !sourceAudioBlob ? (
<div className="source-audio-extraction-state" role="status" aria-live="polite">
<CircleNotch size={16} />
<span>{t("separatingSourceAudio", "正在分离音频…")}</span>
</div>
) : null}
{sourceAudioBlob && sourceAudioLinked && linkedSourceAudioSegments.length ? linkedSourceAudioSegments.map((segment) => (
<div
className={`audio-clip is-source is-linked ${selectedSourceAudioSegmentId === segment.id ? "is-selected" : ""}`}
@@ -1133,7 +1371,7 @@ export function Timeline({
<span className="audio-clip-duration">{formatTime(sourceAudioDuration)}</span>
</div>
) : null}
</button>
</button> : null}
{audioLanes.map((lane, laneIndex) => (
<button
className={`audio-track ${selectedTrack === "audio" ? "is-selected" : ""} ${
@@ -1179,7 +1417,7 @@ export function Timeline({
})}
</button>
))}
<button
{showMusicTrack ? <button
className={`audio-track music-track ${selectedTrack === "music" ? "is-selected" : ""} ${
!trackVisibility.music ? "is-track-disabled" : ""
} ${
@@ -1206,7 +1444,7 @@ export function Timeline({
<span className="audio-clip-duration">{formatTime(musicDuration)}</span>
</div>
) : null}
</button>
</button> : null}
</div>
</div>
</div>
@@ -1236,7 +1474,7 @@ export function Timeline({
) : null}
{contextMenu ? (
<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>
<div className="timeline-context-heading">{contextMenu.kind === "clip" ? t("clipActions") : t("trackActions")}<span>{t({ image: "imageTrack", overlay: "overlayTrack", 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" ? (
<>
@@ -1252,6 +1490,16 @@ export function Timeline({
{t(imageCaptionPendingId === contextImageSegment.id ? "generatingImageAiCaption" : "generateImageAiCaption")}
</button>
) : null}
{contextMenu.track === "image" && contextImageSegment?.type === "video" ? <>
<button type="button" role="menuitem" onClick={() => runContextAction(() => setVisualSegments((items) => items.map((item) => item.id === contextImageSegment.id ? { ...item, sourceAudioDisabled: !item.sourceAudioDisabled } : item)))}>{contextImageSegment.sourceAudioDisabled ? <SpeakerHigh size={16} /> : <SpeakerSlash size={16} />}{t(contextImageSegment.sourceAudioDisabled ? "unmuteClip" : "muteClip", contextImageSegment.sourceAudioDisabled ? "取消静音" : "静音")}</button>
<button type="button" role="menuitem" disabled={Boolean(sourceAudioExtractionPendingId)} onClick={() => void runSourceAudioExtraction(contextImageSegment)}>
{sourceAudioExtractionPendingId === contextImageSegment.id ? <CircleNotch size={16} /> : <Waveform size={16} />}
{t(sourceAudioExtractionPendingId === contextImageSegment.id ? "separatingSourceAudio" : "separateSourceAudio", sourceAudioExtractionPendingId === contextImageSegment.id ? "正在分离音频…" : "分离音频")}
</button>
</> : null}
{contextMenu.track === "overlay" && contextOverlaySegment?.type === "video" ? (
<button type="button" role="menuitem" onClick={() => runContextAction(() => setVisualOverlaySegments((items) => items.map((item) => item.id === contextOverlaySegment.id ? { ...item, muted: !item.muted } : item)))}>{contextOverlaySegment.muted ? <SpeakerHigh size={16} /> : <SpeakerSlash size={16} />}{t(contextOverlaySegment.muted ? "unmuteClip" : "muteClip", contextOverlaySegment.muted ? "取消静音" : "静音")}</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" />
+22 -7
View File
@@ -76,7 +76,6 @@ function AutoEditReviewDialog({ t, autoEdit }) {
function AutoEditPanel({ t, hasVisual, language, autoEdit }) {
const availability = autoEdit?.support?.availability || "unknown";
const languageFallback = autoEdit?.support?.language && autoEdit.support.language !== language;
const ready = availability === "available" || availability === "downloadable" || availability === "downloading";
return (<>
<div className="auto-edit-panel">
@@ -84,7 +83,6 @@ function AutoEditPanel({ t, hasVisual, language, autoEdit }) {
<section className="auto-edit-status-card">
<div><span>{t("autoEditBrowserModel")}</span><strong className={`auto-edit-availability is-${availability}`}>{t(`autoEditStatus_${availability}`)}</strong></div>
<p>{t("autoEditPrivacyHint")}</p>
{languageFallback ? <p className="auto-edit-warning">{t("autoEditLanguageFallback")}</p> : null}
<button className="panel-secondary" type="button" disabled={autoEdit?.job?.running || availability === "checking"} onClick={autoEdit?.checkSupport}>{t("autoEditCheckSupport")}</button>
</section>
<div className="auto-edit-flow"><span>1</span><p><strong>{t("autoEditStepScenes")}</strong><small>{t("autoEditStepScenesHint")}</small></p><span>2</span><p><strong>{t("autoEditStepCaptions")}</strong><small>{t("autoEditStepCaptionsHint")}</small></p><span>3</span><p><strong>{t("autoEditStepTimeline")}</strong><small>{t("autoEditStepTimelineHint")}</small></p></div>
@@ -451,6 +449,10 @@ export function VoicePanel({
selectedFilterId,
setSelectedFilterId,
trOption,
selectedVisualOverlay,
updateVisualOverlaySegment,
deleteVisualOverlay,
applyVisualOverlayPreset,
}) {
const [captionPanelTab, setCaptionPanelTab] = useState("caption");
const panelRef = useRef(null);
@@ -462,14 +464,17 @@ export function VoicePanel({
const isAudioClipContext = selectedTrack === "audio" && Boolean(selectedAudioSegment);
const isVisualContext = !isSmartContext && selectedTrack === "image";
const isStickerContext = selectedTrack === "sticker" && Boolean(selectedStickerSegment);
const isOverlayContext = selectedTrack === "overlay" && Boolean(selectedVisualOverlay);
const selectedCaptionAudioSegment = getCaptionVoiceSegment(audioSegments, selectedCaptionSegment);
const title = isSmartAutoContext ? t("smartAutoEdit") : isSmartFrameContext ? t("smartFrame") : isAvatarContext ? t("avatarTitle") : isStickerContext ? t("stickerProperties") : isVisualContext ? t("visualPanelTitle") : isCaptionContext ? t("caption") : isAudioClipContext ? t("audioClipProperties") : t("aiVoice");
const title = isSmartAutoContext ? t("smartAutoEdit") : isSmartFrameContext ? t("smartFrame") : isAvatarContext ? t("avatarTitle") : isOverlayContext ? t("pictureInPicture", "画中画") : isStickerContext ? t("stickerProperties") : isVisualContext ? t("visualPanelTitle") : isCaptionContext ? t("caption") : isAudioClipContext ? t("audioClipProperties") : t("aiVoice");
const panelStatusText = isSmartAutoContext ? t(`autoEditStatus_${autoEdit?.support?.availability || "unknown"}`) : isSmartFrameContext ? (hasVisual ? t("smartVisualReady") : t("smartWaitingVisual")) : isCaptionContext
? captionSegments.length
? `${captionSegments.length} ${t("captionSegmentsUnit", "条字幕")}`
: t("noCaptionSegments")
: isStickerContext
? `${selectedStickerSegment.start.toFixed(2)}s · ${selectedStickerSegment.duration.toFixed(2)}s`
: isOverlayContext
? `${selectedVisualOverlay.start.toFixed(2)}s · ${selectedVisualOverlay.duration.toFixed(2)}s · L${selectedVisualOverlay.layer || 1}`
: isVisualContext
? selectedVisualSegment
? `${visualLocalTime.toFixed(2)}s · ${normalizeVisualKeyframes(selectedVisualSegment.keyframes).length} ${t("visualFrames")}`
@@ -506,7 +511,7 @@ export function VoicePanel({
</span>
</div>
{!isSmartContext && !isCaptionContext && !isAvatarContext && !isAudioClipContext && !isVisualContext && !isStickerContext ? (
{!isSmartContext && !isCaptionContext && !isAvatarContext && !isAudioClipContext && !isVisualContext && !isStickerContext && !isOverlayContext ? (
<div className="tabs compact">
{[
["synthesis", t("voiceSynthesis")],
@@ -552,6 +557,16 @@ export function VoicePanel({
{isSmartAutoContext ? <AutoEditPanel t={t} hasVisual={hasVisual} language={uiLanguage} autoEdit={autoEdit} /> : null}
{isSmartFrameContext ? <SmartVisionPanel t={t} language={uiLanguage} hasVisual={hasVisual} visualType={visualType} analysis={visionAnalysis} options={visionOptions} running={visionRunning} progress={visionProgress} phase={visionPhase} onAnalyze={analyzeCurrentVisual} onToggle={toggleVisionOption} onClear={clearVisionAnalysis} onDownloadCutout={downloadVisionCutout} /> : null}
{isStickerContext ? <StickerContextPanel t={t} segment={selectedStickerSegment} updateStickerSegment={updateStickerSegment} deleteStickerSegment={deleteStickerSegment} /> : null}
{isOverlayContext ? <div className="visual-overlay-inspector">
<div className="sticker-properties-preview">{selectedVisualOverlay.type === "video" ? <video src={selectedVisualOverlay.src} muted playsInline /> : <img src={selectedVisualOverlay.src} alt="" />}</div>
<section className="visual-overlay-presets"><strong>{t("layoutPresets", "布局预设")}</strong><div>
{[["top-left", "↖"], ["top-right", "↗"], ["bottom-left", "↙"], ["bottom-right", "↘"], ["center", "●"], ["full", "□"]].map(([id, label]) => <button type="button" key={id} title={id} aria-label={`${t("layoutPresets", "布局预设")} ${id}`} onClick={() => applyVisualOverlayPreset?.(id)}>{label}</button>)}
</div></section>
<label><span>{t("clipStart", "开始时间")}</span><input type="number" min="0" step="0.1" value={selectedVisualOverlay.start} onChange={(event) => updateVisualOverlaySegment?.({ start: Math.max(0, Number(event.target.value) || 0) })} /></label>
<label><span>{t("clipDuration", "持续时间")}</span><input type="number" min="0.1" step="0.1" value={selectedVisualOverlay.duration} onChange={(event) => updateVisualOverlaySegment?.({ duration: Math.max(0.1, Number(event.target.value) || 0.1) })} /></label>
<label><span>{t("layer", "图层")}</span><input type="number" min="1" step="1" value={selectedVisualOverlay.layer || 1} onChange={(event) => updateVisualOverlaySegment?.({ layer: Math.max(1, Math.round(Number(event.target.value) || 1)) })} /></label>
<button className="panel-secondary visual-overlay-delete" type="button" onClick={deleteVisualOverlay}><Trash size={14} />{t("delete", "删除")}</button>
</div> : null}
{isVisualContext && selectedVisualSegment ? (
<VisualEffectsPanel
contextMode
@@ -633,7 +648,7 @@ export function VoicePanel({
{isAudioClipContext ? <AudioClipContextPanel t={t} segment={selectedAudioSegment} updateAudioSegment={updateAudioSegment} toggleAudioSegmentReverse={toggleAudioSegmentReverse} deleteAudioSegment={deleteAudioSegment} downloadBlob={downloadBlob} /> : null}
{!isSmartContext && !isCaptionContext && !isAvatarContext && !isAudioClipContext && !isVisualContext && !isStickerContext && voiceTab === "synthesis" ? (
{!isSmartContext && !isCaptionContext && !isAvatarContext && !isAudioClipContext && !isVisualContext && !isStickerContext && !isOverlayContext && voiceTab === "synthesis" ? (
<VoiceSynthesisPanel
script={script}
updateScript={updateScript}
@@ -661,7 +676,7 @@ export function VoicePanel({
/>
) : null}
{!isSmartContext && !isCaptionContext && !isAvatarContext && !isAudioClipContext && !isVisualContext && !isStickerContext && voiceTab === "mine" ? (
{!isSmartContext && !isCaptionContext && !isAvatarContext && !isAudioClipContext && !isVisualContext && !isStickerContext && !isOverlayContext && voiceTab === "mine" ? (
<MyVoicesPanel
favoriteVoiceIds={favoriteVoiceIds}
setFavoriteVoiceIds={setFavoriteVoiceIds}
@@ -679,7 +694,7 @@ export function VoicePanel({
/>
) : null}
{!isSmartContext && !isCaptionContext && !isAvatarContext && !isAudioClipContext && !isVisualContext && !isStickerContext && voiceTab === "history" ? (
{!isSmartContext && !isCaptionContext && !isAvatarContext && !isAudioClipContext && !isVisualContext && !isStickerContext && !isOverlayContext && voiceTab === "history" ? (
<HistoryPanel
historyItems={historyItems}
useHistoryItem={useHistoryItem}
+6 -2
View File
@@ -568,7 +568,7 @@ export function VisualEffectsPanel({ t, segment, localTime, onChange, onSeek, on
const [animationSection, setAnimationSection] = useState("in");
const [hoveredAnimation, setHoveredAnimation] = useState(null);
const keyframes = normalizeVisualKeyframes(segment?.keyframes ?? []);
const transform = resolveVisualTransform(keyframes, localTime);
const transform = resolveVisualTransform(keyframes, localTime, segment?.baseTransform);
const mask = segment?.mask ?? { type: "none", feather: 0, inverted: false };
const hasMask = mask.type && mask.type !== "none";
const isCircleMask = mask.type === "circle";
@@ -577,7 +577,11 @@ export function VisualEffectsPanel({ t, segment, localTime, onChange, onSeek, on
const clipAnimation = normalizeVisualClipAnimation(segment?.animation);
const activeAnimation = clipAnimation[animationSection];
const sourceDuration = Math.max(0, Number(segment?.sourceDuration) || (Number(segment?.duration) || 0) * playbackRate);
const updateTransform = (key, value) => onChange?.({ propertyKeyframe: { time: localTime, key, value } });
const updateTransform = (key, value) => onChange?.(
hasVisualPropertyKeyframe(keyframes, localTime, key)
? { propertyKeyframe: { time: localTime, key, value } }
: { baseTransform: { [key]: value } },
);
const tabs = [
["transform", t("visualTabTransform")],
["mask", t("visualTabMask")],
+8 -2
View File
@@ -10,8 +10,8 @@ import {
const HISTORY_LIMIT = 50;
const HISTORY_DEBOUNCE_MS = 180;
function cloneItems(items) {
return items.map((item) => ({ ...item }));
function cloneItems(items = []) {
return (Array.isArray(items) ? items : []).map((item) => ({ ...item }));
}
function createSnapshot(d) {
@@ -24,6 +24,7 @@ function createSnapshot(d) {
captionStyle: { ...d.captionStyle },
captionsEnabled: d.captionsEnabled,
visualSegments: cloneItems(d.visualSegments),
visualOverlaySegments: cloneItems(d.visualOverlaySegments),
imageSrc: d.imageSrc,
imageName: d.imageName,
imageMeta: d.imageMeta,
@@ -59,6 +60,7 @@ function createSnapshot(d) {
selectedTrack: d.selectedTrack,
selectedSegmentId: d.selectedSegmentId,
selectedVisualSegmentId: d.selectedVisualSegmentId,
selectedVisualOverlayId: d.selectedVisualOverlayId,
selectedStickerSegmentId: d.selectedStickerSegmentId,
selectedAudioSegmentId: d.selectedAudioSegmentId,
currentTime: d.currentTime,
@@ -86,6 +88,7 @@ export function createEditorSnapshotSignature(snapshot) {
captionStyle: snapshot.captionStyle,
captionsEnabled: snapshot.captionsEnabled,
visuals: snapshot.visualSegments.map(mediaIdentity),
visualOverlays: (snapshot.visualOverlaySegments ?? []).map(mediaIdentity),
image: {
name: snapshot.imageName,
meta: snapshot.imageMeta,
@@ -139,6 +142,7 @@ function restoreSnapshot(snapshot, d) {
return { ...item, src: item.src ? nextUrl : item.src, url: item.url ? nextUrl : item.url };
};
const visualSegments = snapshot.visualSegments.map(restoreAsset);
const visualOverlaySegments = (snapshot.visualOverlaySegments ?? []).map(restoreAsset);
const userAssets = snapshot.userAssets.map(restoreAsset);
const restoredImage = visualSegments.find((item) => item.id === snapshot.selectedVisualSegmentId)
?? visualSegments.find((item) => item.src)
@@ -152,6 +156,7 @@ function restoreSnapshot(snapshot, d) {
d.setCaptionStyle({ ...snapshot.captionStyle });
d.setCaptionsEnabled(snapshot.captionsEnabled);
d.setVisualSegments(visualSegments);
d.setVisualOverlaySegments(visualOverlaySegments);
d.setImageSrc(restoredImage?.src || snapshot.imageSrc);
d.setImageName(snapshot.imageName);
d.setImageMeta(snapshot.imageMeta);
@@ -194,6 +199,7 @@ function restoreSnapshot(snapshot, d) {
d.setSelectedTrack(snapshot.selectedTrack);
d.setSelectedSegmentId(snapshot.selectedSegmentId);
d.setSelectedVisualSegmentId(snapshot.selectedVisualSegmentId);
d.setSelectedVisualOverlayId(snapshot.selectedVisualOverlayId);
d.setSelectedStickerSegmentId(snapshot.selectedStickerSegmentId);
d.setSelectedAudioSegmentId(snapshot.selectedAudioSegmentId);
d.setCurrentTime(snapshot.currentTime);
+1
View File
@@ -137,6 +137,7 @@ export function useEditorLifecycle(d) {
(d.selectedTrack === "caption" && d.selectedSegmentId && d.captionSegments.some((segment) => segment.id === d.selectedSegmentId)) ||
(d.selectedTrack === "sticker" && d.selectedStickerSegmentId && d.stickerSegments.some((segment) => segment.id === d.selectedStickerSegmentId)) ||
(d.selectedTrack === "image" && d.selectedVisualSegmentId && d.visualSegments.some((segment) => segment.id === d.selectedVisualSegmentId)) ||
(d.selectedTrack === "overlay" && d.selectedVisualOverlayId && d.visualOverlaySegments.some((segment) => segment.id === d.selectedVisualOverlayId)) ||
(d.selectedTrack === "audio" && d.selectedAudioSegmentId && d.audioSegments.some((segment) => segment.id === d.selectedAudioSegmentId)) ||
(d.selectedTrack === "source" && d.sourceAudioBlob) ||
(d.selectedTrack === "music" && d.musicBlob);
+13 -3
View File
@@ -3,6 +3,12 @@ import { MAX_TIMELINE_DURATION_SECONDS, SUPPORTED_MEDIA_TYPES } from "../config/
import { decodeWaveform, extractVideoTrackFrames } from "../lib/media.js";
import { formatClock, formatTime } from "../lib/timeline.js";
export function shouldAutoAddImportedVisual(assets, visualSegments) {
return Boolean(
!visualSegments.length && assets.some((asset) => asset.type === "image" || asset.type === "video"),
);
}
export function useFileUpload(deps) {
return useCallback((files) => {
const mediaFiles = Array.from(files ?? []).filter((file) => SUPPORTED_MEDIA_TYPES.some((type) => file.type.startsWith(type)));
@@ -15,7 +21,8 @@ export function useFileUpload(deps) {
});
const primary = assets[0]; deps.setSelectedLibraryAssetId(primary.id); deps.setUserAssets((current) => [...assets, ...current]);
const primaryVisual = assets.find((asset) => asset.type === "image" || asset.type === "video");
if (primaryVisual) {
const shouldAutoAddFirstVisual = shouldAutoAddImportedVisual(assets, deps.visualSegments);
if (shouldAutoAddFirstVisual) {
deps.appendVisualAssetToTimeline(primaryVisual);
deps.setSelectedTrack("image");
}
@@ -47,7 +54,10 @@ export function useFileUpload(deps) {
};
image.onerror = () => update(asset.id, { meta: "读取失败" }); image.src = asset.src;
});
deps.notify(mediaFiles.length > 1 ? `已上传 ${mediaFiles.length} 个素材${primaryVisual ? ",首个画面已加入时间线" : ""}`
: primaryVisual ? `${primary.type === "video" ? "视频" : "图片"}已加入画布和时间线` : "音频已上传到素材库,可拖到音乐或配音轨");
deps.notify(mediaFiles.length > 1 ? `已上传 ${mediaFiles.length} 个素材${shouldAutoAddFirstVisual ? ",项目首个画面已加入时间线" : ",请拖到目标轨道使用"}`
: primaryVisual ? shouldAutoAddFirstVisual
? `${primary.type === "video" ? "视频" : "图片"}已加入画布和时间线`
: `${primary.type === "video" ? "视频" : "图片"}已加入素材库,请拖到 Visuals 或画中画轨道`
: "音频已上传到素材库,可拖到音乐或配音轨");
}, [deps]);
}
+15
View File
@@ -0,0 +1,15 @@
import { describe, expect, it } from "vitest";
import { shouldAutoAddImportedVisual } from "./useFileUpload.js";
describe("visual import placement", () => {
it("auto-adds the first project visual only", () => {
const assets = [{ type: "audio" }, { type: "image" }, { type: "video" }];
expect(shouldAutoAddImportedVisual(assets, [])).toBe(true);
expect(shouldAutoAddImportedVisual(assets, [{ id: "existing" }])).toBe(false);
});
it("does not auto-add audio-only imports", () => {
expect(shouldAutoAddImportedVisual([{ type: "audio" }], [])).toBe(false);
});
});
+24 -6
View File
@@ -1,5 +1,5 @@
import { useEffect } from "react";
import { PLAYBACK_UI_FRAME_MS, getAudioSegmentPreviewVolume, getTimelineTrackLocalTime, isTimelineTimeInsideTrack } from "../lib/editorRuntime.js";
import { startTransition, useEffect } from "react";
import { PLAYBACK_UI_FRAME_MS, getAudioSegmentPreviewVolume, getTimelineTrackLocalTime, isTimelineTimeInsideTrack, shouldCorrectPreviewMediaTime } from "../lib/editorRuntime.js";
import { getLinkedSourceAudioState } from "../lib/sourceAudioSync.js";
export function useMediaSync(d) {
@@ -38,11 +38,26 @@ export function useMediaSync(d) {
useEffect(() => {
const v = d.previewVideoRef.current; if (!v || d.previewVisualType !== "video") return;
v.playbackRate = Math.max(0.25, Math.min(4, Number(d.previewVisualSegment?.playbackRate) || 1));
}, [d.previewVisualSegment?.playbackRate, d.previewVisualSrc, d.previewVisualType]);
useEffect(() => {
const v = d.previewVideoRef.current; if (!v || d.previewVisualType !== "video") return;
const sourceStart = Math.max(0, Number(d.previewVisualSegment?.sourceStart) || 0);
const max = Math.max(0, (Number(v.duration) || sourceStart) - 0.001);
const time = Math.min(sourceStart, max);
if (Number.isFinite(time) && Math.abs(v.currentTime - time) > 0.04) {
v.currentTime = time;
d.setPreviewVideoMediaTime(time);
}
}, [d.previewVisualSegment?.id, d.previewVisualSegment?.sourceStart, d.previewVisualSrc, d.previewVisualType]);
useEffect(() => {
const v = d.previewVideoRef.current; if (!v || d.previewVisualType !== "video") return;
const max = Math.max(0, (Number(v.duration) || d.previewVisualSourceTime) - 0.001);
const time = Math.min(Math.max(0, d.previewVisualSourceTime), max);
if (Number.isFinite(time) && Math.abs(v.currentTime - time) > 0.2) { v.currentTime = time; d.setPreviewVideoMediaTime(time); }
if (d.isPlaying && d.trackVisibility.image && v.paused) v.play().catch(() => {});
}, [d.isPlaying, d.previewVisualSegment?.playbackRate, d.previewVisualSourceTime, d.previewVisualSrc, d.previewVisualType, d.trackVisibility.image]);
if (shouldCorrectPreviewMediaTime({ isPlaying: d.isPlaying, currentTime: v.currentTime, targetTime: time })) {
v.currentTime = time;
d.setPreviewVideoMediaTime(time);
}
}, [d.isPlaying, d.previewVisualSegment?.id, d.previewVisualSourceTime, d.previewVisualSrc, d.previewVisualType]);
useEffect(() => {
const v = d.previewVideoRef.current; if (!v || d.previewVisualType !== "video") return;
if (!d.isPlaying || !d.trackVisibility.image) v.pause(); else v.play().catch(() => {});
@@ -55,7 +70,10 @@ export function useMediaSync(d) {
const tick = (now) => {
const next = Math.min(d.estimatedDuration, d.visualPlaybackStartTimeRef.current + (now - d.visualPlaybackStartedAtRef.current) / 1000);
d.currentTimeRef.current = next;
if (now - d.visualPlaybackLastUpdateRef.current > PLAYBACK_UI_FRAME_MS || next >= d.estimatedDuration) { d.visualPlaybackLastUpdateRef.current = now; d.setCurrentTime(next); }
if (now - d.visualPlaybackLastUpdateRef.current > PLAYBACK_UI_FRAME_MS || next >= d.estimatedDuration) {
d.visualPlaybackLastUpdateRef.current = now;
startTransition(() => d.setCurrentTime(next));
}
if (next >= d.estimatedDuration) { d.pauseTimelineMedia(); d.setIsPlaying(false); d.visualPlaybackFrameRef.current = 0; return; }
d.visualPlaybackFrameRef.current = requestAnimationFrame(tick);
};
+9
View File
@@ -1,10 +1,19 @@
import { useEffect, useState } from "react";
export function isValidPreviewShellMeasurement(shell) {
return Boolean(shell?.isConnected && shell.clientWidth >= 2 && shell.clientHeight >= 2);
}
export function usePreviewFrameSize(shellRef, ratio, compactRail) {
const [size, setSize] = useState({ width: 0, height: 0 });
useEffect(() => {
const shell = shellRef.current;
if (!shell) return undefined;
const update = () => {
// Moving PreviewStage into or out of its large-canvas portal briefly
// disconnects the old shell. Ignore that transient 0/1px measurement so
// it cannot replace the valid inline preview size after the portal closes.
if (!isValidPreviewShellMeasurement(shell)) return;
const style = getComputedStyle(shell);
const aw = Math.max(1, shell.clientWidth - parseFloat(style.paddingLeft || 0) - parseFloat(style.paddingRight || 0));
const ah = Math.max(1, shell.clientHeight - parseFloat(style.paddingTop || 0) - parseFloat(style.paddingBottom || 0));
+9 -2
View File
@@ -7,11 +7,12 @@ import { createCaptionSegments, getImageThumbnailCount, getVisualSegmentsTotal }
export function useProjectFiles(deps) {
const getProjectSnapshot = useCallback(() => {
const visualSegments = deps.visualSegments.map(({ blob, trackFrames, src, cutoutVisual, enhancement: _enhancement, ...segment }) => segment);
const visualOverlaySegments = deps.visualOverlaySegments.map(({ blob, src, ...segment }) => segment);
return {
script: deps.script, selectedVoiceId: deps.selectedVoiceId, speed: deps.speed, volume: deps.volume,
ratioId: deps.ratioId, fitMode: deps.fitMode, captionPosition: deps.captionPosition,
captionPlacement: deps.captionPlacement, captionSize: deps.captionSize, captionStyle: deps.captionStyle,
captionsEnabled: deps.captionsEnabled, captionSegments: deps.captionSegments, visualSegments,
captionsEnabled: deps.captionsEnabled, captionSegments: deps.captionSegments, visualSegments, visualOverlaySegments,
stickerSegments: deps.stickerSegments, selectedFilterId: deps.selectedFilterId,
selectedTransitionId: deps.selectedTransitionId, selectedStickerId: deps.selectedStickerId,
trackVisibility: deps.trackVisibility, timelineZoom: deps.timelineZoom, audioDuration: deps.audioDuration,
@@ -28,7 +29,7 @@ export function useProjectFiles(deps) {
try {
deps.notify("正在打包工程与媒体素材…");
const archive = await createProjectArchive({
project: getProjectSnapshot(), visualSegments: deps.visualSegments,
project: getProjectSnapshot(), visualSegments: [...deps.visualSegments, ...deps.visualOverlaySegments],
audio: deps.audioBlob ? { blob: deps.audioBlob, name: "ai-voiceover" } : null,
sourceAudio: deps.sourceAudioBlob ? { blob: deps.sourceAudioBlob, name: deps.sourceAudioName || "source-audio" } : null,
music: deps.musicBlob ? { blob: deps.musicBlob, name: deps.musicName || "background-music" } : null,
@@ -42,6 +43,7 @@ export function useProjectFiles(deps) {
if (!window.confirm("新建工程将清空当前时间线,是否继续?")) return;
deps.setScript(DEFAULT_SCRIPT); deps.setCaptionSegments(createCaptionSegments(DEFAULT_SCRIPT));
deps.setSelectedSegmentId(""); deps.clearImageTrack(""); deps.clearAudioTrack("");
deps.setVisualOverlaySegments([]); deps.setSelectedVisualOverlayId("");
deps.clearSourceAudioTrack(""); deps.clearMusicTrack(""); deps.setStickerSegments([]);
deps.setSelectedStickerSegmentId(""); deps.clearAllVisionState(); deps.setCurrentTime(0);
deps.setTimelineHorizon(DEFAULT_TIMELINE_DURATION_SECONDS); deps.setTimelineZoom(1);
@@ -79,6 +81,11 @@ export function useProjectFiles(deps) {
}).filter(Boolean) : [];
visuals.filter((segment) => segment.src?.startsWith("blob:")).forEach((segment) => deps.imageUrlRefs.current.add(segment.src));
deps.setVisualSegments(visuals); deps.setImageDuration(getVisualSegmentsTotal(visuals));
const overlays = Array.isArray(data.visualOverlaySegments) ? data.visualOverlaySegments.map((segment) => {
const media = visualMedia.get(segment.assetId) || visualMedia.get(segment.id);
return media?.blob ? { ...segment, src: URL.createObjectURL(media.blob), blob: media.blob } : segment?.src ? segment : null;
}).filter(Boolean) : [];
deps.setVisualOverlaySegments(overlays); deps.setSelectedVisualOverlayId("");
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 || "", { focusAudio: false }); } else deps.clearSourceAudioTrack("");
+4 -2
View File
@@ -3,7 +3,7 @@ import { concatenateAudioBlobs, decodeWaveform, extractAudioFromVideo } from "..
export function useSourceAudioExtraction(d) {
return useCallback(async (asset, timelineStart = 0, options = {}) => {
if (!asset?.blob) { d.clearSourceAudioTrack(null); d.notify("当前视频素材缺少原文件,无法分离原声"); return; }
if (!asset?.blob) { d.notify("当前视频素材缺少原文件,无法分离原声"); return false; }
d.setStatus("generating"); d.setStatusText("加载 FFmpeg WASM 分离视频原声"); d.setProgress(12);
try {
const extractedBlob = await extractAudioFromVideo(asset.blob, asset.name); d.setStatusText("解析视频原声波形"); d.setProgress(78);
@@ -17,9 +17,11 @@ export function useSourceAudioExtraction(d) {
: segment));
const sourceName = shouldAppend ? "视频原声合集.wav" : `${asset.name.replace(/\.[^.]+$/, "")} 原声.wav`;
d.replaceSourceAudio(blob, decoded.duration, decoded.peaks, sourceName, shouldAppend ? "视频原声已追加到时间线" : "视频原声已分离到时间线", timelineStart, shouldAppend ? "" : asset.id, { focusAudio: false });
return true;
} catch (error) {
console.warn(error); if (!(options.append === true && d.sourceAudioBlob)) d.clearSourceAudioTrack(null); d.setStatus("ready"); d.setStatusText("视频未检测到可分离原声");
console.warn(error); d.setStatus("ready"); d.setStatusText("视频未检测到可分离原声");
d.setProgress(0); d.notify("视频画面已添加,但没有可分离的原声音轨");
return false;
}
}, [d]);
}
+12 -3
View File
@@ -22,6 +22,7 @@ import {
import { getVisionKey } from "../lib/vision.js";
import { getVisualSourceTime } from "../lib/visualEffects.js";
import { getTimelineProjectDuration } from "../lib/timelineScale.js";
import { getActiveVisualOverlays } from "../lib/visualOverlayTimeline.js";
export function useTimelineModel(d) {
const selectedVoice = useMemo(
@@ -78,17 +79,22 @@ export function useTimelineModel(d) {
() => getTimedSegmentsEnd(d.stickerSegments),
[d.stickerSegments],
);
const visualOverlayDuration = useMemo(
() => getTimedSegmentsEnd(d.visualOverlaySegments),
[d.visualOverlaySegments],
);
const estimatedDuration = useMemo(() => Math.max(
voiceTrackDuration,
captionDuration,
d.sourceAudioBlob ? (d.sourceAudioTimelineEnd ?? d.sourceAudioStart + d.sourceAudioDuration) : 0,
d.musicBlob ? d.musicStart + d.musicDuration : 0,
stickerDuration,
visualOverlayDuration,
d.imageSrc ? d.imageDuration : 0,
), [
voiceTrackDuration, captionDuration, d.imageDuration, d.imageSrc, d.musicBlob,
d.musicDuration, d.musicStart, d.sourceAudioBlob, d.sourceAudioDuration,
d.sourceAudioStart, d.sourceAudioTimelineEnd, stickerDuration,
d.sourceAudioStart, d.sourceAudioTimelineEnd, stickerDuration, visualOverlayDuration,
]);
const timelineDuration = useMemo(() => estimatedDuration <= 0
? DEFAULT_TIMELINE_DURATION_SECONDS
@@ -155,6 +161,9 @@ export function useTimelineModel(d) {
// creating a clip; it must not survive after the final sticker clip is deleted.
const previewSticker = d.trackVisibility.sticker ? currentStickerSegment : null;
const previewStickers = currentStickerSegments;
const previewVisualOverlays = d.trackVisibility.overlay === false
? []
: getActiveVisualOverlays(d.visualOverlaySegments, d.currentTime);
const currentVisualSegmentIndex = getVisualSegmentIndexAtTime(d.visualSegments, d.currentTime);
const currentVisualSegment = currentVisualSegmentIndex >= 0
? d.visualSegments[currentVisualSegmentIndex] ?? null
@@ -225,12 +234,12 @@ export function useTimelineModel(d) {
currentCaptionSegment, currentSegmentIndex, currentStickerSegment,
currentStickerSegmentIndex, currentVisualRange, currentVisualSegment,
currentVisualSegmentIndex, estimatedDuration, focusedSegmentIndex, getStickerDragAsset,
peaks, previewSticker, previewStickers, previewVisionBaseAnalysis, previewVisionKey,
peaks, previewSticker, previewStickers, previewVisualOverlays, previewVisionBaseAnalysis, previewVisionKey,
previewTransition, previewVisionRecord, previewVisualLocalTime, previewVisualRange, previewVisualSegment,
previewVisualSegmentIndex, previewVisualSourceTime, previewVisualSrc, previewVisualType,
ratio, segments, selectedAudioSegment, selectedCaptionSegment, selectedFilter,
selectedSegmentIndex, selectedSticker, selectedStickerSegmentIndex,
selectedVisualSegmentIndex, selectedVoice, stickerDuration, timelineDuration, visualTimeline,
voiceTrackDuration,
voiceTrackDuration, visualOverlayDuration,
};
}
+32 -14
View File
@@ -3,20 +3,37 @@ import { downloadBlob, exportBrowserVideo, getSupportedRecordingFormat, transcod
import { exportOfflineVideo } from "../lib/offlineVideoExport.js";
import { estimateDuration } from "../lib/timeline.js";
import { getVisionKey } from "../lib/vision.js";
import { prepareEmbeddedVideoAudio } from "../lib/embeddedVideoAudioExport.js";
export function useVideoExport(d) {
return useCallback(async () => {
if (d.exporting) return;
if (!d.imageSrc) return void d.notify("请先上传或选择图片/视频素材再导出");
d.setExporting(true); d.exportStartRef.current = performance.now(); d.setExportProgress(1);
d.setExportPhase("准备导出"); d.setStatus("generating");
const format = getSupportedRecordingFormat(); d.setStatusText(`录制 ${format.label} 视频流`); d.setExportPhase(`录制 ${format.label} 视频流`);
const progress = ({ progress, phase }) => {
const localize = (key, params = {}) => Object.entries(params).reduce(
(text, [name, value]) => text.replaceAll(`{${name}}`, String(value)),
d.t(key),
);
d.setExportPhase(localize("exportPreparing")); d.setStatus("generating");
const format = getSupportedRecordingFormat();
const recordingPhase = localize("exportRecordingStream", { format: format.label });
d.setStatusText(recordingPhase); d.setExportPhase(recordingPhase);
const progress = ({ progress, phase, phaseKey, phaseParams }) => {
d.setExportProgress((current) => Math.max(current, Math.min(100, Math.max(0, Math.round(progress)))));
if (phase) d.setExportPhase(phase);
const localizedPhase = phaseKey ? localize(phaseKey, phaseParams) : phase;
if (localizedPhase) d.setExportPhase(localizedPhase);
};
const finish = async (phase) => { d.setExportPhase(phase); d.setExportProgress(100); await new Promise((resolve) => setTimeout(resolve, 450)); };
try {
const embeddedVideoAudio = !d.sourceAudioBlob && d.trackVisibility.source !== false
? await prepareEmbeddedVideoAudio(d.renderedVisualSegments, progress)
: { blob: null, segments: [] };
const exportSourceAudioBlob = d.trackVisibility.source !== false
? d.sourceAudioBlob || embeddedVideoAudio.blob
: null;
const exportSourceAudioSegments = d.sourceAudioBlob
? d.sourceAudioLinked ? d.linkedSourceAudioSegments : []
: embeddedVideoAudio.segments;
const exportOptions = {
imageSrc: d.imageSrc, visualType: d.visualType,
visualSegments: d.renderedVisualSegments.map((segment) => {
@@ -24,8 +41,8 @@ export function useVideoExport(d) {
return record ? { ...segment, vision: { ...record.analysis, options: record.options } } : segment;
}),
audioBlob: null, voiceAudioSegments: d.trackVisibility.audio ? d.audioSegments : [], voiceVolume: d.volume,
sourceAudioBlob: d.trackVisibility.source ? d.sourceAudioBlob : null, sourceAudioVolume: d.sourceAudioVolume,
sourceAudioSegments: d.sourceAudioLinked ? d.linkedSourceAudioSegments : [],
sourceAudioBlob: exportSourceAudioBlob, sourceAudioVolume: d.sourceAudioBlob ? d.sourceAudioVolume : 1,
sourceAudioSegments: exportSourceAudioSegments,
sourceAudioStart: d.sourceAudioStart, musicBlob: d.trackVisibility.music ? d.musicBlob : null,
musicVolume: d.musicVolume, musicStart: d.musicStart, text: d.script, captionSegments: d.captionSegments,
duration: Math.max(d.trackVisibility.audio ? d.voiceTrackDuration : 0, d.captionDuration,
@@ -41,6 +58,7 @@ export function useVideoExport(d) {
// Stickers are timeline clips; a selected library item is not export content.
sticker: null,
stickerSegments: d.trackVisibility.sticker ? d.stickerSegments : [],
visualOverlaySegments: d.trackVisibility.overlay === false ? [] : d.visualOverlaySegments,
transitionId: "none", exportSettings: d.exportSettings, onProgress: progress,
};
let video;
@@ -48,31 +66,31 @@ export function useVideoExport(d) {
video = await exportOfflineVideo(exportOptions);
} catch (offlineError) {
console.warn("Offline WebCodecs export unavailable; using compatibility recorder", offlineError);
progress({ progress: 5, phase: "切换兼容导出模式" });
progress({ progress: 5, phaseKey: "exportCompatibility" });
video = await exportBrowserVideo(exportOptions);
}
const name = `ai-voiceover-${d.ratio.id.replace(":", "x")}`;
if (d.exportSettings.codec !== "h264") {
progress({ progress: 99, phase: `保存 ${video.label} 文件` });
progress({ progress: 99, phaseKey: "exportSaveFile", phaseParams: { format: video.label } });
downloadBlob(video.blob, `${name}.${video.extension}`);
d.setStatus("done"); d.setStatusText(`${video.label} 已导出`); await finish("导出完成");
d.setStatus("done"); d.setStatusText(localize("exportComplete")); await finish(localize("exportComplete"));
d.notify(`${video.label} 视频已导出`); return;
}
if (video.nativeMp4) {
progress({ progress: 98, phase: "保存 MP4 文件" }); downloadBlob(video.blob, `${name}.mp4`);
d.setStatus("done"); d.setStatusText("MP4 已导出"); await finish("导出完成"); d.notify("已用浏览器原生 MP4 快速导出"); return;
progress({ progress: 98, phaseKey: "exportSaveFile", phaseParams: { format: "MP4" } }); downloadBlob(video.blob, `${name}.mp4`);
d.setStatus("done"); d.setStatusText(localize("exportComplete")); await finish(localize("exportComplete")); d.notify(localize("exportComplete")); return;
}
d.setStatusText("当前浏览器不支持原生 MP4,加载 FFmpeg WASM"); progress({ progress: 95, phase: "加载 FFmpeg 转码器" });
try {
d.setStatusText("转码 MP4"); progress({ progress: 96, phase: "转码 MP4" });
const mp4 = await transcodeWebmToMp4(video.blob); progress({ progress: 99, phase: "保存 MP4 文件" });
downloadBlob(mp4, `${name}.mp4`); d.setStatus("done"); d.setStatusText("MP4 已导出"); await finish("导出完成"); d.notify("MP4 视频已导出");
const mp4 = await transcodeWebmToMp4(video.blob); progress({ progress: 99, phaseKey: "exportSaveFile", phaseParams: { format: "MP4" } });
downloadBlob(mp4, `${name}.mp4`); d.setStatus("done"); d.setStatusText(localize("exportComplete")); await finish(localize("exportComplete")); d.notify(localize("exportComplete"));
} catch (error) {
console.error(error); progress({ progress: 99, phase: "保存 WebM 兜底文件" }); downloadBlob(video.blob, `${name}.webm`);
d.setStatus("done"); d.setStatusText("WebM 兜底已导出"); await finish("WebM 兜底已导出"); d.notify("MP4 转码失败,已导出 WebM 兜底");
}
} catch (error) {
console.error(error); d.setStatus("error"); d.setStatusText(error instanceof Error ? error.message : "视频导出失败"); d.setExportPhase("导出失败");
console.error(error); d.setStatus("error"); d.setStatusText(error instanceof Error ? error.message : localize("exportFailed")); d.setExportPhase(localize("exportFailed"));
} finally { d.setExporting(false); d.setExportProgress(0); }
}, [d]);
}
+4 -1
View File
@@ -10,6 +10,8 @@ export function useVisualTrackState() {
const [imageDuration, setImageDuration] = useState(0);
const [visualSegments, setVisualSegments] = useState([]);
const [selectedVisualSegmentId, setSelectedVisualSegmentId] = useState("");
const [visualOverlaySegments, setVisualOverlaySegments] = useState([]);
const [selectedVisualOverlayId, setSelectedVisualOverlayId] = useState("");
const [selectedFilterId, setSelectedFilterId] = useState("none");
const [selectedTransitionId, setSelectedTransitionId] = useState("none");
const [selectedStickerId, setSelectedStickerId] = useState("none");
@@ -23,6 +25,7 @@ export function useVisualTrackState() {
setImageDuration, setImageMeta, setImageName, setImageSrc, setSelectedFilterId,
setSelectedStickerId, setSelectedStickerSegmentId, setSelectedTransitionId,
setSelectedVisualSegmentId, setStickerSegments, setVisualSegments, setVisualType,
stickerSegments, visualSegments, visualType,
stickerSegments, visualSegments, visualType, visualOverlaySegments,
selectedVisualOverlayId, setVisualOverlaySegments, setSelectedVisualOverlayId,
};
}
+71 -3
View File
@@ -13,6 +13,19 @@ export const APP_LANGUAGES = [
{ id: "vi", name: "Vietnamese", nativeName: "Tiếng Việt", hint: "Vietnamese" },
];
const EXPORT_RENDER_COPY = {
zh: { exportPreparing: "准备导出", exportRecordingStream: "录制 {format} 视频流", exportEmbeddedAudio: "准备视频内嵌音频 {current}/{total}", exportOfflinePreparing: "准备离线渲染", exportOfflineRendering: "离线渲染 {current}/{total}", exportVerifyFile: "验证导出文件", exportPrepareVisuals: "准备导出画面", exportPrepareTracks: "准备画布与轨道", exportMixAudio: "解码并混合音频轨", exportStartRecording: "开始录制视频流", exportRecording: "录制视频流", exportPackageFile: "封装导出文件", exportCompatibility: "切换兼容导出模式", exportSaveFile: "保存 {format} 文件", exportComplete: "导出完成", exportFailed: "导出失败" },
en: { exportPreparing: "Preparing export", exportRecordingStream: "Recording {format} video stream", exportEmbeddedAudio: "Preparing embedded video audio {current}/{total}", exportOfflinePreparing: "Preparing offline render", exportOfflineRendering: "Offline rendering {current}/{total}", exportVerifyFile: "Verifying exported file", exportPrepareVisuals: "Preparing visuals", exportPrepareTracks: "Preparing canvas and tracks", exportMixAudio: "Decoding and mixing audio tracks", exportStartRecording: "Starting video stream recording", exportRecording: "Recording video stream", exportPackageFile: "Packaging export file", exportCompatibility: "Switching to compatibility export", exportSaveFile: "Saving {format} file", exportComplete: "Export complete", exportFailed: "Export failed" },
ja: { exportPreparing: "書き出しを準備中", exportRecordingStream: "{format} 動画ストリームを録画中", exportEmbeddedAudio: "動画内音声を準備中 {current}/{total}", exportOfflinePreparing: "オフラインレンダリングを準備中", exportOfflineRendering: "オフラインレンダリング {current}/{total}", exportVerifyFile: "書き出しファイルを確認中", exportPrepareVisuals: "映像を準備中", exportPrepareTracks: "キャンバスとトラックを準備中", exportMixAudio: "音声トラックをデコード・ミックス中", exportStartRecording: "動画ストリーム録画を開始中", exportRecording: "動画ストリームを録画中", exportPackageFile: "書き出しファイルを作成中", exportCompatibility: "互換書き出しに切り替え中", exportSaveFile: "{format} ファイルを保存中", exportComplete: "書き出し完了", exportFailed: "書き出し失敗" },
ko: { exportPreparing: "내보내기 준비 중", exportRecordingStream: "{format} 비디오 스트림 녹화 중", exportEmbeddedAudio: "비디오 내장 오디오 준비 중 {current}/{total}", exportOfflinePreparing: "오프라인 렌더링 준비 중", exportOfflineRendering: "오프라인 렌더링 {current}/{total}", exportVerifyFile: "내보낸 파일 확인 중", exportPrepareVisuals: "화면 준비 중", exportPrepareTracks: "캔버스와 트랙 준비 중", exportMixAudio: "오디오 트랙 디코딩 및 믹싱 중", exportStartRecording: "비디오 스트림 녹화 시작 중", exportRecording: "비디오 스트림 녹화 중", exportPackageFile: "내보내기 파일 패키징 중", exportCompatibility: "호환 내보내기로 전환 중", exportSaveFile: "{format} 파일 저장 중", exportComplete: "내보내기 완료", exportFailed: "내보내기 실패" },
es: { exportPreparing: "Preparando exportación", exportRecordingStream: "Grabando flujo de vídeo {format}", exportEmbeddedAudio: "Preparando audio integrado {current}/{total}", exportOfflinePreparing: "Preparando renderizado sin conexión", exportOfflineRendering: "Renderizado sin conexión {current}/{total}", exportVerifyFile: "Verificando archivo exportado", exportPrepareVisuals: "Preparando imagen", exportPrepareTracks: "Preparando lienzo y pistas", exportMixAudio: "Decodificando y mezclando audio", exportStartRecording: "Iniciando grabación del flujo", exportRecording: "Grabando flujo de vídeo", exportPackageFile: "Empaquetando archivo exportado", exportCompatibility: "Cambiando a exportación compatible", exportSaveFile: "Guardando archivo {format}", exportComplete: "Exportación completada", exportFailed: "Error de exportación" },
fr: { exportPreparing: "Préparation de l’export", exportRecordingStream: "Enregistrement du flux vidéo {format}", exportEmbeddedAudio: "Préparation de l’audio intégré {current}/{total}", exportOfflinePreparing: "Préparation du rendu hors ligne", exportOfflineRendering: "Rendu hors ligne {current}/{total}", exportVerifyFile: "Vérification du fichier exporté", exportPrepareVisuals: "Préparation des images", exportPrepareTracks: "Préparation du canevas et des pistes", exportMixAudio: "Décodage et mixage audio", exportStartRecording: "Démarrage de l’enregistrement vidéo", exportRecording: "Enregistrement du flux vidéo", exportPackageFile: "Assemblage du fichier exporté", exportCompatibility: "Passage à l’export compatible", exportSaveFile: "Enregistrement du fichier {format}", exportComplete: "Export terminé", exportFailed: "Échec de l’export" },
de: { exportPreparing: "Export wird vorbereitet", exportRecordingStream: "{format}-Videostream wird aufgenommen", exportEmbeddedAudio: "Eingebettetes Audio wird vorbereitet {current}/{total}", exportOfflinePreparing: "Offline-Rendering wird vorbereitet", exportOfflineRendering: "Offline-Rendering {current}/{total}", exportVerifyFile: "Exportdatei wird geprüft", exportPrepareVisuals: "Bildmaterial wird vorbereitet", exportPrepareTracks: "Canvas und Spuren werden vorbereitet", exportMixAudio: "Audiospuren werden dekodiert und gemischt", exportStartRecording: "Videostream-Aufnahme wird gestartet", exportRecording: "Videostream wird aufgenommen", exportPackageFile: "Exportdatei wird verpackt", exportCompatibility: "Kompatibilitätsexport wird verwendet", exportSaveFile: "{format}-Datei wird gespeichert", exportComplete: "Export abgeschlossen", exportFailed: "Export fehlgeschlagen" },
pt: { exportPreparing: "Preparando exportação", exportRecordingStream: "Gravando fluxo de vídeo {format}", exportEmbeddedAudio: "Preparando áudio incorporado {current}/{total}", exportOfflinePreparing: "Preparando renderização offline", exportOfflineRendering: "Renderização offline {current}/{total}", exportVerifyFile: "Verificando arquivo exportado", exportPrepareVisuals: "Preparando imagens", exportPrepareTracks: "Preparando tela e faixas", exportMixAudio: "Decodificando e mixando áudio", exportStartRecording: "Iniciando gravação do vídeo", exportRecording: "Gravando fluxo de vídeo", exportPackageFile: "Empacotando arquivo exportado", exportCompatibility: "Alternando para exportação compatível", exportSaveFile: "Salvando arquivo {format}", exportComplete: "Exportação concluída", exportFailed: "Falha na exportação" },
th: { exportPreparing: "กำลังเตรียมส่งออก", exportRecordingStream: "กำลังบันทึกสตรีมวิดีโอ {format}", exportEmbeddedAudio: "กำลังเตรียมเสียงในวิดีโอ {current}/{total}", exportOfflinePreparing: "กำลังเตรียมเรนเดอร์ออฟไลน์", exportOfflineRendering: "เรนเดอร์ออฟไลน์ {current}/{total}", exportVerifyFile: "กำลังตรวจสอบไฟล์ส่งออก", exportPrepareVisuals: "กำลังเตรียมภาพ", exportPrepareTracks: "กำลังเตรียมแคนวาสและแทร็ก", exportMixAudio: "กำลังถอดรหัสและผสมเสียง", exportStartRecording: "กำลังเริ่มบันทึกวิดีโอ", exportRecording: "กำลังบันทึกสตรีมวิดีโอ", exportPackageFile: "กำลังจัดแพ็กไฟล์ส่งออก", exportCompatibility: "กำลังสลับเป็นโหมดส่งออกที่เข้ากันได้", exportSaveFile: "กำลังบันทึกไฟล์ {format}", exportComplete: "ส่งออกเสร็จแล้ว", exportFailed: "ส่งออกไม่สำเร็จ" },
vi: { exportPreparing: "Đang chuẩn bị xuất", exportRecordingStream: "Đang ghi luồng video {format}", exportEmbeddedAudio: "Đang chuẩn bị âm thanh nhúng {current}/{total}", exportOfflinePreparing: "Đang chuẩn bị kết xuất ngoại tuyến", exportOfflineRendering: "Kết xuất ngoại tuyến {current}/{total}", exportVerifyFile: "Đang xác minh tệp xuất", exportPrepareVisuals: "Đang chuẩn bị hình ảnh", exportPrepareTracks: "Đang chuẩn bị khung vẽ và rãnh", exportMixAudio: "Đang giải mã và trộn âm thanh", exportStartRecording: "Đang bắt đầu ghi video", exportRecording: "Đang ghi luồng video", exportPackageFile: "Đang đóng gói tệp xuất", exportCompatibility: "Đang chuyển sang xuất tương thích", exportSaveFile: "Đang lưu tệp {format}", exportComplete: "Xuất hoàn tất", exportFailed: "Xuất thất bại" },
};
const VISUAL_EDITOR_COPY = {
zh: { visualSelectClip: "请先选择 Visuals 轨上的片段", visualKeyframes: "关键帧", visualFrames: "帧", visualScale: "缩放", visualPositionX: "水平位置", visualPositionY: "垂直位置", visualRotation: "旋转", visualOpacity: "不透明度", visualDeleteKeyframe: "删除当前位置关键帧", visualMask: "蒙版", visualMaskResize: "调整蒙版大小", visualClipScoped: "片段级", visualMaskNone: "无", visualMaskRectangle: "矩形", visualMaskRounded: "圆角", visualMaskCircle: "圆形", visualFeather: "羽化", visualHorizontal: "水平", visualVertical: "垂直", visualWidth: "宽度", visualHeight: "高度", visualDiameter: "直径", visualCornerRadius: "圆角半径", visualMaskNoneHint: "选择一种蒙版后显示对应参数", visualInvertMask: "反向蒙版", visualEffects: "画面效果" },
en: { visualSelectClip: "Select a clip on the Visuals track", visualKeyframes: "Keyframes", visualFrames: "frames", visualScale: "Scale", visualPositionX: "Horizontal position", visualPositionY: "Vertical position", visualRotation: "Rotation", visualOpacity: "Opacity", visualDeleteKeyframe: "Delete keyframe at playhead", visualMask: "Mask", visualMaskResize: "Resize mask", visualClipScoped: "Clip", visualMaskNone: "None", visualMaskRectangle: "Rectangle", visualMaskRounded: "Rounded", visualMaskCircle: "Circle", visualFeather: "Feather", visualHorizontal: "Horizontal", visualVertical: "Vertical", visualWidth: "Width", visualHeight: "Height", visualDiameter: "Diameter", visualCornerRadius: "Corner radius", visualMaskNoneHint: "Choose a mask to show its parameters", visualInvertMask: "Invert mask", visualEffects: "Visual effects" },
@@ -199,6 +212,23 @@ const CONTEXT_PANEL_COPY = {
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 TIMELINE_AUDIO_MENU_COPY = {
zh: { muteClip: "静音", unmuteClip: "取消静音", separateSourceAudio: "分离音频", separatingSourceAudio: "正在分离音频…" },
en: { muteClip: "Mute", unmuteClip: "Unmute", separateSourceAudio: "Separate audio", separatingSourceAudio: "Separating audio…" },
ja: { muteClip: "ミュート", unmuteClip: "ミュート解除", separateSourceAudio: "音声を分離", separatingSourceAudio: "音声を分離中…" },
ko: { muteClip: "음소거", unmuteClip: "음소거 해제", separateSourceAudio: "오디오 분리", separatingSourceAudio: "오디오 분리 중…" },
es: { muteClip: "Silenciar", unmuteClip: "Activar sonido", separateSourceAudio: "Separar audio", separatingSourceAudio: "Separando audio…" },
fr: { muteClip: "Couper le son", unmuteClip: "Rétablir le son", separateSourceAudio: "Séparer l’audio", separatingSourceAudio: "Séparation audio…" },
de: { muteClip: "Stummschalten", unmuteClip: "Ton einschalten", separateSourceAudio: "Audio trennen", separatingSourceAudio: "Audio wird getrennt…" },
pt: { muteClip: "Silenciar", unmuteClip: "Ativar som", separateSourceAudio: "Separar áudio", separatingSourceAudio: "Separando áudio…" },
th: { muteClip: "ปิดเสียง", unmuteClip: "เปิดเสียง", separateSourceAudio: "แยกเสียง", separatingSourceAudio: "กำลังแยกเสียง…" },
vi: { muteClip: "Tắt tiếng", unmuteClip: "Bật tiếng", separateSourceAudio: "Tách âm thanh", separatingSourceAudio: "Đang tách âm thanh…" },
};
Object.entries(TIMELINE_AUDIO_MENU_COPY).forEach(([language, copy]) => {
Object.assign(CONTEXT_PANEL_COPY[language], copy);
});
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" },
@@ -299,6 +329,19 @@ const IMAGE_AI_CAPTION_COPY = {
en: { generateImageAiCaption: "Generate AI voiceover caption", generatingImageAiCaption: "Generating AI caption…", imageAiCaptionAdded: "AI voiceover caption added to the timeline", imageAiCaptionFailed: "Could not generate an image voiceover caption" },
};
const PICTURE_IN_PICTURE_COPY = {
zh: { pictureInPicture: "画中画", overlayTrack: "画中画", dropAsOverlay: "作为画中画", appendAfter: "添加到后面", dropSlot: "放置位置", layoutPresets: "布局预设", moveLayerUp: "上移一层", moveLayerDown: "下移一层" },
en: { pictureInPicture: "Picture in picture", overlayTrack: "Overlay", dropAsOverlay: "Add as picture in picture", appendAfter: "Append to sequence", dropSlot: "Drop position", layoutPresets: "Layout presets", moveLayerUp: "Move layer up", moveLayerDown: "Move layer down" },
ja: { pictureInPicture: "ピクチャーインピクチャー", overlayTrack: "オーバーレイ", dropAsOverlay: "ワイプとして追加", appendAfter: "後ろに追加", dropSlot: "配置位置", layoutPresets: "レイアウトプリセット", moveLayerUp: "レイヤーを上へ", moveLayerDown: "レイヤーを下へ" },
ko: { pictureInPicture: "화면 속 화면", overlayTrack: "오버레이", dropAsOverlay: "오버레이로 추가", appendAfter: "뒤에 추가", dropSlot: "놓을 위치", layoutPresets: "레이아웃 프리셋", moveLayerUp: "레이어 올리기", moveLayerDown: "레이어 내리기" },
es: { pictureInPicture: "Imagen en imagen", overlayTrack: "Superposición", dropAsOverlay: "Añadir como superposición", appendAfter: "Añadir al final", dropSlot: "Posición de destino", layoutPresets: "Diseños predefinidos", moveLayerUp: "Subir capa", moveLayerDown: "Bajar capa" },
fr: { pictureInPicture: "Image dans l’image", overlayTrack: "Incrustation", dropAsOverlay: "Ajouter en incrustation", appendAfter: "Ajouter à la suite", dropSlot: "Position de dépôt", layoutPresets: "Préréglages de disposition", moveLayerUp: "Monter le calque", moveLayerDown: "Descendre le calque" },
de: { pictureInPicture: "Bild-in-Bild", overlayTrack: "Overlay", dropAsOverlay: "Als Überlagerung hinzufügen", appendAfter: "Hinten anfügen", dropSlot: "Ablageposition", layoutPresets: "Layout-Vorlagen", moveLayerUp: "Ebene nach oben", moveLayerDown: "Ebene nach unten" },
pt: { pictureInPicture: "Picture-in-picture", overlayTrack: "Sobreposição", dropAsOverlay: "Adicionar como sobreposição", appendAfter: "Adicionar ao final", dropSlot: "Posição de destino", layoutPresets: "Predefinições de layout", moveLayerUp: "Subir camada", moveLayerDown: "Descer camada" },
th: { pictureInPicture: "ภาพซ้อนภาพ", overlayTrack: "ภาพซ้อน", dropAsOverlay: "เพิ่มเป็นภาพซ้อน", appendAfter: "เพิ่มต่อท้าย", dropSlot: "ตำแหน่งวาง", layoutPresets: "รูปแบบสำเร็จรูป", moveLayerUp: "เลื่อนเลเยอร์ขึ้น", moveLayerDown: "เลื่อนเลเยอร์ลง" },
vi: { pictureInPicture: "Hình trong hình", overlayTrack: "Lớp phủ", dropAsOverlay: "Thêm làm lớp phủ", appendAfter: "Thêm vào cuối", dropSlot: "Vị trí thả", layoutPresets: "Bố cục mẫu", moveLayerUp: "Đưa lớp lên", moveLayerDown: "Đưa lớp xuống" },
};
export const UI_COPY = {
zh: {
...SMART_WORKSPACE_COPY.zh,
@@ -309,6 +352,7 @@ export const UI_COPY = {
...AUTO_EDIT_SEGMENT_COPY.zh,
...AUTO_EDIT_RESULT_COPY.zh,
...IMAGE_AI_CAPTION_COPY.zh,
...PICTURE_IN_PICTURE_COPY.zh,
...VISUAL_EDITOR_COPY.zh,
...TRANSITION_EDITOR_COPY.zh,
...VISUAL_ANIMATION_COPY.zh,
@@ -390,7 +434,10 @@ export const UI_COPY = {
currentMediaAlt: "当前上传素材预览",
fit: "适合",
cover: "填充",
fullscreenPreview: "全屏预览",
fullscreenPreview: "大画布预览与编辑",
focusPreviewTitle: "大画布编辑",
focusPreviewHint: "点击画面元素进行移动、缩放和旋转",
closeFocusPreview: "关闭大画布预览",
backTwoSeconds: "后退 2 秒",
forwardTwoSeconds: "前进 2 秒",
deleteTrack: "删除选中轨道",
@@ -689,6 +736,7 @@ export const UI_COPY = {
...AUTO_EDIT_SEGMENT_COPY.en,
...AUTO_EDIT_RESULT_COPY.en,
...IMAGE_AI_CAPTION_COPY.en,
...PICTURE_IN_PICTURE_COPY.en,
...VISUAL_EDITOR_COPY.en,
...TRANSITION_EDITOR_COPY.en,
...VISUAL_ANIMATION_COPY.en,
@@ -770,7 +818,10 @@ export const UI_COPY = {
currentMediaAlt: "Current uploaded media preview",
fit: "Fit",
cover: "Fill",
fullscreenPreview: "Fullscreen preview",
fullscreenPreview: "Large canvas preview and edit",
focusPreviewTitle: "Large canvas editor",
focusPreviewHint: "Select an element to move, resize, or rotate it",
closeFocusPreview: "Close large canvas preview",
backTwoSeconds: "Back 2 seconds",
forwardTwoSeconds: "Forward 2 seconds",
deleteTrack: "Delete selected track",
@@ -1061,6 +1112,7 @@ export const UI_COPY = {
dropMusicHere: "Drop on music track",
},
ja: {
...PICTURE_IN_PICTURE_COPY.ja,
...SMART_WORKSPACE_COPY.ja,
...VISUAL_EDITOR_COPY.ja,
...TRANSITION_EDITOR_COPY.ja,
@@ -1081,6 +1133,7 @@ export const UI_COPY = {
...TTS_BACKEND_COPY.ja,
...CAPTION_WORKSPACE_COPY.ja,
...RESOURCE_LINK_COPY.ja,
...PICTURE_IN_PICTURE_COPY.ja,
languageTitle: "表示言語を選択",
languageSubtitle: "一度保存すると、次回からこの言語で開きます。",
languageSaved: "あとで設定から変更できます",
@@ -1143,6 +1196,7 @@ export const UI_COPY = {
Object.assign(UI_COPY, {
ko: {
...PICTURE_IN_PICTURE_COPY.ko,
...SMART_WORKSPACE_COPY.ko,
...VISUAL_EDITOR_COPY.ko,
...TRANSITION_EDITOR_COPY.ko,
@@ -1166,6 +1220,7 @@ Object.assign(UI_COPY, {
...TTS_BACKEND_COPY.ko,
...CAPTION_WORKSPACE_COPY.ko,
...RESOURCE_LINK_COPY.ko,
...PICTURE_IN_PICTURE_COPY.ko,
languageTitle: "인터페이스 언어 선택",
languageSubtitle: "한 번 저장하면 다음부터 이 언어로 열립니다.",
languageSaved: "나중에 설정에서 변경할 수 있습니다",
@@ -1206,6 +1261,7 @@ Object.assign(UI_COPY, {
musicTrack: "배경 음악",
},
es: {
...PICTURE_IN_PICTURE_COPY.es,
...SMART_WORKSPACE_COPY.es,
...UI_COPY.en,
...VISUAL_EDITOR_COPY.es,
@@ -1227,6 +1283,7 @@ Object.assign(UI_COPY, {
...TTS_BACKEND_COPY.es,
...CAPTION_WORKSPACE_COPY.es,
...RESOURCE_LINK_COPY.es,
...PICTURE_IN_PICTURE_COPY.es,
languageTitle: "Elige el idioma",
languageSubtitle: "Se guarda una vez y se abrirá así la próxima vez.",
languageSaved: "Puedes cambiarlo luego en Ajustes",
@@ -1267,6 +1324,7 @@ Object.assign(UI_COPY, {
musicTrack: "Música",
},
fr: {
...PICTURE_IN_PICTURE_COPY.fr,
...SMART_WORKSPACE_COPY.fr,
...UI_COPY.en,
...VISUAL_EDITOR_COPY.fr,
@@ -1288,6 +1346,7 @@ Object.assign(UI_COPY, {
...TTS_BACKEND_COPY.fr,
...CAPTION_WORKSPACE_COPY.fr,
...RESOURCE_LINK_COPY.fr,
...PICTURE_IN_PICTURE_COPY.fr,
languageTitle: "Choisir la langue",
languageSubtitle: "Enregistrée une fois, elle sera utilisée à la prochaine ouverture.",
languageSaved: "Modifiable plus tard dans les réglages",
@@ -1328,6 +1387,7 @@ Object.assign(UI_COPY, {
musicTrack: "Musique",
},
de: {
...PICTURE_IN_PICTURE_COPY.de,
...SMART_WORKSPACE_COPY.de,
...UI_COPY.en,
...VISUAL_EDITOR_COPY.de,
@@ -1349,6 +1409,7 @@ Object.assign(UI_COPY, {
...TTS_BACKEND_COPY.de,
...CAPTION_WORKSPACE_COPY.de,
...RESOURCE_LINK_COPY.de,
...PICTURE_IN_PICTURE_COPY.de,
languageTitle: "Sprache wählen",
languageSubtitle: "Einmal gespeichert, startet der Editor künftig in dieser Sprache.",
languageSaved: "Später in den Einstellungen änderbar",
@@ -1389,6 +1450,7 @@ Object.assign(UI_COPY, {
musicTrack: "Musik",
},
pt: {
...PICTURE_IN_PICTURE_COPY.pt,
...SMART_WORKSPACE_COPY.pt,
...UI_COPY.en,
...VISUAL_EDITOR_COPY.pt,
@@ -1410,6 +1472,7 @@ Object.assign(UI_COPY, {
...TTS_BACKEND_COPY.pt,
...CAPTION_WORKSPACE_COPY.pt,
...RESOURCE_LINK_COPY.pt,
...PICTURE_IN_PICTURE_COPY.pt,
languageTitle: "Escolha o idioma",
languageSubtitle: "Salvo uma vez, o editor abrirá nesse idioma depois.",
languageSaved: "Você pode alterar em Configurações",
@@ -1450,6 +1513,7 @@ Object.assign(UI_COPY, {
musicTrack: "Música",
},
th: {
...PICTURE_IN_PICTURE_COPY.th,
...SMART_WORKSPACE_COPY.th,
...UI_COPY.en,
...VISUAL_EDITOR_COPY.th,
@@ -1471,6 +1535,7 @@ Object.assign(UI_COPY, {
...TTS_BACKEND_COPY.th,
...CAPTION_WORKSPACE_COPY.th,
...RESOURCE_LINK_COPY.th,
...PICTURE_IN_PICTURE_COPY.th,
languageTitle: "เลือกภาษาอินเทอร์เฟซ",
languageSubtitle: "บันทึกครั้งเดียว ครั้งถัดไปจะเปิดด้วยภาษานี้",
languageSaved: "เปลี่ยนได้ภายหลังใน Settings",
@@ -1511,6 +1576,7 @@ Object.assign(UI_COPY, {
musicTrack: "เพลง",
},
vi: {
...PICTURE_IN_PICTURE_COPY.vi,
...SMART_WORKSPACE_COPY.vi,
...UI_COPY.en,
...VISUAL_EDITOR_COPY.vi,
@@ -1532,6 +1598,7 @@ Object.assign(UI_COPY, {
...TTS_BACKEND_COPY.vi,
...CAPTION_WORKSPACE_COPY.vi,
...RESOURCE_LINK_COPY.vi,
...PICTURE_IN_PICTURE_COPY.vi,
languageTitle: "Chọn ngôn ngữ giao diện",
languageSubtitle: "Lưu một lần, lần sau sẽ mở bằng ngôn ngữ này.",
languageSaved: "Có thể đổi lại trong Cài đặt",
@@ -1670,7 +1737,8 @@ export function createTranslator(languageId) {
const copyLanguage = getCopyLanguage(languageId);
const copy = UI_COPY[copyLanguage] ?? UI_COPY.en;
const fallback = UI_COPY.en;
return (key, fallbackText) => copy[key] ?? fallback[key] ?? UI_COPY.zh[key] ?? fallbackText ?? key;
const exportCopy = EXPORT_RENDER_COPY[copyLanguage] ?? EXPORT_RENDER_COPY.en;
return (key, fallbackText) => exportCopy[key] ?? EXPORT_RENDER_COPY.en[key] ?? copy[key] ?? fallback[key] ?? UI_COPY.zh[key] ?? fallbackText ?? key;
}
export function translateOptionName(languageId, name) {
+21
View File
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";
import { APP_LANGUAGES, createTranslator } from "./i18n.js";
describe("export rendering translations", () => {
it("provides localized offline-render phases for every supported interface language", () => {
const keys = [
"exportPreparing", "exportRecordingStream", "exportEmbeddedAudio", "exportOfflinePreparing",
"exportOfflineRendering", "exportVerifyFile", "exportPrepareVisuals", "exportPrepareTracks",
"exportMixAudio", "exportStartRecording", "exportRecording", "exportPackageFile",
"exportCompatibility", "exportSaveFile", "exportComplete", "exportFailed",
];
APP_LANGUAGES.forEach(({ id }) => {
const t = createTranslator(id);
keys.forEach((key) => expect(t(key)).not.toBe(key));
expect(t("exportOfflineRendering")).toContain("{current}");
expect(t("exportOfflineRendering")).toContain("{total}");
expect(t("exportComplete")).not.toBe("exportComplete");
expect(t("exportFailed")).not.toBe("exportFailed");
});
});
});
+20
View File
@@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import { APP_LANGUAGES, createTranslator } from "./i18n.js";
describe("timeline audio context-menu translations", () => {
it("provides localized mute and separate-audio labels for every interface language", () => {
APP_LANGUAGES.forEach(({ id }) => {
const t = createTranslator(id);
expect(t("muteClip")).not.toBe("muteClip");
expect(t("unmuteClip")).not.toBe("unmuteClip");
expect(t("separateSourceAudio")).not.toBe("separateSourceAudio");
});
});
it("uses English labels in the English context menu", () => {
const t = createTranslator("en");
expect(t("muteClip")).toBe("Mute");
expect(t("unmuteClip")).toBe("Unmute");
expect(t("separateSourceAudio")).toBe("Separate audio");
});
});
+17 -7
View File
@@ -1,5 +1,9 @@
import { ASSET_DRAG_MIME, STICKERS } from "../config/editor.js";
export function resolveVisualDropIntent({ track = "image" } = {}) {
return track === "overlay" ? "overlay" : "image";
}
export function createAssetDragControls(deps) {
const findAssetById = (id) => {
if (!id) return null;
@@ -11,7 +15,7 @@ export function createAssetDragControls(deps) {
const getTimelineDropPercent = (clientX, rect) => rect?.width ? Math.max(8, Math.min(92, ((clientX - rect.left) / rect.width) * 100)) : 50;
const canDropAssetOnTrack = (asset, track) => {
if (!asset || deps.trackLocks[track]) return false;
if (track === "image") return asset.type === "image" || asset.type === "video";
if (track === "image" || track === "overlay") return asset.type === "image" || asset.type === "video";
if (track === "sticker") return asset.type === "sticker";
if (track === "audio" || track === "music") return asset.type === "audio";
return track === "source" && asset.type === "video";
@@ -33,9 +37,15 @@ export function createAssetDragControls(deps) {
return { track: "sticker", percent: getTimelineDropPercent(clientX, rect) };
}
const trackElement = element.closest("[data-asset-drop-track]");
const track = trackElement?.dataset.assetDropTrack ?? "";
return !track || !(trackElement instanceof HTMLElement) ? { track, percent: 50 }
: { track, percent: getTimelineDropPercent(clientX, trackElement.getBoundingClientRect()) };
let track = trackElement?.dataset.assetDropTrack ?? "";
const startTime = trackElement instanceof HTMLElement && Number.isFinite(Number(trackElement.dataset.dropStartTime))
? Number(trackElement.dataset.dropStartTime)
: undefined;
const layer = trackElement instanceof HTMLElement && Number.isFinite(Number(trackElement.dataset.dropLayer))
? Number(trackElement.dataset.dropLayer)
: undefined;
return !track || !(trackElement instanceof HTMLElement) ? { track, percent: 50, startTime, layer }
: { track, percent: getTimelineDropPercent(clientX, trackElement.getBoundingClientRect()), startTime, layer };
};
const triggerAssetDropPulse = (track) => {
if (!track) return;
@@ -67,14 +77,13 @@ export function createAssetDragControls(deps) {
if (!state?.dragging) return;
deps.suppressAssetClickRef.current = state.assetId; setTimeout(() => { if (deps.suppressAssetClickRef.current === state.assetId) deps.suppressAssetClickRef.current = ""; }, 300);
const dragged = findAssetById(state.assetId); const track = dragged?.type === "sticker" && info.track ? "sticker" : info.track;
if (canDropAssetOnTrack(dragged, track)) { triggerAssetDropPulse(track); void deps.applyAssetToTrack(dragged, track, { percent: info.percent }); }
if (canDropAssetOnTrack(dragged, track)) { triggerAssetDropPulse(track); void deps.applyAssetToTrack(dragged, track, { percent: info.percent, startTime: info.startTime, layer: info.layer }); }
};
addEventListener("pointermove", move, { passive: false }); addEventListener("pointerup", up); addEventListener("pointercancel", cleanup);
};
const handleAssetClick = (event, asset) => {
if (deps.suppressAssetClickRef.current === asset.id) { deps.suppressAssetClickRef.current = ""; event.preventDefault(); event.stopPropagation(); return; }
deps.setSelectedLibraryAssetId(asset.id);
if (event.detail >= 2) return void deps.applyAssetToTrack(asset, asset.type === "audio" ? "music" : "image");
deps.notify("素材已选中,请拖到对应轨道使用");
};
const handleStickerClick = (event, sticker) => {
@@ -83,7 +92,8 @@ export function createAssetDragControls(deps) {
deps.addStickerAssetToTimeline(sticker, { startTime: deps.currentTime });
};
const handleTrackAssetDragOver = (event, track) => {
const asset = getDraggedAsset(event); const target = asset?.type === "sticker" ? "sticker" : track;
const asset = getDraggedAsset(event);
let target = asset?.type === "sticker" ? "sticker" : track;
if (!canDropAssetOnTrack(asset, target)) return;
event.preventDefault(); event.dataTransfer.dropEffect = "copy";
const rect = target === "sticker" ? deps.trackScrollRef.current?.getBoundingClientRect() ?? event.currentTarget.getBoundingClientRect() : event.currentTarget.getBoundingClientRect();
+9
View File
@@ -0,0 +1,9 @@
import { describe, expect, it } from "vitest";
import { resolveVisualDropIntent } from "./assetDragControls.js";
describe("visual asset drop intent", () => {
it("uses the explicit target track instead of guessing from pointer position", () => {
expect(resolveVisualDropIntent({ track: "image" })).toBe("image");
expect(resolveVisualDropIntent({ track: "overlay" })).toBe("overlay");
});
});
+8 -2
View File
@@ -15,6 +15,10 @@ export function createAssetDropActions(d) {
d.appendVisualAssetToTimeline(asset);
return;
}
if (track === "overlay") {
d.addVisualOverlay?.(asset, options);
return;
}
if (track === "music") {
await d.selectAsset(asset);
return;
@@ -42,7 +46,7 @@ export function createAssetDropActions(d) {
function handleTrackAssetDrop(event, track) {
const asset = d.getDraggedAsset(event);
const targetTrack = asset?.type === "sticker" ? "sticker" : track;
let targetTrack = asset?.type === "sticker" ? "sticker" : track;
if (!d.canDropAssetOnTrack(asset, targetTrack)) return;
event.preventDefault();
event.stopPropagation();
@@ -56,7 +60,9 @@ export function createAssetDropActions(d) {
d.setAssetDropTargetTrack("");
d.setAssetDropPosition({ track: "", percent: 50 });
d.triggerAssetDropPulse(targetTrack);
void applyAssetToTrack(asset, targetTrack, { percent });
const startTime = Number.isFinite(Number(event.currentTarget.dataset.dropStartTime)) ? Number(event.currentTarget.dataset.dropStartTime) : undefined;
const layer = Number.isFinite(Number(event.currentTarget.dataset.dropLayer)) ? Number(event.currentTarget.dataset.dropLayer) : undefined;
void applyAssetToTrack(asset, targetTrack, { percent, startTime, layer });
}
function handleVisualStyleDrop(event) {
-1
View File
@@ -10,7 +10,6 @@ export function createAssetLibraryActions(deps) {
}
deps.replaceVisualTimeline(asset, deps.getVisualDurationForAsset(asset));
deps.notify(`${asset.type === "video" ? "视频" : "图片"}素材已应用到预览和时间线`);
if (asset.type === "video") deps.extractVideoSourceAudio(asset);
}
function deleteUserAsset(asset) {
+20
View File
@@ -0,0 +1,20 @@
import { describe, expect, it, vi } from "vitest";
import { createAssetLibraryActions } from "./assetLibraryActions.js";
describe("asset library visual selection", () => {
it("does not extract video audio until the user requests it from the clip menu", async () => {
const video = { id: "video-1", type: "video", src: "blob:video", duration: 8 };
const deps = {
replaceVisualTimeline: vi.fn(),
getVisualDurationForAsset: vi.fn(() => 8),
extractVideoSourceAudio: vi.fn(),
notify: vi.fn(),
};
const { selectAsset } = createAssetLibraryActions(deps);
await selectAsset(video);
expect(deps.replaceVisualTimeline).toHaveBeenCalledWith(video, 8);
expect(deps.extractVideoSourceAudio).not.toHaveBeenCalled();
});
});
+34 -6
View File
@@ -1,10 +1,37 @@
import { makeId } from "./timeline.js";
export const BUILT_IN_AI_LANGUAGES = new Set(["en", "es", "ja", "de", "fr"]);
const AUTO_EDIT_LANGUAGE_TAGS = {
zh: "zh-CN",
en: "en",
ja: "ja",
ko: "ko",
es: "es",
fr: "fr",
de: "de",
pt: "pt-BR",
th: "th",
vi: "vi",
};
const AUTO_EDIT_LANGUAGE_NAMES = {
"zh-CN": "Simplified Chinese",
en: "English",
ja: "Japanese",
ko: "Korean",
es: "Spanish",
fr: "French",
de: "German",
"pt-BR": "Brazilian Portuguese",
th: "Thai",
vi: "Vietnamese",
};
export function getAutoEditLanguage(language = "en") {
const normalized = language === "pt" ? "pt-BR" : language;
return BUILT_IN_AI_LANGUAGES.has(normalized) ? normalized : "en";
return AUTO_EDIT_LANGUAGE_TAGS[language] || language || "en";
}
function getAutoEditLanguageName(language) {
return AUTO_EDIT_LANGUAGE_NAMES[language] || language;
}
export async function probeBuiltInAI(language = "en") {
@@ -248,7 +275,7 @@ export async function generateImageVoiceoverText({ src, language = "en", signal
additionalProperties: false,
};
const result = await session.prompt([{ role: "user", content: [
{ type: "text", value: `Write one concise, natural voiceover narration sentence in ${modelLanguage} describing only the visible content of this image. Do not invent names, identities, locations, or unseen events. Do not use labels, markdown, or quotation marks.` },
{ type: "text", value: `Write one concise, natural voiceover narration sentence in ${getAutoEditLanguageName(modelLanguage)} describing only the visible content of this image. Do not invent names, identities, locations, or unseen events. Do not use labels, markdown, or quotation marks.` },
{ type: "image", value: image },
] }], { responseConstraint: schema, signal });
const text = String(JSON.parse(result)?.text || "").trim();
@@ -260,7 +287,8 @@ export async function generateImageVoiceoverText({ src, language = "en", signal
}
async function generateCaptionGroup(session, frames, duration, modelLanguage) {
const content = [{ type: "text", value: `Describe every provided candidate frame with one concise on-screen caption. Output in ${modelLanguage}. Return exactly ${frames.length} captions in the same order as the images. Use only visible evidence; do not invent names or facts. Frame timestamps: ${frames.map((frame) => frame.time.toFixed(2)).join(", ")} seconds.` }];
const outputLanguage = getAutoEditLanguageName(modelLanguage);
const content = [{ type: "text", value: `Describe every provided candidate frame with one concise on-screen caption. Output only in ${outputLanguage}. Return exactly ${frames.length} captions in the same order as the images. Use only visible evidence; do not invent names or facts. Frame timestamps: ${frames.map((frame) => frame.time.toFixed(2)).join(", ")} seconds.` }];
frames.forEach((frame) => content.push({ type: "image", value: frame.blob }));
const schema = { type: "object", properties: { captions: { type: "array", minItems: frames.length, maxItems: frames.length, items: { type: "object", properties: { text: { type: "string", minLength: 1 } }, required: ["text"], additionalProperties: false } } }, required: ["captions"], additionalProperties: false };
const response = await session.prompt([{ role: "user", content }], { responseConstraint: schema });
@@ -271,7 +299,7 @@ async function generateCaptionGroup(session, frames, duration, modelLanguage) {
if (descriptions[index]) continue;
const frame = frames[index];
const singleResponse = await session.prompt([{ role: "user", content: [
{ type: "text", value: `Write one concise ${modelLanguage} on-screen caption describing only what is visibly happening in this video frame at ${frame.time.toFixed(2)} seconds. Return a meaningful non-empty caption. Do not mention the timestamp.` },
{ type: "text", value: `Write one concise on-screen caption in ${outputLanguage} describing only what is visibly happening in this video frame at ${frame.time.toFixed(2)} seconds. Return a meaningful non-empty caption. Do not mention the timestamp.` },
{ type: "image", value: frame.blob },
] }], { responseConstraint: singleSchema });
descriptions[index] = String(JSON.parse(singleResponse)?.text || "").trim();
+5 -1
View File
@@ -32,7 +32,11 @@ describe("auto edit", () => {
];
expect(selectChangedFrames(frames, { maxFrames: 3 }).map((frame) => frame.time)).toEqual([0, 2, 5]);
});
it("falls back to an officially supported output language", () => expect(getAutoEditLanguage("zh")).toBe("en"));
it("uses the language selected by the user", () => {
expect(getAutoEditLanguage("zh")).toBe("zh-CN");
expect(getAutoEditLanguage("pt")).toBe("pt-BR");
expect(getAutoEditLanguage("ko")).toBe("ko");
});
it("labels common source aspect ratios", () => {
expect(getAspectRatioLabel(1080, 1920)).toBe("9:16");
expect(getAspectRatioLabel(1920, 1080)).toBe("16:9");
+34 -3
View File
@@ -6,6 +6,23 @@ export function setCaptionSegmentPlacement(segments, segmentId, placement) {
));
}
export function snapCaptionPlacement(x, y, thresholdX, thresholdY) {
const closest = (value, anchors, threshold) => {
const anchor = anchors.reduce((best, item) => (
Math.abs(item - value) < Math.abs(best - value) ? item : best
));
return Math.abs(anchor - value) <= threshold ? anchor : null;
};
const guideX = closest(x, [50], thresholdX);
const guideY = closest(y, [18, 50, 78], thresholdY);
return {
x: guideX ?? x,
y: guideY ?? y,
guideX,
guideY,
};
}
export function createCaptionEditingActions(d) {
function updateScript(nextScript) {
d.setScript(nextScript);
@@ -81,10 +98,21 @@ export function createCaptionEditingActions(d) {
if (segmentId) d.setSelectedSegmentId(segmentId);
const applyPlacement = (clientX, clientY) => {
const rect = d.previewCanvasRef.current?.getBoundingClientRect();
const frame = d.previewCanvasRef.current;
const rect = frame?.getBoundingClientRect();
if (!rect) return;
const x = Math.max(10, Math.min(90, ((clientX - rect.left) / rect.width) * 100));
const y = Math.max(10, Math.min(90, ((clientY - rect.top) / rect.height) * 100));
const rawX = Math.max(10, Math.min(90, ((clientX - rect.left) / rect.width) * 100));
const rawY = Math.max(10, Math.min(90, ((clientY - rect.top) / rect.height) * 100));
const { x, y, guideX, guideY } = snapCaptionPlacement(
rawX,
rawY,
(9 / Math.max(1, rect.width)) * 100,
(9 / Math.max(1, rect.height)) * 100,
);
frame.style.setProperty("--caption-guide-x", `${guideX ?? 50}%`);
frame.style.setProperty("--caption-guide-y", `${guideY ?? 50}%`);
frame.toggleAttribute("data-caption-guide-x", guideX !== null);
frame.toggleAttribute("data-caption-guide-y", guideY !== null);
if (segmentId) {
d.setCaptionSegments((items) => setCaptionSegmentPlacement(items, segmentId, { x, y }));
} else {
@@ -98,6 +126,9 @@ export function createCaptionEditingActions(d) {
const handlePointerUp = () => {
window.removeEventListener("pointermove", handlePointerMove);
window.removeEventListener("pointerup", handlePointerUp);
const frame = d.previewCanvasRef.current;
frame?.removeAttribute("data-caption-guide-x");
frame?.removeAttribute("data-caption-guide-y");
d.notify(disabledSmartAvoidance
? "字幕位置已手动调整,智能避让已关闭"
: "字幕位置已调整");
+11 -13
View File
@@ -1,19 +1,17 @@
import { describe, expect, it } from "vitest";
import { setCaptionSegmentPlacement } from "./captionEditingActions.js";
import { snapCaptionPlacement } from "./captionEditingActions.js";
describe("caption canvas placement", () => {
it("moves only the caption selected on the preview canvas", () => {
const source = [
{ id: "first", text: "First", placement: { x: 30, y: 40 } },
{ id: "second", text: "Second", placement: { x: 60, y: 70 } },
];
const result = setCaptionSegmentPlacement(source, "first", { x: 45, y: 55 });
expect(result[0].placement).toEqual({ x: 45, y: 55 });
expect(result[1]).toBe(source[1]);
expect(source[0].placement).toEqual({ x: 30, y: 40 });
describe("caption canvas snapping", () => {
it("snaps captions to the horizontal center and bottom safe position", () => {
expect(snapCaptionPlacement(49.2, 77.4, 1, 1)).toEqual({
x: 50, y: 78, guideX: 50, guideY: 78,
});
});
it("keeps freely placed captions outside the snap threshold", () => {
expect(snapCaptionPlacement(42, 63, 1, 1)).toEqual({
x: 42, y: 63, guideX: null, guideY: null,
});
});
});
+5 -1
View File
@@ -1,9 +1,13 @@
import { RATIO_OPTIONS } from "../config/editor.js";
export const PLAYBACK_UI_FRAME_MS = 50;
export const PLAYBACK_UI_FRAME_MS = 80;
export const DEFAULT_VISION_OPTIONS = Object.freeze({ showDetections: true, removeBackground: false, avoidCaptions: true, smartCrop: true });
export const EMPTY_VISION_OPTIONS = Object.freeze({ showDetections: false, removeBackground: false, avoidCaptions: false, smartCrop: false });
export function shouldCorrectPreviewMediaTime({ isPlaying, currentTime, targetTime, threshold = 0.04 }) {
return !isPlaying && Number.isFinite(targetTime) && Math.abs((Number(currentTime) || 0) - targetTime) > threshold;
}
export function getAudioSegmentPreviewVolume(segment, timelineTime) {
const volume = Math.max(0, Math.min(1, segment.volume ?? 1));
const localTime = Math.max(0, Math.min(segment.duration, timelineTime - segment.start));
+13
View File
@@ -0,0 +1,13 @@
import { describe, expect, it } from "vitest";
import { shouldCorrectPreviewMediaTime } from "./editorRuntime.js";
describe("preview media clock", () => {
it("never seeks a natively playing video to chase React timeline state", () => {
expect(shouldCorrectPreviewMediaTime({ isPlaying: true, currentTime: 4.8, targetTime: 4.1 })).toBe(false);
});
it("seeks precisely while paused and ignores negligible drift", () => {
expect(shouldCorrectPreviewMediaTime({ isPlaying: false, currentTime: 4.8, targetTime: 4.1 })).toBe(true);
expect(shouldCorrectPreviewMediaTime({ isPlaying: false, currentTime: 4.11, targetTime: 4.1 })).toBe(false);
});
});
+72
View File
@@ -0,0 +1,72 @@
import { concatenateAudioBlobs, decodeWaveform, extractAudioFromVideo } from "./media.js";
import { getVisualSegmentTimeline } from "./timeline.js";
const getAssetKey = (segment) => segment?.assetId || segment?.src || segment?.id || "";
export function createEmbeddedVideoAudioSegments(visualSegments = [], audioAssets = new Map()) {
const timeline = getVisualSegmentTimeline(visualSegments);
return visualSegments.flatMap((segment, index) => {
if (segment.type !== "video" || segment.sourceAudioDisabled) return [];
const audio = audioAssets.get(getAssetKey(segment));
if (!audio) return [];
const playbackRate = Math.max(0.25, Math.min(4, Number(segment.playbackRate) || 1));
const sourceStart = Math.max(0, Number(segment.sourceStart) || 0);
const requestedSourceDuration = Math.max(0, Number(segment.sourceDuration) || segment.duration * playbackRate);
const availableSourceDuration = Math.max(0, audio.duration - sourceStart);
const sourceDuration = Math.min(requestedSourceDuration || availableSourceDuration, availableSourceDuration);
if (!(sourceDuration > 0)) return [];
return [{
id: segment.id,
assetId: segment.assetId,
start: timeline[index]?.start || 0,
duration: Math.min(segment.duration, sourceDuration / playbackRate),
sourceStart: audio.offset + sourceStart,
sourceDuration,
playbackRate,
}];
});
}
export async function prepareEmbeddedVideoAudio(visualSegments = [], onProgress) {
const candidates = visualSegments.filter((segment) => segment.type === "video" && !segment.sourceAudioDisabled);
const uniqueAssets = [...new Map(candidates.map((segment) => [getAssetKey(segment), segment])).entries()];
if (!uniqueAssets.length) return { blob: null, segments: [] };
const extracted = [];
for (let index = 0; index < uniqueAssets.length; index += 1) {
const [key, segment] = uniqueAssets[index];
onProgress?.({
progress: 2 + Math.round((index / uniqueAssets.length) * 3),
phaseKey: "exportEmbeddedAudio",
phaseParams: { current: index + 1, total: uniqueAssets.length },
});
try {
const sourceBlob = segment.blob instanceof Blob
? segment.blob
: segment.src
? await fetch(segment.src).then((response) => {
if (!response.ok) throw new Error(`无法读取视频素材:${response.status}`);
return response.blob();
})
: null;
if (!sourceBlob) continue;
const blob = await extractAudioFromVideo(sourceBlob, segment.name || "source-video.mp4");
const decoded = await decodeWaveform(blob, 24);
if (decoded.duration > 0) extracted.push({ key, blob, duration: decoded.duration });
} catch (error) {
console.warn("Embedded video audio extraction skipped", segment.name || segment.id, error);
}
}
if (!extracted.length) return { blob: null, segments: [] };
let offset = 0;
const audioAssets = new Map(extracted.map((item) => {
const mapped = [item.key, { offset, duration: item.duration }];
offset += item.duration;
return mapped;
}));
return {
blob: await concatenateAudioBlobs(extracted.map((item) => item.blob)),
segments: createEmbeddedVideoAudioSegments(visualSegments, audioAssets),
};
}
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from "vitest";
import { createEmbeddedVideoAudioSegments } from "./embeddedVideoAudioExport.js";
describe("embedded video audio export mapping", () => {
it("keeps embedded audio after the separated source track has been removed", () => {
const visuals = [
{ id: "image", type: "image", duration: 4 },
{ id: "video", assetId: "asset-video", type: "video", duration: 5, sourceStart: 2, sourceDuration: 10, playbackRate: 2 },
];
const segments = createEmbeddedVideoAudioSegments(visuals, new Map([
["asset-video", { offset: 0, duration: 15 }],
]));
expect(segments).toEqual([{
id: "video", assetId: "asset-video", start: 4, duration: 5,
sourceStart: 2, sourceDuration: 10, playbackRate: 2,
}]);
});
it("does not export embedded audio from a muted video clip", () => {
const visuals = [{ id: "video", assetId: "asset-video", type: "video", duration: 5, sourceAudioDisabled: true }];
expect(createEmbeddedVideoAudioSegments(visuals, new Map([
["asset-video", { offset: 0, duration: 15 }],
]))).toEqual([]);
});
});
+24 -7
View File
@@ -543,13 +543,15 @@ export function drawPreviewFrame(context, visual, canvas, options) {
vision = null,
visualEffects = null,
visualTime = 0,
visualOverlays = [],
visualOverlaySources = [],
} = options;
const { width, height } = canvas;
context.clearRect(0, 0, width, height);
context.fillStyle = "#090b0f";
context.fillRect(0, 0, width, height);
const transform = resolveVisualTransform(visualEffects?.keyframes, visualTime);
const transform = resolveVisualTransform(visualEffects?.keyframes, visualTime, visualEffects?.baseTransform);
const animation = resolveVisualClipAnimation(visualEffects?.animation, visualTime, visualEffects?.duration);
const animatedTransform = {
...transform,
@@ -630,6 +632,21 @@ export function drawPreviewFrame(context, visual, canvas, options) {
}
}
visualOverlays.forEach((overlay, index) => {
const overlayVisual = visualOverlaySources[index];
if (!overlayVisual) return;
const overlayTime = Math.max(0, visualTime - (overlay.start || 0));
const overlayTransform = resolveVisualTransform(overlay.keyframes, overlayTime);
context.save();
context.globalAlpha = overlayTransform.opacity;
context.translate(width / 2 + (overlayTransform.x / 100) * width, height / 2 + (overlayTransform.y / 100) * height);
context.rotate((overlayTransform.rotation * Math.PI) / 180);
context.scale(overlayTransform.scale, overlayTransform.scale);
context.translate(-width / 2, -height / 2);
drawFittedVisual(context, overlayVisual, canvas, "contain", "none", null);
context.restore();
});
if (captionsEnabled && subtitle) {
const captionLayout = getCaptionTextLayout({
context,
@@ -784,7 +801,7 @@ export async function exportBrowserVideo({
await document.fonts.ready.catch(() => {});
}
onProgress?.({ progress: 4, phase: "准备导出画面" });
onProgress?.({ progress: 4, phaseKey: "exportPrepareVisuals" });
const exportVisualSegments = visualSegments.some((segment) => segment.src)
? visualSegments.filter((segment) => segment.src)
: [{ id: "export-visual", src: imageSrc, type: visualType, duration }];
@@ -844,7 +861,7 @@ export async function exportBrowserVideo({
stickerSources.map(async (src) => [src, await loadImage(src).catch(() => null)]),
);
const stickerImageMap = new Map(stickerImageEntries.filter(([, image]) => image));
onProgress?.({ progress: 8, phase: "准备画布与轨道" });
onProgress?.({ progress: 8, phaseKey: "exportPrepareTracks" });
const canvas = document.createElement("canvas");
canvas.width = Math.max(2, Math.round(Number(exportSettings.width) || ratio.width));
canvas.height = Math.max(2, Math.round(Number(exportSettings.height) || ratio.height));
@@ -891,7 +908,7 @@ export async function exportBrowserVideo({
throw new Error("当前浏览器不支持 AudioContext,无法混入音频。");
}
onProgress?.({ progress: 12, phase: "解码并混合音频轨" });
onProgress?.({ progress: 12, phaseKey: "exportMixAudio" });
audioContext = new AudioContextClass();
destination = audioContext.createMediaStreamDestination();
const decodedByBlob = new Map();
@@ -977,7 +994,7 @@ export async function exportBrowserVideo({
recorder.onstop = () => resolve();
});
onProgress?.({ progress: 16, phase: "开始录制视频流" });
onProgress?.({ progress: 16, phaseKey: "exportStartRecording" });
recorder.start(250);
const startTime = performance.now();
let animationFrame = 0;
@@ -1093,7 +1110,7 @@ export async function exportBrowserVideo({
lastProgressUpdate = performance.now();
onProgress?.({
progress: Math.min(92, 16 + Math.round((elapsed / totalDuration) * 76)),
phase: "录制视频流",
phaseKey: "exportRecording",
});
}
@@ -1151,7 +1168,7 @@ export async function exportBrowserVideo({
vision: finalFrameVision,
});
recorder.stop();
onProgress?.({ progress: 94, phase: "封装导出文件" });
onProgress?.({ progress: 94, phaseKey: "exportPackageFile" });
await stopped;
canvasStream.getTracks().forEach((track) => track.stop());
destination?.stream.getTracks().forEach((track) => track.stop());
+29 -4
View File
@@ -54,6 +54,12 @@ export function getOfflineStickersAtTime(stickerSegments = [], sticker = null, t
return stickerSegments.filter((item) => time >= item.start && time < item.start + item.duration);
}
export function getOfflineVisualOverlaysAtTime(segments = [], time = 0) {
return segments
.filter((segment) => time >= segment.start && time < segment.start + segment.duration)
.sort((left, right) => (left.layer || 1) - (right.layer || 1));
}
async function decodeAudioInputs(inputs) {
if (!inputs.length) return [];
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
@@ -176,7 +182,11 @@ async function prepareComposition(options) {
...(options.sticker?.src ? [options.sticker.src] : []),
])];
const stickerImages = new Map((await Promise.all(stickerSources.map(async (src) => [src, await loadImage(src).catch(() => null)]))).filter(([, image]) => image));
return { segments, timeline, items, stickerImages };
const overlayItems = await Promise.all((options.visualOverlaySegments || []).filter((segment) => segment.src).map(async (segment) => ({
segment,
visual: segment.type === "video" ? await loadVideo(segment.src) : await loadImage(segment.src),
})));
return { segments, timeline, items, stickerImages, overlayItems };
}
async function renderCompositionAt(context, canvas, prepared, options, time) {
@@ -211,6 +221,16 @@ async function renderCompositionAt(context, canvas, prepared, options, time) {
const captionIndex = getSegmentIndexAtTime(captionSegments, time, 0);
const caption = captionIndex >= 0 && !captionSegments[captionIndex]?.hidden ? captionSegments[captionIndex].text : "";
const stickers = getOfflineStickersAtTime(options.stickerSegments, options.sticker, time);
const activeOverlaySegments = getOfflineVisualOverlaysAtTime(prepared.overlayItems.map((item) => item.segment), time);
const activeOverlayIds = new Set(activeOverlaySegments.map((segment) => segment.id));
const activeOverlayItems = prepared.overlayItems
.filter((item) => activeOverlayIds.has(item.segment.id))
.sort((left, right) => activeOverlaySegments.findIndex((segment) => segment.id === left.segment.id) - activeOverlaySegments.findIndex((segment) => segment.id === right.segment.id));
for (const overlay of activeOverlayItems) {
if (overlay.segment.type === "video") {
await seekVideoFrame(overlay.visual, Math.min(Math.max(0, (overlay.visual.duration || 0) - 0.04), Math.max(0, time - overlay.segment.start)));
}
}
drawPreviewFrame(context, frameVisual, canvas, {
subtitle: caption, fitMode: options.fitMode, filter: options.filter,
captionsEnabled: options.captionsEnabled, captionPosition: options.captionPosition,
@@ -220,6 +240,8 @@ async function renderCompositionAt(context, canvas, prepared, options, time) {
transitionId: next ? junction.id : "none",
transitionNext: next ? { visual: next.cutoutVisual || next.visual } : null,
transitionProgress, vision: frameVision, visualEffects: item.segment, visualTime: localTime,
visualOverlays: activeOverlayItems.map((item) => ({ ...item.segment, start: item.segment.start - (range?.start || 0) })),
visualOverlaySources: activeOverlayItems.map((item) => item.visual),
});
}
@@ -237,7 +259,7 @@ export async function exportOfflineVideo(options) {
canvas.width = width; canvas.height = height;
const context = canvas.getContext("2d", { alpha: false, desynchronized: false });
if (!context) throw new Error("无法创建离线导出画布。");
options.onProgress?.({ progress: 4, phase: "准备离线渲染" });
options.onProgress?.({ progress: 4, phaseKey: "exportOfflinePreparing" });
const frames = createOfflineFramePlan(options.duration, settings.frameRate);
const preparedPromise = prepareComposition({ ...options, framePlan: frames });
const audioPromise = mixOfflineAudio({ ...options, duration: frames.length * frames[0].duration });
@@ -265,7 +287,7 @@ export async function exportOfflineVideo(options) {
await renderCompositionAt(context, canvas, prepared, options, frame.timestamp);
await videoSource.add(frame.timestamp, frame.duration, { keyFrame: frame.keyFrame });
if (frame.index % Math.max(1, Math.round(frames.length / 100)) === 0) {
options.onProgress?.({ progress: 10 + Math.round((frame.index / frames.length) * 84), phase: `离线渲染 ${frame.index + 1} / ${frames.length}` });
options.onProgress?.({ progress: 10 + Math.round((frame.index / frames.length) * 84), phaseKey: "exportOfflineRendering", phaseParams: { current: frame.index + 1, total: frames.length } });
}
}
await output.finalize();
@@ -277,8 +299,11 @@ export async function exportOfflineVideo(options) {
item.temporalMaskCache?.dispose();
if (item.segment.type === "video") { item.visual.removeAttribute("src"); item.visual.load(); }
});
prepared.overlayItems.forEach((item) => {
if (item.segment.type === "video") { item.visual.removeAttribute("src"); item.visual.load(); }
});
}
options.onProgress?.({ progress: 98, phase: "验证导出文件" });
options.onProgress?.({ progress: 98, phaseKey: "exportVerifyFile" });
return {
blob: new Blob([target.buffer], { type: codec.mimeType }), extension: codec.extension,
label: codec.extension === "mp4" ? "MP4" : "WebM", mimeType: codec.mimeType,
+10
View File
@@ -4,6 +4,7 @@ import {
createOfflineFramePlan,
getOfflineExportCodec,
getOfflineStickersAtTime,
getOfflineVisualOverlaysAtTime,
} from "./offlineVideoExport.js";
import { getVisualDimensions } from "./media.js";
@@ -38,6 +39,15 @@ describe("offline video export", () => {
expect(getOfflineStickersAtTime([], null, 1)).toEqual([]);
});
it("resolves active picture-in-picture layers in export order", () => {
const overlays = [
{ id: "top", start: 0, duration: 3, layer: 2 },
{ id: "bottom", start: 1, duration: 3, layer: 1 },
{ id: "ended", start: 0, duration: 1, layer: 3 },
];
expect(getOfflineVisualOverlaysAtTime(overlays, 1.5).map((item) => item.id)).toEqual(["bottom", "top"]);
});
it("preserves decoded canvas dimensions instead of treating frames as square", () => {
expect(getVisualDimensions({ width: 1920, height: 1080 })).toEqual({ width: 1920, height: 1080 });
expect(getVisualDimensions({ videoWidth: 1280, videoHeight: 720, width: 1, height: 1 })).toEqual({ width: 1280, height: 720 });
+8
View File
@@ -56,6 +56,14 @@ export function getLinkedSourceAudioEnd(linkedSegments = []) {
return linkedSegments.reduce((end, segment) => Math.max(end, segment.start + segment.duration), 0);
}
export function shouldMuteEmbeddedVideoAudio(segment, { sourceAudioBlob = null, sourceAudioAssetId = "", linkedSegments = [] } = {}) {
if (!segment || segment.type !== "video" || segment.sourceAudioDisabled) return true;
if (!sourceAudioBlob) return false;
return Number.isFinite(segment.sourceAudioOffset) ||
Boolean(sourceAudioAssetId && segment.assetId === sourceAudioAssetId) ||
linkedSegments.some((item) => item.id === segment.id);
}
export function sliceSourceAudioPeaks(peaks = [], segment, sourceAudioDuration = 0) {
if (!peaks.length || !segment || sourceAudioDuration <= 0) return peaks;
const startIndex = Math.max(0, Math.floor((segment.sourceStart / sourceAudioDuration) * peaks.length));
+9 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { getLinkedSourceAudioEnd, getLinkedSourceAudioSegments, getLinkedSourceAudioState } from "./sourceAudioSync.js";
import { getLinkedSourceAudioEnd, getLinkedSourceAudioSegments, getLinkedSourceAudioState, shouldMuteEmbeddedVideoAudio } from "./sourceAudioSync.js";
describe("linked source audio", () => {
const visualSegments = [
@@ -46,4 +46,12 @@ describe("linked source audio", () => {
);
expect(segments.map((segment) => segment.id)).toEqual(["c"]);
});
it("plays embedded video audio until that clip has an extracted source-audio mapping", () => {
const clip = { id: "video-clip", assetId: "video-1", type: "video" };
expect(shouldMuteEmbeddedVideoAudio(clip)).toBe(false);
expect(shouldMuteEmbeddedVideoAudio({ ...clip, sourceAudioDisabled: true })).toBe(true);
expect(shouldMuteEmbeddedVideoAudio(clip, { sourceAudioBlob: new Blob(), sourceAudioAssetId: "video-1" })).toBe(true);
expect(shouldMuteEmbeddedVideoAudio(clip, { sourceAudioBlob: new Blob(), sourceAudioAssetId: "another-video" })).toBe(false);
});
});
+8
View File
@@ -289,6 +289,14 @@ export function getSegmentStartTime(captionSegments, index, targetDuration = 0)
return getCaptionTimeline(captionSegments, targetDuration)[Math.max(0, index)]?.start ?? 0;
}
export function getVisualSegmentStartTime(visualSegments, index) {
const safeIndex = Math.max(0, Math.min(Array.isArray(visualSegments) ? visualSegments.length : 0, Number(index) || 0));
return (visualSegments || []).slice(0, safeIndex).reduce(
(total, segment) => total + Math.max(0, Number(segment?.duration) || 0),
0,
);
}
export function formatTime(value) {
const seconds = Math.max(0, Number.isFinite(value) ? value : 0);
const minutes = Math.floor(seconds / 60);
+8
View File
@@ -8,6 +8,7 @@ import {
getTimedSegmentIndexAtTime,
getTimedSegmentsEnd,
getVisualSegmentIndexAtTime,
getVisualSegmentStartTime,
getVisualSegmentTimeline,
moveTimedCaptionSegment,
materializeCaptionTimings,
@@ -24,6 +25,13 @@ import {
} from "./timelineScale.js";
describe("timeline primitives", () => {
it("computes a visual clip start without treating visual clips as captions", () => {
const clips = [{ duration: 1.25 }, { duration: 2.5 }, { duration: 4 }];
expect(getVisualSegmentStartTime(clips, 0)).toBe(0);
expect(getVisualSegmentStartTime(clips, 1)).toBe(1.25);
expect(getVisualSegmentStartTime(clips, 2)).toBe(3.75);
});
it("fits an uploaded video into most of the visible timeline", () => {
const zoom = getTimelineAutoFitZoom(15);
const visibleDuration = getTimelineVisibleDuration(zoom);
+15
View File
@@ -17,6 +17,13 @@ export function createTimelineClipboardActions(d) {
const handleDeleteTrack = () => {
if (d.trackLocks[d.selectedTrack]) return void d.notify("当前轨道已锁定,无法删除");
if (d.selectedTrack === "caption") return void d.handleRemoveSegment();
if (d.selectedTrack === "overlay") {
if (!d.selectedVisualOverlayId) return void d.notify("请先选择一个画中画片段");
const next = d.visualOverlaySegments.filter((segment) => segment.id !== d.selectedVisualOverlayId);
d.setVisualOverlaySegments(next);
d.setSelectedVisualOverlayId("");
return void d.notify("已删除画中画片段");
}
if (d.selectedTrack === "sticker") return void deleteSticker();
if (d.selectedTrack === "image") {
if (!d.imageSrc || d.imageClipCount === 0) return void d.notify("当前没有视觉片段可删除");
@@ -49,6 +56,14 @@ export function createTimelineClipboardActions(d) {
d.clearImageTrack();
};
const handleDuplicateTrack = () => {
if (d.selectedTrack === "overlay") {
const source = d.visualOverlaySegments.find((segment) => segment.id === d.selectedVisualOverlayId);
if (!source) return void d.notify("请先选择一个画中画片段");
const copy = { ...source, id: makeId("overlay"), name: `${source.name || "画中画"} 副本`, start: Math.min(MAX_TIMELINE_DURATION_SECONDS - source.duration, source.start + 0.2), layer: d.visualOverlaySegments.length + 1 };
d.setVisualOverlaySegments((items) => [...items, copy]);
d.setSelectedVisualOverlayId(copy.id);
return void d.notify("已复制画中画片段");
}
if (d.selectedTrack === "sticker") {
const source = d.stickerSegments[focusedStickerIndex()]; if (!source) return void d.notify("请先选择一个贴纸片段");
const copy = { ...source, id: makeId("sticker"), start: Math.min(MAX_TIMELINE_DURATION_SECONDS - source.duration, source.start + source.duration + 0.2) };
+31
View File
@@ -15,6 +15,37 @@ function installPointerListeners() {
afterEach(() => vi.unstubAllGlobals());
describe("timeline drag playback behavior", () => {
it("reveals and commits a picture-in-picture target when a main visual is dragged downward", () => {
const listeners = installPointerListeners();
vi.stubGlobal("document", {
querySelector: vi.fn(() => ({
getBoundingClientRect: () => ({ left: 100, width: 500, top: 20, bottom: 68 }),
querySelectorAll: () => [],
})),
});
const first = { id: "visual-1", assetId: "asset-1", type: "image", src: "one.png", duration: 5 };
const second = { id: "visual-2", assetId: "asset-2", type: "image", src: "two.png", duration: 5 };
const timelineClipDragRef = { current: null };
const setVisualOverlaySegments = vi.fn((update) => update([]));
const controls = createTimelineReorderControls({
visualSegments: [first, second], renderedVisualSegments: [first, second], visualOverlaySegments: [],
timelineDuration: 10, trackLocks: { image: false }, timelineClipDragRef,
setTimelineClipDrag: vi.fn(), setSelectedTrack: vi.fn(), setSelectedVisualSegmentId: vi.fn(),
setSelectedVisualOverlayId: vi.fn(), setVisualOverlaySegments, commitVisualSegments: vi.fn(),
seekTo: vi.fn(), notify: vi.fn(), suppressTimelineClipClickRef: { current: "" },
pauseForTimelineEdit: vi.fn(),
});
controls.startTimelineClipDrag(
{ button: 0, clientX: 400, clientY: 40, target: { closest: () => null }, preventDefault: vi.fn(), stopPropagation: vi.fn() },
"image", "visual-2", 1,
);
listeners.get("pointermove")({ clientX: 200, clientY: 90 });
expect(timelineClipDragRef.current).toMatchObject({ mode: "overlay", overlayStart: 2, dragging: true });
listeners.get("pointerup")();
expect(setVisualOverlaySegments).toHaveBeenCalledTimes(1);
});
it("pauses immediately when a sticker clip is pressed", () => {
const listeners = installPointerListeners();
const pauseForTimelineEdit = vi.fn();
+32 -3
View File
@@ -1,5 +1,6 @@
import { getVisualSegmentTimeline, materializeCaptionTimings, moveTimedCaptionSegment, reorderTimelineItems } from "./timeline.js";
import { collectTimelineSnapPoints, findClosestTimelineSnap, snapTimelineRange } from "./timelineSnap.js";
import { createVisualOverlaySegment } from "./visualOverlayTimeline.js";
export function createTimelineReorderControls(d) {
const getTimelineReorderIndex = (track, x, y) => {
@@ -68,13 +69,25 @@ export function createTimelineReorderControls(d) {
const count = track === "image" ? d.renderedVisualSegments.length : d.captionSegments.length;
if (count < 2) return;
event.preventDefault(); event.stopPropagation();
const initial = { track, segmentId, fromIndex: index, overIndex: index, startX: event.clientX, startY: event.clientY, x: event.clientX, y: event.clientY, dragging: false };
const imageTrackElement = track === "image" ? document.querySelector('[data-timeline-reorder-track="image"]') : null;
const imageTrackRect = imageTrackElement?.getBoundingClientRect();
const draggedVisual = track === "image" ? d.renderedVisualSegments[index] : null;
const initial = { track, mode: "reorder", segmentId, fromIndex: index, overIndex: index, startX: event.clientX, startY: event.clientY, x: event.clientX, y: event.clientY, dragging: false };
d.timelineClipDragRef.current = initial; d.setTimelineClipDrag(initial);
const move = (e) => {
const state = d.timelineClipDragRef.current; if (!state || state.segmentId !== segmentId) return;
if (!state.dragging && Math.hypot(e.clientX - state.startX, e.clientY - state.startY) < 6) return;
const overIndex = Math.max(0, Math.min(count - 1, getTimelineReorderIndex(track, e.clientX, e.clientY)));
const next = { ...state, overIndex, x: e.clientX, y: e.clientY, dragging: true };
const wantsOverlay = track === "image" && imageTrackRect && e.clientY > imageTrackRect.bottom + 8;
const overIndex = wantsOverlay
? state.overIndex
: Math.max(0, Math.min(count - 1, getTimelineReorderIndex(track, e.clientX, e.clientY)));
const overlayStart = wantsOverlay
? Math.max(0, Math.min(
Math.max(0, d.timelineDuration - (draggedVisual?.duration || 0)),
((e.clientX - imageTrackRect.left) / Math.max(1, imageTrackRect.width)) * d.timelineDuration,
))
: state.overlayStart;
const next = { ...state, mode: wantsOverlay ? "overlay" : "reorder", overIndex, overlayStart, x: e.clientX, y: e.clientY, dragging: true };
d.timelineClipDragRef.current = next; d.setTimelineClipDrag(next);
};
const up = () => {
@@ -83,6 +96,22 @@ export function createTimelineReorderControls(d) {
if (!state?.dragging) return;
d.suppressTimelineClipClickRef.current = segmentId;
setTimeout(() => { if (d.suppressTimelineClipClickRef.current === segmentId) d.suppressTimelineClipClickRef.current = ""; }, 120);
if (track === "image" && state.mode === "overlay" && draggedVisual) {
const remaining = d.visualSegments.filter((segment) => segment.id !== segmentId);
if (!remaining.length) return void d.notify("至少保留一个主画面后才能转为画中画");
const overlay = createVisualOverlaySegment(
{ ...draggedVisual, id: draggedVisual.assetId || draggedVisual.id },
state.overlayStart,
{ duration: draggedVisual.duration, layer: d.visualOverlaySegments.length + 1 },
);
d.commitVisualSegments(remaining, "画面片段已移至画中画轨道");
d.setVisualOverlaySegments((items) => [...items, overlay]);
d.setSelectedVisualSegmentId("");
d.setSelectedVisualOverlayId(overlay.id);
d.setSelectedTrack("overlay");
d.seekTo(overlay.start);
return;
}
commitTimelineClipReorder(track, state.fromIndex, state.overIndex);
};
addEventListener("pointermove", move); addEventListener("pointerup", up, { once: true });
+9 -1
View File
@@ -11,7 +11,15 @@ const addRange = (points, track, id, start, duration) => {
};
export function collectTimelineSnapPoints(d, exclude = {}) {
const points = [];
const timelineDuration = Math.max(0, Number(d.timelineDuration) || 0);
const currentTime = Math.max(0, Math.min(timelineDuration, Number(d.currentTime) || 0));
const points = [
{ time: 0, track: "timeline", id: "start", edge: "start" },
];
if (timelineDuration > 0) points.push({ time: timelineDuration, track: "timeline", id: "end", edge: "end" });
if (currentTime > 0 && currentTime < timelineDuration) {
points.push({ time: currentTime, track: "playhead", id: "playhead", edge: "playhead" });
}
getVisualSegmentTimeline(d.visualSegments ?? []).forEach((range, index) => {
const segment = d.visualSegments[index];
addRange(points, "image", segment?.id, range.start, range.end - range.start);
+11 -2
View File
@@ -11,13 +11,22 @@ describe("cross-track timeline snapping", () => {
audioSegments: [{ id: "voice", start: 7, duration: 2 }],
sourceAudioStart: 10, sourceAudioDuration: 2,
musicStart: 13, musicDuration: 2,
timelineDuration: 20,
currentTime: 6.5, timelineDuration: 20,
});
expect(points.map((point) => point.time)).toEqual(expect.arrayContaining([0, 2, 3, 4, 5, 6, 7, 9, 10, 12, 13, 15]));
expect(points.map((point) => point.time)).toEqual(expect.arrayContaining([0, 2, 3, 4, 5, 6, 6.5, 7, 9, 10, 12, 13, 15, 20]));
expect(points).toEqual(expect.arrayContaining([
expect.objectContaining({ time: 6.5, track: "playhead" }),
]));
});
it("snaps either moving edge to the closest foreign boundary", () => {
expect(snapTimelineRange(2.94, 1, [{ time: 3, track: "caption", id: "a" }], 0.1)).toMatchObject({ start: 3, guide: { time: 3 } });
expect(snapTimelineRange(1.96, 1, [{ time: 3, track: "audio", id: "b" }], 0.1)).toMatchObject({ start: 2, guide: { time: 3 } });
});
it("snaps a caption edge to the playhead", () => {
const points = collectTimelineSnapPoints({ currentTime: 4.25, timelineDuration: 10 });
expect(snapTimelineRange(4.19, 1.5, points, 0.1)).toMatchObject({ start: 4.25, guide: { time: 4.25 } });
expect(snapTimelineRange(2.69, 1.5, points, 0.1)).toMatchObject({ start: 2.75, guide: { time: 4.25 } });
});
});
+1 -1
View File
@@ -33,7 +33,7 @@ export function createTimelineViewModel(d) {
assetDragPreview: d.assetDragPreview,
draggedAsset,
});
const displayedVisualSegments = activeTimelineClipDrag?.track === "image"
const displayedVisualSegments = activeTimelineClipDrag?.track === "image" && activeTimelineClipDrag.mode !== "overlay"
? reorderTimelineItems(
renderedVisualSegments,
activeTimelineClipDrag.fromIndex,
+34 -3
View File
@@ -71,18 +71,19 @@ export function normalizeVisualKeyframes(keyframes = []) {
}, []);
}
export function resolveVisualTransform(keyframes = [], time = 0) {
export function resolveVisualTransform(keyframes = [], time = 0, baseTransform = DEFAULT_TRANSFORM) {
const safeTime = Math.max(0, Number(time) || 0);
const normalizedKeyframes = normalizeVisualKeyframes(keyframes);
const normalizedBaseTransform = normalizeVisualTransform(baseTransform);
return Object.fromEntries(VISUAL_TRANSFORM_KEYS.map((key) => {
const frames = normalizedKeyframes
.filter((frame) => Number.isFinite(Number(frame[key])))
.map((frame) => ({ time: Math.max(0, Number(frame.time) || 0), value: normalizeVisualProperty(key, frame[key]) }))
.sort((a, b) => a.time - b.time);
if (!frames.length) return [key, DEFAULT_TRANSFORM[key]];
if (!frames.length) return [key, normalizedBaseTransform[key]];
// A keyframe starts controlling its property at its own timestamp. Before
// the first keyframe the clip must retain its unmodified default value.
if (safeTime < frames[0].time) return [key, DEFAULT_TRANSFORM[key]];
if (safeTime < frames[0].time) return [key, normalizedBaseTransform[key]];
if (safeTime === frames[0].time) return [key, frames[0].value];
if (safeTime >= frames.at(-1).time) return [key, frames.at(-1).value];
const rightIndex = frames.findIndex((frame) => frame.time >= safeTime);
@@ -124,6 +125,36 @@ export function removeVisualPropertyKeyframe(keyframes = [], time, key) {
});
}
export function snapVisualScaleToFrameEdges(transform = {}, frame = {}, thresholdPixels = 8) {
const width = Math.max(1, Number(frame.width) || 1);
const height = Math.max(1, Number(frame.height) || 1);
const scale = Math.max(0.1, Number(transform.scale) || 1);
const centerX = 0.5 + (Number(transform.x) || 0) / 100;
const centerY = 0.5 + (Number(transform.y) || 0) / 100;
const radians = (Number(transform.rotation) || 0) * Math.PI / 180;
const cosine = Math.abs(Math.cos(radians));
const sine = Math.abs(Math.sin(radians));
const horizontalScaleExtent = 0.5 * (cosine + (height / width) * sine);
const verticalScaleExtent = 0.5 * (cosine + (width / height) * sine);
const targets = [
{ scale: centerX / horizontalScaleExtent, guide: "left", dimension: width },
{ scale: (1 - centerX) / horizontalScaleExtent, guide: "right", dimension: width },
{ scale: centerY / verticalScaleExtent, guide: "top", dimension: height },
{ scale: (1 - centerY) / verticalScaleExtent, guide: "bottom", dimension: height },
].filter((target) => Number.isFinite(target.scale) && target.scale >= 0.1 && target.scale <= 4);
const nearest = targets.reduce((best, target) => {
const distance = Math.abs(scale - target.scale) * target.dimension * (target.dimension === width ? horizontalScaleExtent : verticalScaleExtent);
return distance < best.distance ? { ...target, distance } : best;
}, { distance: Infinity });
if (nearest.distance > Math.max(1, Number(thresholdPixels) || 8)) return { transform, guides: [] };
const snappedScale = nearest.scale;
const guides = targets.filter((target) => {
const extent = target.dimension === width ? horizontalScaleExtent : verticalScaleExtent;
return Math.abs(snappedScale - target.scale) * target.dimension * extent <= 0.75;
}).map((target) => target.guide);
return { transform: { ...transform, scale: snappedScale }, guides };
}
export function getVisualMaskCss(mask = {}) {
const feather = Math.max(0, Math.min(40, Number(mask.feather) || 0));
const edge = Math.max(0, 50 - feather);
+25 -1
View File
@@ -1,7 +1,18 @@
import { describe, expect, it } from "vitest";
import { getCircleMaskCss, getVisualMaskFeatherPixels, getVisualMaskInsets, getVisualMaskSvgDataUrl, getVisualSourceTime, hasVisualPropertyKeyframe, normalizeVisualKeyframes, removeVisualPropertyKeyframe, resolveVisualTransform, updateVisualSegmentPlaybackRate, upsertVisualKeyframe, upsertVisualPropertyKeyframe } from "./visualEffects.js";
import { getCircleMaskCss, getVisualMaskFeatherPixels, getVisualMaskInsets, getVisualMaskSvgDataUrl, getVisualSourceTime, hasVisualPropertyKeyframe, normalizeVisualKeyframes, removeVisualPropertyKeyframe, resolveVisualTransform, snapVisualScaleToFrameEdges, updateVisualSegmentPlaybackRate, upsertVisualKeyframe, upsertVisualPropertyKeyframe } from "./visualEffects.js";
describe("visual effects", () => {
it("snaps visual scaling to nearby frame edges", () => {
const snapped = snapVisualScaleToFrameEdges({ x: 0, y: 0, scale: 0.985, rotation: 0 }, { width: 360, height: 640 });
expect(snapped.transform.scale).toBe(1);
expect(snapped.guides).toEqual(["left", "right", "top", "bottom"]);
});
it("keeps free scaling outside the edge snap threshold", () => {
const transform = { x: 0, y: 0, scale: 0.8, rotation: 0 };
expect(snapVisualScaleToFrameEdges(transform, { width: 360, height: 640 })).toEqual({ transform, guides: [] });
});
it("maps timeline time to source time using the clip playback rate", () => {
expect(getVisualSourceTime({ sourceStart: 1.5, playbackRate: 2 }, 2)).toBe(5.5);
});
@@ -32,6 +43,19 @@ describe("visual effects", () => {
.toMatchObject({ x: 20, scale: 1.5 });
});
it("applies a clip-wide base transform when no keyframe was explicitly added", () => {
const baseTransform = { x: 12, y: -8, scale: 1.6, rotation: 4, opacity: 0.75 };
expect(resolveVisualTransform([], 0, baseTransform)).toEqual(baseTransform);
expect(resolveVisualTransform([], 8, baseTransform)).toEqual(baseTransform);
});
it("uses the clip-wide transform before sparse keyframes and for unkeyed properties", () => {
const baseTransform = { x: 10, y: -8, scale: 1.4, rotation: 4, opacity: 0.75 };
expect(resolveVisualTransform([{ time: 2, scale: 2 }], 1, baseTransform)).toEqual(baseTransform);
expect(resolveVisualTransform([{ time: 2, scale: 2 }], 3, baseTransform))
.toEqual({ ...baseTransform, scale: 2 });
});
it("keeps defaults before the first keyframe, interpolates between frames, and holds the last frame", () => {
const frames = [{ time: 1, x: 20, scale: 1.2 }, { time: 3, x: 60, scale: 1.6 }];
expect(resolveVisualTransform(frames, 0.5)).toMatchObject({ x: 0, scale: 1 });
+127
View File
@@ -0,0 +1,127 @@
import { normalizeVisualKeyframes, upsertVisualKeyframe } from "./visualEffects.js";
import { createVisualSegment } from "./timeline.js";
export const DEFAULT_OVERLAY_SECONDS = 5;
function toAspectRatio(value, fallback = 1) {
if (typeof value === "string") {
const [width, height] = value.split("/").map(Number);
if (width > 0 && height > 0) return width / height;
}
const ratio = Number(value);
return Number.isFinite(ratio) && ratio > 0 ? ratio : fallback;
}
export function getVisualOverlayContainBox(overlay, frameAspectRatio) {
const sourceAspectRatio = overlay?.width > 0 && overlay?.height > 0
? overlay.width / overlay.height
: 1;
const frameRatio = toAspectRatio(frameAspectRatio);
if (sourceAspectRatio >= frameRatio) {
return { widthPercent: 100, heightPercent: (frameRatio / sourceAspectRatio) * 100 };
}
return { widthPercent: (sourceAspectRatio / frameRatio) * 100, heightPercent: 100 };
}
export function getVisualOverlayPixelBox(overlay, frameSize) {
const frameWidth = Math.max(1, Number(frameSize?.width) || 1);
const frameHeight = Math.max(1, Number(frameSize?.height) || 1);
const sourceAspectRatio = overlay?.width > 0 && overlay?.height > 0
? overlay.width / overlay.height
: 1;
if (sourceAspectRatio >= frameWidth / frameHeight) {
return { width: frameWidth, height: frameWidth / sourceAspectRatio };
}
return { width: frameHeight * sourceAspectRatio, height: frameHeight };
}
export function createVisualOverlaySegment(asset, start = 0, options = {}) {
const duration = Math.max(0.1, Number(options.duration ?? asset?.duration) || DEFAULT_OVERLAY_SECONDS);
return {
id: options.id || `overlay-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
assetId: asset?.id || "",
name: asset?.name || "画中画",
type: asset?.type === "video" ? "video" : "image",
src: asset?.src || "",
blob: asset?.blob,
width: Number(asset?.width) || 0,
height: Number(asset?.height) || 0,
trackFrames: Array.isArray(asset?.trackFrames) ? asset.trackFrames : [],
sourceStart: Math.max(0, Number(asset?.sourceStart) || 0),
sourceDuration: Math.max(0, Number(asset?.sourceDuration) || Number(asset?.duration) || 0),
playbackRate: Math.max(0.25, Math.min(4, Number(asset?.playbackRate) || 1)),
start: Math.max(0, Number(start) || 0),
duration,
muted: options.muted === true,
layer: Math.max(1, Number(options.layer) || 1),
keyframes: normalizeVisualKeyframes(options.keyframes?.length ? options.keyframes : [{
time: 0,
x: 27,
y: -24,
scale: 0.34,
rotation: 0,
opacity: 1,
}]),
};
}
export function createMainVisualFromOverlay(overlay) {
if (!overlay?.src) return null;
return createVisualSegment(overlay.duration, {
assetId: overlay.assetId,
name: overlay.name,
type: overlay.type,
src: overlay.src,
blob: overlay.blob,
width: overlay.width,
height: overlay.height,
duration: overlay.duration,
trackFrames: overlay.trackFrames,
});
}
export function getActiveVisualOverlays(segments = [], time = 0) {
return segments
.filter((segment) => time >= segment.start && time < segment.start + segment.duration)
.sort((left, right) => (left.layer || 1) - (right.layer || 1));
}
export function updateVisualOverlayTransform(segment, localTime, transform) {
return {
...segment,
keyframes: upsertVisualKeyframe(segment?.keyframes, Math.max(0, Number(localTime) || 0), transform),
};
}
export function snapVisualOverlayTransform(transform, threshold = 1.6) {
const scale = Math.max(0.08, Number(transform?.scale) || 1);
const targetsX = [
{ value: 0, guide: "center-x" },
{ value: -50 + scale * 50, guide: "left" },
{ value: 50 - scale * 50, guide: "right" },
];
const targetsY = [
{ value: 0, guide: "center-y" },
{ value: -50 + scale * 50, guide: "top" },
{ value: 50 - scale * 50, guide: "bottom" },
];
const snapAxis = (value, targets) => targets.reduce((best, target) => {
const distance = Math.abs(value - target.value);
return distance <= threshold && distance < best.distance ? { ...target, distance } : best;
}, { value, guide: "", distance: Infinity });
const x = snapAxis(Number(transform?.x) || 0, targetsX);
const y = snapAxis(Number(transform?.y) || 0, targetsY);
return { transform: { ...transform, x: x.value, y: y.value }, guides: [x.guide, y.guide].filter(Boolean) };
}
export function getVisualOverlayPreset(id) {
const presets = {
"top-left": { x: -29, y: -27, scale: 0.32, rotation: 0, opacity: 1 },
"top-right": { x: 29, y: -27, scale: 0.32, rotation: 0, opacity: 1 },
"bottom-left": { x: -29, y: 27, scale: 0.32, rotation: 0, opacity: 1 },
"bottom-right": { x: 29, y: 27, scale: 0.32, rotation: 0, opacity: 1 },
center: { x: 0, y: 0, scale: 0.5, rotation: 0, opacity: 1 },
full: { x: 0, y: 0, scale: 1, rotation: 0, opacity: 1 },
};
return presets[id] ? { ...presets[id] } : null;
}
+63
View File
@@ -0,0 +1,63 @@
import { describe, expect, it } from "vitest";
import { createMainVisualFromOverlay, createVisualOverlaySegment, getActiveVisualOverlays, getVisualOverlayContainBox, getVisualOverlayPixelBox, getVisualOverlayPreset, snapVisualOverlayTransform, updateVisualOverlayTransform } from "./visualOverlayTimeline.js";
describe("visual overlay timeline", () => {
it("promotes an overlay to a full main-track visual while preserving its media and duration", () => {
const overlay = createVisualOverlaySegment({ id: "asset-1", name: "clip.png", type: "image", src: "blob:test", width: 800, height: 600 }, 3, { duration: 4 });
const visual = createMainVisualFromOverlay(overlay);
expect(visual).toMatchObject({ assetId: "asset-1", name: "clip.png", type: "image", src: "blob:test", width: 800, height: 600, duration: 4 });
expect(visual.id).not.toBe(overlay.id);
expect(visual).not.toHaveProperty("start");
expect(visual).not.toHaveProperty("layer");
});
it("creates a picture-in-picture clip at the requested time", () => {
const clip = createVisualOverlaySegment({ id: "asset", name: "camera", type: "video", src: "blob:test", duration: 3, trackFrames: ["frame-a", "frame-b"] }, 4, { id: "pip" });
expect(clip).toMatchObject({ id: "pip", start: 4, duration: 3, type: "video", layer: 1, muted: false, trackFrames: ["frame-a", "frame-b"] });
expect(clip.keyframes[0]).toMatchObject({ scale: 0.34, x: 27, y: -24 });
});
it("preserves a square overlay box inside portrait and landscape frames", () => {
const square = { width: 2048, height: 2048 };
expect(getVisualOverlayContainBox(square, "9 / 16")).toEqual({ widthPercent: 100, heightPercent: 56.25 });
expect(getVisualOverlayContainBox(square, "16 / 9")).toEqual({ widthPercent: 56.25, heightPercent: 100 });
});
it("creates pixel bounds that hug the overlay content", () => {
expect(getVisualOverlayPixelBox({ width: 2048, height: 2048 }, { width: 291, height: 518 }))
.toEqual({ width: 291, height: 291 });
const portrait = getVisualOverlayPixelBox({ width: 720, height: 1280 }, { width: 291, height: 518 });
expect(portrait.width).toBe(291);
expect(portrait.height).toBeCloseTo(517.3333);
});
it("preserves non-square source aspect ratios in the overlay box", () => {
const box = getVisualOverlayContainBox({ width: 1920, height: 1080 }, "9 / 16");
expect(box.widthPercent).toBe(100);
expect(box.heightPercent).toBeCloseTo(31.640625);
});
it("returns only active overlays in layer order", () => {
const clips = [
{ id: "top", start: 0, duration: 5, layer: 2 },
{ id: "past", start: 0, duration: 1, layer: 3 },
{ id: "bottom", start: 1, duration: 5, layer: 1 },
];
expect(getActiveVisualOverlays(clips, 2).map((clip) => clip.id)).toEqual(["bottom", "top"]);
});
it("stores direct manipulation as a real keyframe", () => {
const clip = createVisualOverlaySegment({ src: "x" }, 0, { id: "pip" });
const updated = updateVisualOverlayTransform(clip, 1.25, { x: 5, y: 6, scale: 0.5, rotation: 10, opacity: 1 });
expect(updated.keyframes.at(-1)).toMatchObject({ time: 1.25, x: 5, y: 6, scale: 0.5, rotation: 10 });
});
it("snaps overlay centers and edges to the canvas", () => {
expect(snapVisualOverlayTransform({ x: 0.8, y: -33.4, scale: 0.34 }).transform).toMatchObject({ x: 0, y: -33 });
expect(snapVisualOverlayTransform({ x: 0.8, y: -33.4, scale: 0.34 }).guides).toEqual(["center-x", "top"]);
});
it("provides deterministic layout presets", () => {
expect(getVisualOverlayPreset("bottom-right")).toMatchObject({ x: 29, y: 27, scale: 0.32 });
expect(getVisualOverlayPreset("missing")).toBeNull();
});
});
-1
View File
@@ -114,7 +114,6 @@ export function createVisualTimelineActions(d) {
sourceSegments.length,
);
d.seekTo(totalDuration);
if (asset.type === "video") d.extractVideoSourceAudio(asset, totalDuration, { append: true });
}
function updateVisualAssetInTimeline(assetId, updates) {
+10
View File
@@ -0,0 +1,10 @@
import { describe, expect, it } from "vitest";
import { isValidPreviewShellMeasurement } from "./hooks/usePreviewFrameSize.js";
describe("large-canvas preview sizing", () => {
it("documents that disconnected portal shells are not valid resize measurements", () => {
expect(isValidPreviewShellMeasurement({ isConnected: true, clientWidth: 640, clientHeight: 360 })).toBe(true);
expect(isValidPreviewShellMeasurement({ isConnected: false, clientWidth: 1, clientHeight: 1 })).toBe(false);
expect(isValidPreviewShellMeasurement({ isConnected: true, clientWidth: 1, clientHeight: 1 })).toBe(false);
});
});
+284 -12
View File
@@ -7,6 +7,7 @@
color: #eef5f7;
font-synthesis: none;
text-rendering: optimizeLegibility;
font-size: 13px;
}
* {
@@ -744,6 +745,49 @@ button:disabled {
border-radius: 7px;
}
.focus-preview-backdrop {
position: fixed;
z-index: 9998;
inset: 0;
border: 0;
padding: 0;
background: rgba(3, 6, 10, .82);
backdrop-filter: blur(8px);
cursor: default;
}
.preview-stage.is-focus-preview {
position: fixed;
z-index: 9999;
inset: 20px;
grid-template-rows: 54px minmax(0, 1fr) 70px;
border: 1px solid rgba(255, 255, 255, .12);
border-radius: 12px;
padding: 0;
background: #0f1319;
box-shadow: 0 28px 90px rgba(0, 0, 0, .62);
}
.focus-preview-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
min-width: 0;
border-bottom: 1px solid rgba(255, 255, 255, .08);
padding: 0 14px 0 18px;
background: #141920;
}
.focus-preview-header > div { display: flex; align-items: baseline; gap: 12px; min-width: 0; }
.focus-preview-header strong { color: #edf5f7; font-size: 14px; }
.focus-preview-header span { overflow: hidden; color: #84919b; font-size: 11px; text-overflow: ellipsis; white-space: nowrap; }
.preview-stage.is-focus-preview .preview-canvas { padding: 12px; }
.preview-stage.is-focus-preview .preview-empty { width: auto; min-width: min(420px, 78%); }
.preview-stage.is-focus-preview .preview-empty strong,
.preview-stage.is-focus-preview .preview-empty span { max-width: min(520px, 82%); text-align: center; }
.preview-stage.is-focus-preview .preview-frame { box-shadow: 0 20px 64px rgba(0, 0, 0, .5); }
.media-panel {
display: flex;
flex-direction: column;
@@ -2648,6 +2692,112 @@ button:disabled {
overflow: hidden;
}
.visual-media-layer.is-transform-editable { cursor: move; }
.visual-transform-box {
position: absolute;
z-index: 7;
inset: 0;
border: 1.5px solid #58a6ff;
box-shadow: 0 0 0 1px rgba(5, 10, 18, .82), 0 0 18px rgba(46, 143, 255, .18);
cursor: move;
pointer-events: auto;
transform-origin: center;
touch-action: none;
}
.visual-transform-label {
position: absolute;
top: -25px;
left: -1px;
max-width: 120px;
overflow: hidden;
padding: 3px 7px;
border-radius: 4px;
color: #07121e;
background: #58a6ff;
font-size: 10px;
font-weight: 750;
line-height: 16px;
text-overflow: ellipsis;
white-space: nowrap;
}
.visual-transform-handle,
.visual-transform-rotate {
position: absolute;
z-index: 2;
width: 12px;
height: 12px;
border: 2px solid #071018;
border-radius: 2px;
padding: 0;
background: #f2f7ff;
box-shadow: 0 0 0 1px #58a6ff;
}
.visual-transform-handle.is-nw { top: -6px; left: -6px; cursor: nwse-resize; }
.visual-transform-handle.is-ne { top: -6px; right: -6px; cursor: nesw-resize; }
.visual-transform-handle.is-sw { bottom: -6px; left: -6px; cursor: nesw-resize; }
.visual-transform-handle.is-se { right: -6px; bottom: -6px; cursor: nwse-resize; }
.visual-transform-handle.is-n { top: -6px; left: calc(50% - 6px); cursor: ns-resize; }
.visual-transform-handle.is-e { top: calc(50% - 6px); right: -6px; cursor: ew-resize; }
.visual-transform-handle.is-s { bottom: -6px; left: calc(50% - 6px); cursor: ns-resize; }
.visual-transform-handle.is-w { top: calc(50% - 6px); left: -6px; cursor: ew-resize; }
.visual-transform-rotate { top: -34px; left: calc(50% - 6px); border-radius: 50%; background: #58a6ff; cursor: grab; }
.visual-transform-rotate::after { position: absolute; top: 10px; left: 4px; width: 2px; height: 22px; background: #58a6ff; content: ""; }
.visual-overlay-layer {
position: absolute;
transform-origin: center;
cursor: move;
touch-action: none;
}
.visual-overlay-layer > img,
.visual-overlay-layer > video { display: block; width: 100%; height: 100%; object-fit: contain; background: transparent; pointer-events: none; }
.visual-overlay-layer.is-selected { border: 1.5px solid #58a6ff; box-shadow: 0 0 0 1px rgba(5,10,18,.82), 0 0 18px rgba(46,143,255,.18); }
.visual-overlay-order-actions { position: absolute; top: -26px; right: 0; display: flex; gap: 3px; }
.visual-overlay-order-actions button { display: grid; place-items: center; width: 22px; height: 20px; border: 1px solid rgba(88,166,255,.7); border-radius: 4px; padding: 0; color: #eaf4ff; background: #162536; cursor: pointer; }
.visual-snap-guide { position: absolute; z-index: 30; pointer-events: none; background: #ff4fa3; box-shadow: 0 0 0 1px rgba(6,10,16,.7); }
.visual-snap-guide.is-center-x, .visual-snap-guide.is-left, .visual-snap-guide.is-right { top: 0; bottom: 0; width: 1px; }
.visual-snap-guide.is-center-x { left: 50%; }
.visual-snap-guide.is-left { left: 0; }
.visual-snap-guide.is-right { right: 0; }
.visual-snap-guide.is-center-y, .visual-snap-guide.is-top, .visual-snap-guide.is-bottom { right: 0; left: 0; height: 1px; }
.visual-snap-guide.is-center-y { top: 50%; }
.visual-snap-guide.is-top { top: 0; }
.visual-snap-guide.is-bottom { bottom: 0; }
.visual-overlay-track { position: relative; min-width: 0; border-bottom: 1px solid rgba(255,255,255,.045); background: rgba(88,166,255,.025); }
.visual-overlay-track.is-selected { background: rgba(88,166,255,.07); }
.visual-overlay-clip { position: absolute; top: 5px; left: var(--overlay-left); width: var(--overlay-width); height: 38px; overflow: hidden; border: 1px solid rgba(88,166,255,.5); border-radius: 5px; padding: 0; background: #162231; color: #eaf4ff; text-align: left; cursor: pointer; }
.visual-overlay-drop-preview { position: absolute; top: 5px; left: var(--overlay-left); width: var(--overlay-width); height: 38px; min-width: 18px; display: grid; place-items: center; overflow: hidden; border: 1px dashed rgba(83,166,255,.96); border-radius: 5px; color: #dcecff; font-size: 10px; font-weight: 700; background: repeating-linear-gradient(-45deg,rgba(83,166,255,.24) 0 8px,rgba(83,166,255,.08) 8px 16px); box-shadow: inset 0 0 0 1px rgba(83,166,255,.16),0 0 18px rgba(50,132,255,.2); pointer-events: none; }
.visual-overlay-drop-preview span { overflow: hidden; padding: 0 6px; text-overflow: ellipsis; white-space: nowrap; }
.visual-overlay-thumbnails { position: absolute; inset: 0; display: flex; overflow: hidden; opacity: .72; }
.visual-overlay-thumbnails > img, .visual-overlay-thumbnails > video { flex: 1 0 auto; min-width: 42px; height: 100%; object-fit: cover; }
.visual-overlay-clip > span { position: absolute; right: 6px; bottom: 4px; left: 6px; z-index: 2; overflow: hidden; font-size: 10px; font-weight: 650; text-overflow: ellipsis; white-space: nowrap; text-shadow: 0 1px 3px rgba(0,0,0,.9); }
.visual-overlay-clip.is-video > span { left: 31px; }
.visual-overlay-clip.is-current { border-color: #35ead9; }
.visual-overlay-clip.is-selected-segment { border-color: #58a6ff; box-shadow: 0 0 0 2px rgba(88,166,255,.28), 0 0 14px rgba(88,166,255,.25); filter: brightness(1.12); }
.clip-mute-toggle { position: absolute; top: 4px; left: 4px; z-index: 5; display: grid; place-items: center; width: 22px; height: 22px; border: 1px solid rgba(255,255,255,.18); border-radius: 5px; padding: 0; color: #eef8fb; background: rgba(5,10,14,.78); cursor: pointer; }
.clip-mute-toggle:hover { color: #071616; background: #35ead9; }
.visual-overlay-resize { position: absolute; top: 4px; bottom: 4px; width: 6px; border-radius: 3px; background: rgba(232,244,255,.9); opacity: 0; cursor: ew-resize; }
.visual-overlay-resize.is-start { left: 2px; }
.visual-overlay-resize.is-end { right: 2px; }
.visual-overlay-clip.is-selected-segment .visual-overlay-resize { opacity: 1; }
.visual-overlay-inspector { display: grid; gap: 12px; }
.visual-overlay-inspector label { display: grid; grid-template-columns: minmax(0,1fr) 82px; align-items: center; gap: 10px; color: #9ba8b5; font-size: 12px; }
.visual-overlay-inspector input { width: 100%; min-width: 0; border: 1px solid rgba(255,255,255,.09); border-radius: 6px; padding: 7px 8px; color: #eef5f7; background: #11161d; }
.visual-overlay-inspector .sticker-properties-preview video { width: 100%; height: 92px; object-fit: contain; }
.visual-overlay-delete { justify-self: end; color: #ff8e96; }
.visual-overlay-presets { display: grid; gap: 8px; }
.visual-overlay-presets > strong { color: #c9d4de; font-size: 12px; }
.visual-overlay-presets > div { display: grid; grid-template-columns: repeat(6,1fr); gap: 5px; }
.visual-overlay-presets button { height: 32px; border: 1px solid rgba(255,255,255,.08); border-radius: 6px; padding: 0; color: #c8d8e7; background: #121a23; cursor: pointer; }
.visual-overlay-presets button:hover { border-color: #58a6ff; color: #fff; background: rgba(88,166,255,.12); }
.panel-title-row > *, .tool-panel button, .voice-panel button { min-width: 0; }
.tool-panel button, .voice-panel button { text-wrap: balance; }
.visual-media-layer > img,
.visual-media-layer > video {
grid-area: 1 / 1;
@@ -2808,6 +2958,31 @@ button:disabled {
pointer-events: none;
}
.caption-canvas-guide {
position: absolute;
z-index: 5;
display: none;
pointer-events: none;
background: #31ead7;
box-shadow: 0 0 10px rgba(49, 234, 215, 0.55);
}
.preview-frame[data-caption-guide-x] .caption-canvas-guide.is-vertical {
top: 0;
bottom: 0;
left: var(--caption-guide-x);
display: block;
width: 1px;
}
.preview-frame[data-caption-guide-y] .caption-canvas-guide.is-horizontal {
right: 0;
left: 0;
top: var(--caption-guide-y);
display: block;
height: 1px;
}
.caption-overlay:hover,
.caption-overlay:focus-visible {
outline: 2px solid rgba(53, 234, 217, 0.64);
@@ -3647,6 +3822,7 @@ button:disabled {
.timeline-board {
display: grid;
grid-template-columns: 164px minmax(0, 1fr);
grid-template-rows: 28px auto;
min-height: 0;
max-height: min(430px, 48vh);
overflow-y: auto;
@@ -3661,10 +3837,36 @@ button:disabled {
.track-labels {
display: grid;
grid-template-rows: repeat(5, 48px);
padding-top: 28px;
border-right: 1px solid rgba(255, 255, 255, 0.07);
}
.track-labels-ruler-spacer {
position: sticky;
top: 0;
z-index: 8;
min-height: 28px;
border-bottom: 1px solid rgba(255, 255, 255, 0.035);
padding: 0;
background: #10141a;
}
.timeline-ruler-viewport {
position: sticky;
top: 0;
z-index: 8;
min-width: 0;
overflow: hidden;
padding: 0 18px 0 8px;
background: #10141a;
}
.timeline-ruler-canvas {
position: relative;
height: 28px;
min-width: 25%;
transition: width 140ms cubic-bezier(0.16, 1, 0.3, 1);
}
.track-labels div {
display: flex;
align-items: center;
@@ -3745,7 +3947,8 @@ button:disabled {
.track-scroll {
position: relative;
display: grid;
grid-template-rows: 28px repeat(5, 48px);
grid-template-rows: repeat(5, 48px);
min-height: 100%;
min-width: 25%;
transition: width 140ms cubic-bezier(0.16, 1, 0.3, 1);
}
@@ -3762,6 +3965,30 @@ button:disabled {
font-variant-numeric: tabular-nums;
cursor: ew-resize;
touch-action: none;
background: #10141a;
}
.playhead-ruler {
position: absolute;
top: 0;
bottom: 0;
z-index: 9;
width: 2px;
background: #f4fbff;
cursor: ew-resize;
touch-action: none;
}
.playhead-ruler::after {
position: absolute;
right: 50%;
bottom: 0;
width: 18px;
height: 10px;
background: #f4fbff;
clip-path: polygon(0 0, 100% 0, 50% 100%);
transform: translateX(50%);
content: "";
}
.ruler::after {
@@ -3813,20 +4040,12 @@ button:disabled {
}
.playhead::before {
position: absolute;
top: 27px;
left: 50%;
width: 13px;
height: 13px;
border-radius: 3px;
background: #f4fbff;
transform: translateX(-50%) rotate(45deg);
content: "";
display: none;
}
.snap-guide {
position: absolute;
top: 26px;
top: 0;
bottom: 12px;
z-index: 6;
width: 2px;
@@ -3893,6 +4112,29 @@ button:disabled {
padding: 4px 0;
}
.main-track-drop-preview {
position: absolute;
top: 4px;
bottom: 4px;
left: var(--main-drop-left);
z-index: 10;
display: grid;
place-items: center;
width: var(--main-drop-width);
min-width: 22px;
overflow: hidden;
border: 1px dashed rgba(53, 234, 217, 0.98);
border-radius: 5px;
color: #c9fffa;
font-size: 10px;
font-weight: 800;
background: repeating-linear-gradient(-45deg, rgba(53,234,217,.25) 0 8px, rgba(53,234,217,.07) 8px 16px);
box-shadow: 0 0 18px rgba(53,234,217,.24);
pointer-events: none;
}
.main-track-drop-preview span { overflow: hidden; padding: 0 6px; text-overflow: ellipsis; white-space: nowrap; }
.visual-junction {
position: absolute;
top: 27px;
@@ -4116,6 +4358,10 @@ button:disabled {
0 0 0 1px rgba(53, 234, 217, 0.16);
}
.image-clip.is-overlay-promotion-insert-target {
margin-left: var(--promotion-gap-width, 0%);
}
.image-clip-duration {
position: absolute;
right: 12px;
@@ -4479,6 +4725,21 @@ button:disabled {
padding: 4px 0;
}
.source-audio-extraction-state {
display: flex;
align-items: center;
gap: 8px;
margin-left: 12px;
color: #ffd45f;
font-size: 12px;
font-weight: 700;
white-space: nowrap;
}
.source-audio-extraction-state svg {
animation: timeline-context-spin 0.8s linear infinite;
}
.audio-clip {
position: relative;
min-width: 0;
@@ -4659,6 +4920,17 @@ button:disabled {
text-overflow: ellipsis;
white-space: nowrap;
}
.asset-drop-slot span { display: flex; align-items: center; gap: 4px; }
.asset-drop-slot.mode-overlay {
height: 38px;
border-color: rgba(83,166,255,.92);
color: #d9ebff;
background: repeating-linear-gradient(-45deg,rgba(83,166,255,.22) 0 8px,rgba(83,166,255,.07) 8px 16px),rgba(8,19,34,.9);
box-shadow: inset 0 0 0 1px rgba(83,166,255,.22),0 0 20px rgba(50,132,255,.2);
}
.asset-drop-slot.mode-overlay strong { color: #78b8ff; }
.image-track.is-drop-overlay { background: linear-gradient(180deg,rgba(68,144,255,.16),rgba(68,144,255,.035)); box-shadow: inset 0 0 0 1px rgba(88,166,255,.56),inset 0 0 24px rgba(88,166,255,.1); }
.image-track.is-drop-image .asset-drop-slot { border-style: solid; }
.asset-drop-slot::after {
position: absolute;