diff --git a/README.md b/README.md index f8b6f0e..2274332 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/README.zh-CN.md b/README.zh-CN.md index bb51e15..31f5195 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -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) diff --git a/docs/screenshots/drop-intent-comparison.png b/docs/screenshots/drop-intent-comparison.png new file mode 100644 index 0000000..05076d1 Binary files /dev/null and b/docs/screenshots/drop-intent-comparison.png differ diff --git a/docs/screenshots/drop-intent-hover.png b/docs/screenshots/drop-intent-hover.png new file mode 100644 index 0000000..3ec2db9 Binary files /dev/null and b/docs/screenshots/drop-intent-hover.png differ diff --git a/docs/screenshots/drop-intent-implementation.png b/docs/screenshots/drop-intent-implementation.png new file mode 100644 index 0000000..14a8d80 Binary files /dev/null and b/docs/screenshots/drop-intent-implementation.png differ diff --git a/e2e/embedded-source-audio-export.spec.js b/e2e/embedded-source-audio-export.spec.js new file mode 100644 index 0000000..9afc2ed --- /dev/null +++ b/e2e/embedded-source-audio-export.spec.js @@ -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); +}); diff --git a/e2e/offline-export.spec.js b/e2e/offline-export.spec.js index a1eefe4..f50049f 100644 --- a/e2e/offline-export.spec.js +++ b/e2e/offline-export.spec.js @@ -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); }); diff --git a/package-lock.json b/package-lock.json index e37c1bf..8e7cfb3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index a0fdafd..0a66ec5 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/skills/edit-timeline-studio/SKILL.md b/skills/edit-timeline-studio/SKILL.md new file mode 100644 index 0000000..a10c3e3 --- /dev/null +++ b/skills/edit-timeline-studio/SKILL.md @@ -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 `. + +### 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. diff --git a/skills/edit-timeline-studio/agents/openai.yaml b/skills/edit-timeline-studio/agents/openai.yaml new file mode 100644 index 0000000..4412e47 --- /dev/null +++ b/skills/edit-timeline-studio/agents/openai.yaml @@ -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." diff --git a/skills/edit-timeline-studio/references/command-contract.md b/skills/edit-timeline-studio/references/command-contract.md new file mode 100644 index 0000000..991619c --- /dev/null +++ b/skills/edit-timeline-studio/references/command-contract.md @@ -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. diff --git a/skills/edit-timeline-studio/references/current-capabilities.md b/skills/edit-timeline-studio/references/current-capabilities.md new file mode 100644 index 0000000..2fa3474 --- /dev/null +++ b/skills/edit-timeline-studio/references/current-capabilities.md @@ -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. diff --git a/skills/edit-timeline-studio/scripts/validate_edit_plan.mjs b/skills/edit-timeline-studio/scripts/validate_edit_plan.mjs new file mode 100755 index 0000000..ad68dc5 --- /dev/null +++ b/skills/edit-timeline-studio/scripts/validate_edit_plan.mjs @@ -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 "); + 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}`); diff --git a/src/App.jsx b/src/App.jsx index 55a6772..9795b4b 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -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 })); + })} /> setVisualOverlaySegments((items) => items.map((item) => item.id === selectedVisualOverlayId ? { ...item, ...patch } : item))} + deleteVisualOverlay={() => handleDeleteTrack()} + applyVisualOverlayPreset={(id) => { + const preset = getVisualOverlayPreset(id); + if (preset) updateSelectedVisualOverlay(preset); + }} /> @@ -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} diff --git a/src/components/PreviewStage.jsx b/src/components/PreviewStage.jsx index 3ec9032..80f23b5 100644 --- a/src/components/PreviewStage.jsx +++ b/src/components/PreviewStage.jsx @@ -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 ( -
+ 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 = ( +
+ {isFocusPreviewOpen ?
+
{t("focusPreviewTitle", "大画布编辑")}{t("focusPreviewHint", "点击画面元素进行移动、缩放和旋转")}
+ setIsFocusPreviewOpen(false)}> +
: null}
{ + 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 ? ( -
+ ) : null} {previewTransition?.next?.src && trackVisibility.image ? (
{previewTransition.next.type === "video" ? ( @@ -290,6 +465,33 @@ export function PreviewStage({ {previewTransition.id === "flash" ? : null}
) : 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
startOverlayTransform(event, "move", overlay)}> + {overlay.type === "video" ?
; + })} + {overlaySnapGuides.map((guide) =>
)} {showVisionOverlays ? visionOverlayBoxes.map((detection, index) => (
startCaptionDrag(event, caption.id)} onDoubleClick={() => setActiveTool("caption")} /> @@ -408,11 +610,18 @@ export function PreviewStage({ > {fitMode === "contain" ? t("fit") : t("cover")} - document.documentElement.requestFullscreen?.()}> + setIsFocusPreviewOpen((open) => !open)}>
); + if (isFocusPreviewOpen && typeof document !== "undefined") { + return createPortal(<> + : null} + {segment.name || t("overlayTrack", "Overlay")} + startOverlayEdit(event, "resize-start")} /> + startOverlayEdit(event, "resize-end")} /> + ; + })} + {laneIndex === 0 && activeTimelineClipDrag?.track === "image" && activeTimelineClipDrag.mode === "overlay" && draggingVisualSegment ? ( +
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}%`, + }} + > + {t("dropAsOverlay", "作为画中画")} +
+ ) : null} + {!lane.length ?
{t("dropAsOverlay", "作为画中画")}
: null} + {renderAssetDropSlot("overlay")} + + ); + }; return (
@@ -737,6 +906,31 @@ export function Timeline({
+